Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96cc57ae06 | ||
|
|
f37a92c240 | ||
|
|
fe45ec0f76 | ||
|
|
d01b6dcaa3 | ||
|
|
4e8aa15b71 | ||
|
|
370d8e7769 | ||
|
|
be4db68550 | ||
|
|
c95e593cf1 | ||
|
|
9ed53aa4bc | ||
|
|
4d9b3c0b02 | ||
|
|
605495fd53 | ||
|
|
eb992a47b7 | ||
|
|
2a36e28f74 | ||
|
|
e82a87d104 | ||
|
|
f408076187 | ||
|
|
7610b34621 | ||
|
|
6595ed0dfc | ||
|
|
f71abdd000 | ||
|
|
9bba684fb2 |
@@ -0,0 +1,4 @@
|
||||
# 行尾规范:文本文件统一 LF,Windows 批处理保留 CRLF
|
||||
* text=auto eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
@@ -76,14 +76,21 @@ lpt-fe/src/
|
||||
|
||||
## 前端代码标准
|
||||
|
||||
### 交互防抖与加载原则
|
||||
|
||||
- 点击后需要跳转到其他页面时,应立刻执行跳转,不要在跳转前等待接口返回;目标页面在数据未加载完成时必须展示页面级 loading。
|
||||
- 点击后不跳转页面时,触发接口的按钮必须自身展示 loading 或在请求期间禁用,防止网络慢时被多次触发。
|
||||
- 登录、创建/更新、结束会话等必须确认后端成功的操作属于例外:按钮先进入 loading,成功后再跳转。
|
||||
- 同一异步动作执行期间必须通过 loading 或 disabled 阻止重复触发,不能只依赖路由跳转后的页面卸载。
|
||||
|
||||
### 按钮规范
|
||||
|
||||
- 页面主操作 / 卡片 CTA:`size="large"`,如 Study 开始任务、TaskForm 保存、Welcome 快速入口。
|
||||
- 区块工具栏 / 页内操作:默认尺寸,如 Review 刷新、ReviewRecall 面板操作、历史记录。
|
||||
- 表格/列表行内操作:`size="small" text`,如 查看记录、回忆复习、编辑、删除。
|
||||
- 表格/列表行内操作:`size="small"`,主操作实底 `type="success"`,次操作 `text`;如 Review 卡片中「回忆复习」为主、「查看记录」为次。
|
||||
- 弹窗 footer:默认尺寸;确认按钮 `type="success"`,取消按钮默认;危险操作统一 `type="danger"`。
|
||||
- 正向/保存语义统一 `success`,次级编辑语义可用 `primary`,不要在同一功能上混用。
|
||||
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css` 的 `.action-row / .edit-actions / .fragment-edit-actions`。
|
||||
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css` 的 `.action-row / .edit-actions / .fragment-edit-actions / .task-actions`;`.task-actions` 中主操作在上、次操作在下(如 Review 的回忆复习/查看记录)。
|
||||
|
||||
### 移动端适配
|
||||
|
||||
@@ -97,10 +104,17 @@ lpt-fe/src/
|
||||
|
||||
- Markdown 渲染统一使用 `src/utils/markdown.ts` 的 `renderMarkdown`,禁止在组件内复制实现。
|
||||
- 应用场景状态常量统一使用 `src/utils/taskApplication.ts` 的 `applicationStatusOptions`。
|
||||
- 用户可见错误提示必须口语化、可理解,不要直接展示接口原始 message、JSON、参数名或“服务器返回”等技术信息;技术细节留在日志。
|
||||
- 不保留无消费者代码:未使用的 import、prop、事件、API 封装、CSS class、组件文件与依赖应及时删除。
|
||||
- 组件公开 props/events 只在有实际消费者时保留,例如 MindMapViewer 通过 `toOutline()` 导出编辑内容,不依赖无人监听的 change 事件。
|
||||
- Vite 模板遗留文件(示例组件、icon、logo)不进入业务代码。
|
||||
|
||||
### 测试规范
|
||||
|
||||
- 单元测试必须直接测试真实代码:直接调用 composable、挂载真实组件、使用真实路由;禁止把组件或 composable 的逻辑复制到测试里再自测。
|
||||
- 测试中可以 mock 外部依赖(API、Element Plus 服务、Audio 等),但被测逻辑本身必须来自生产模块。
|
||||
- `script setup` 内部状态需要测试访问时,通过 `defineExpose` 暴露,而不是在测试里重写一份相同逻辑。
|
||||
|
||||
### 提交前检查
|
||||
|
||||
- 运行 `npx vue-tsc --noEmit`、`npm run test`、`npm run build`。
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
# 部署流水线问题排查进度
|
||||
|
||||
**日期**: 2026-07-20(更新)
|
||||
|
||||
## 当前部署方式
|
||||
|
||||
- **Jenkinsfile / Jenkinsfile-dev**:历史方案,已不再作为主路径
|
||||
- **现行方案**:Gitea Actions(`.gitea/workflows/deploy.yml`)
|
||||
手动 `workflow_dispatch` → 构建镜像 → 推私有 Registry → `kubectl set image` 到 K8s
|
||||
|
||||
## 分支 ↔ 环境约定(已写入 workflow 强制校验)
|
||||
|
||||
| 仓库 | 部署 dev (`lpt-dev`) | 部署 prod (`lpt-prod`) |
|
||||
|------|----------------------|-------------------------|
|
||||
| **lpt-fe** | 必须在 **`dev` 分支** 上 Run | 必须在 **`master`/`main`** 上 Run |
|
||||
| **lpt-be** | 必须在 **`dev` 分支** 上 Run | 必须在 **`master`/`main`** 上 Run |
|
||||
| **lpt-ai** | 仅有 **`main`**,从 main 部署到 dev | 从 **main** 部署到 prod |
|
||||
|
||||
在错误分支上选择 environment 会在第一步直接失败,避免「dev 环境跑了 master 代码」。
|
||||
|
||||
### 正确操作
|
||||
|
||||
1. Gitea 仓库页面切换到目标分支(fe/be 的 dev 或 master)
|
||||
2. Actions → 对应 workflow → Run workflow
|
||||
3. 选择 `environment` = `dev` 或 `prod`(须与当前分支匹配)
|
||||
|
||||
## 已修复项(2026-07-20)
|
||||
|
||||
1. **分支与环境绑定校验** — 三个仓库的 `deploy.yml` 增加 Validate 步骤
|
||||
2. **`IMAGE_TAG` 持久化** — 除 `GITHUB_ENV` 外,写入 `GITEA_ENV`(若存在)+ 临时文件兜底,Deploy 步读取失败则明确报错
|
||||
3. **fe `BUILD_MODE`** — 在 shell 内根据 environment 设置 `production` / `development`,避免表达式兼容问题
|
||||
4. **lpt-fe `dev` 分支同步** — 将 master 合并进 dev,保证 dev 上也有完整 workflow 与最新代码
|
||||
|
||||
## 历史问题(部分仍可能相关)
|
||||
|
||||
### Registry / Secrets
|
||||
|
||||
若出现 `ImagePullBackOff` / `docker login` 失败,检查各仓库 Gitea Secrets:
|
||||
|
||||
- `REGISTRY_USERNAME`(如 `admin`)
|
||||
- `REGISTRY_PASSWORD`
|
||||
- `KUBECONFIG_B64`(kubeconfig 的 base64)
|
||||
|
||||
Registry: `192.168.123.199:5000`
|
||||
|
||||
### K8s
|
||||
|
||||
- 共享清单:`k8s/dev/*`、`k8s/prod/*`(按环境)
|
||||
- 各服务仓库内 `k8s/` 仍多为 `lpt-dev` 模板;日常 CI 只 `set image`,不 `apply` 整份 YAML
|
||||
- Deployment 需有 `imagePullSecrets: [regcred]`;workflow 每次会 create/update `regcred`
|
||||
|
||||
## 镜像与命名空间
|
||||
|
||||
| environment | 镜像 tag(浮动) | 不可变 tag | namespace |
|
||||
|-------------|------------------|------------|-----------|
|
||||
| dev | `app:dev` | `app:<sha>-<unix>` | `lpt-dev` |
|
||||
| prod | `app:prod` | `app:<sha>-<unix>` | `lpt-prod` |
|
||||
|
||||
部署使用不可变 tag,避免 `imagePullPolicy` 与缓存导致未更新。
|
||||
|
||||
## 验证清单
|
||||
|
||||
1. [ ] 三仓库 Secrets 已配置
|
||||
2. [ ] lpt-fe:在 **dev** 分支 Run → environment=dev 成功
|
||||
3. [ ] lpt-fe:在 **master** 上选 environment=dev 应 **失败**(校验)
|
||||
4. [ ] lpt-be:同上
|
||||
5. [ ] lpt-ai:在 **main** 上 Run → dev / prod
|
||||
6. [ ] `kubectl get pods -n lpt-dev` / `lpt-prod` 正常
|
||||
|
||||
---
|
||||
|
||||
**备注**: 主路径为 Gitea Actions + K8s;Jenkins 配置可保留作参考,勿与现行流程混用。
|
||||
@@ -1,413 +0,0 @@
|
||||
# LPT 复习流程设计文档
|
||||
|
||||
> 本文档描述 LPT 系统中「回忆复习」(Recall Review)功能的完整设计,包括数据模型、API、前端交互流程和三种入口的处理方式。
|
||||
|
||||
---
|
||||
|
||||
## 1. 核心概念
|
||||
|
||||
### 1.1 标准思维导图(Standard Mind Map)
|
||||
|
||||
- **任务级单一知识树**:每个学习任务有且仅有一棵标准思维导图,存储在 `review_standard_mind_maps` 表
|
||||
- **生成方式**:
|
||||
- `BUILTIN`:内置规则引擎,按 session 分组、去重、合并
|
||||
- `AI`:调用 lpt-ai 服务生成缩进大纲后解析
|
||||
- `USER`:用户手动编辑
|
||||
- `USER_MERGE`:增量合并后(保留用户编辑 + 追加 AI 新节点)
|
||||
- **数据结构**:`content` 字段存储 JSON 树(递归 `MindMapNode`),`outline` 字段存储缩进大纲文本
|
||||
- **节点模型**:
|
||||
```
|
||||
MindMapNode {
|
||||
title: string // 节点标题
|
||||
notes?: string // 备注 / 对比标记(MATCHED| / MISSED|)
|
||||
sourceType?: string // REPORT | FRAGMENT | APPLICATION
|
||||
sourceId?: number // 对应源数据主键
|
||||
children?: MindMapNode[]
|
||||
}
|
||||
```
|
||||
- **节点标记约定**(用于对比着色):
|
||||
- `notes` 以 `MATCHED|` 开头 → 绿色(回忆命中)
|
||||
- `notes` 以 `MISSED|` 开头 → 红色(回忆遗漏)
|
||||
- 无标记 → 默认色(未参与对比)
|
||||
|
||||
### 1.2 回忆对比记录(Recall Record)
|
||||
|
||||
- 每次用户提交回忆 → 生成一条 `review_recall_records` 记录
|
||||
- 核心字段:
|
||||
- `task_num`:关联任务
|
||||
- `standard_map_id`:对比时使用的标准导图版本
|
||||
- `focus_path`:复习起点节点路径(`"根 / 分支A / 子节点B"`),null 为全量
|
||||
- `recall_content`:用户回忆大纲文本
|
||||
- `compare_result`:对比结果 JSON(含 `matchedTree`、`extraNodes`、覆盖率等)
|
||||
- `recall_ratio` / `matched_count` / `missed_count` / `extra_count`:统计摘要
|
||||
|
||||
---
|
||||
|
||||
## 2. 复习流程
|
||||
|
||||
### 2.1 核心逻辑
|
||||
|
||||
```
|
||||
1. 确定复习起点(节点路径)
|
||||
2. 获取标准导图
|
||||
3. 按起点提取子树作为对比基准
|
||||
4. 用户在大纲编辑器中回忆填充
|
||||
5. 提交对比(AI 语义匹配 或 BUILTIN 字符串匹配)
|
||||
6. 展示对比结果(着色 + 统计)
|
||||
```
|
||||
|
||||
### 2.2 节点选择
|
||||
|
||||
- 用户在标准导图上点击节点 → `MindMapViewer` 发射 `node-select` 事件(含 `title`、`path`、`childCount`)
|
||||
- 弹窗确认:「以「节点名」为起点,复习其下 N 个子知识点?」
|
||||
- 确认后:
|
||||
- `focusPath` = 选中节点的路径(如 `"Java基础 / 集合 / HashMap"`)
|
||||
- `recallTree` 根节点标题 = 选中节点标题
|
||||
- 回忆导图以该标题为根,用户补充子节点
|
||||
|
||||
### 2.3 对比范围
|
||||
|
||||
- **有 `focusPath`**:`MindMapTreeTool.extractSubtree(root, focusPath)` 提取子树,对比基准 = 子树
|
||||
- **无 `focusPath`**:对比基准 = 整棵标准导图
|
||||
- AI 对比:发给 lpt-ai 的 outline 只包含子树范围
|
||||
- BUILTIN 对比:`compareTrees()` 在子树范围内做标题匹配
|
||||
|
||||
### 2.4 对比算法
|
||||
|
||||
**AI 语义匹配(优先):**
|
||||
```
|
||||
POST /ai/tasks → type: "compare-recall"
|
||||
→ 异步轮询结果
|
||||
→ 返回 { matches: [{standardTitle, recallTitle}], missedTitles, extraNodes, evaluation }
|
||||
→ Java 端 buildCompareResultFromAI() 标注标准树
|
||||
```
|
||||
|
||||
**BUILTIN 字符串匹配(降级):**
|
||||
- 展平标准树和回忆树
|
||||
- 标题标准化(去标点、去空格、转小写)
|
||||
- 精确匹配 → 模糊匹配(bigram Jaccard ≥ 0.6)
|
||||
- 标记 MATCHED / MISSED / 额外
|
||||
|
||||
### 2.5 结果展示
|
||||
|
||||
- 标准导图面板直接显示着色对比结果(不再有独立对比面板)
|
||||
- 绿色(`#c8e6c9`)= 命中,红色(`#ffcdd2`)= 遗漏
|
||||
- 统计卡片:覆盖率、命中/遗漏/额外计数
|
||||
- 遗漏项列表 + 额外项列表(可点击回看原文)
|
||||
|
||||
---
|
||||
|
||||
## 3. 三个复习入口
|
||||
|
||||
### 入口 A:复习总览 → "回忆复习"
|
||||
|
||||
**路径:** `Welcome.vue` → "复习回看" → `Review.vue`(任务列表)→ 每行"回忆复习"按钮
|
||||
|
||||
**前端代码:** `Review.vue:110`
|
||||
```typescript
|
||||
router.push(`/review/recall/${row.taskNum}`)
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. 跳转到 `ReviewRecall.vue`,URL 为 `/review/recall/:taskNum`
|
||||
2. 页面加载 → `loadData()` 获取标准导图
|
||||
3. 标准导图 `selectable=true`,显示提示「点击导图节点选择复习起点」
|
||||
4. 用户点击节点 → 弹窗确认 → 进入回忆模式
|
||||
5. 回忆填充 → 提交对比 → 展示结果
|
||||
|
||||
**相关文件:**
|
||||
- `lpt-fe/src/components/Review.vue`
|
||||
- `lpt-fe/src/components/ReviewRecall.vue`
|
||||
|
||||
### 入口 B:从某个残片/报告详情 → "回忆复习"
|
||||
|
||||
**路径:** `Welcome.vue` 滚动回顾 → 点击卡片 → `ReviewDetail.vue` → "回忆复习"按钮
|
||||
|
||||
**前端代码:** `ReviewDetail.vue` 的 `goToRecall()`
|
||||
```typescript
|
||||
const res = await findNode(taskNum, content.substring(0, 500));
|
||||
if (res?.data?.path) {
|
||||
router.push(`/review/recall/${taskNum}?focusPath=${encodeURIComponent(res.data.path)}`);
|
||||
}
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. 用户在详情页查看某个残片/报告的内容
|
||||
2. 点击"回忆复习" → 前端调 `POST /review/standard-mind-map/{taskNum}/find-node`
|
||||
3. 后端 `findClosestNode()` 用 bigram Jaccard 匹配最接近的节点
|
||||
4. 返回 `{ path, nodeTitle, score }`
|
||||
5. 跳转到 `/review/recall/:taskNum?focusPath=...`
|
||||
6. `ReviewRecall.vue` 检测到 URL 参数 → 跳过节点选择,直接进入回忆模式
|
||||
|
||||
**后端 API:**
|
||||
```http
|
||||
POST /review/standard-mind-map/{taskNum}/find-node
|
||||
Content-Type: application/json
|
||||
|
||||
{ "content": "用户查看的残片/报告文本" }
|
||||
|
||||
→ 200 OK
|
||||
{ "code": 200, "data": { "path": "根 / 分支A / 子节点B", "nodeTitle": "子节点B", "score": 0.85 } }
|
||||
```
|
||||
|
||||
**匹配算法(`MindMapTreeTool.findClosestNode`):**
|
||||
1. 展平标准导图所有节点
|
||||
2. 对每个节点,计算其 `title` 与输入文本的 bigram Jaccard 相似度
|
||||
3. `notes` 字段也参与匹配(权重 0.5)
|
||||
4. 返回得分最高(>0.1)的节点
|
||||
|
||||
**相关文件:**
|
||||
- `lpt-fe/src/components/ReviewDetail.vue`
|
||||
- `learning-progress-tracker/.../utils/MindMapTreeTool.java`(`findClosestNode`、`similarityScore`)
|
||||
|
||||
### 入口 C:首页欢迎页 → 回忆卡片 → "前往回忆复习"
|
||||
|
||||
**路径:** `Welcome.vue` → 滚动回顾标签 → 点击弹出回忆对话框 → "前往回忆复习"按钮
|
||||
|
||||
**前端代码:** `Welcome.vue` 的 `goToRecallFromCard()`
|
||||
```typescript
|
||||
const tn = group.taskNum;
|
||||
const res = await findNode(tn, content.substring(0, 500));
|
||||
if (res?.data?.path) {
|
||||
router.push(`/review/recall/${tn}?focusPath=${encodeURIComponent(res.data.path)}`);
|
||||
}
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. Welcome 页加载 `GET /review/feed` 获取复习 feed
|
||||
2. 按 session 分组为标签卡片
|
||||
3. 用户点击某个标签 → 弹出回忆对话框(先回忆→展开对照)
|
||||
4. 点击"前往回忆复习" → 同入口 B,先调 findNode 再跳转
|
||||
|
||||
**相关文件:**
|
||||
- `lpt-fe/src/components/Welcome.vue`
|
||||
|
||||
---
|
||||
|
||||
## 4. 关键 API 清单
|
||||
|
||||
### 4.1 标准思维导图
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| `GET` | `/review/standard-mind-map/{taskNum}` | 获取/自动生成标准导图 |
|
||||
| `POST` | `/review/standard-mind-map/{taskNum}/regenerate?mode=full\|incremental` | 重新生成 |
|
||||
| `PUT` | `/review/standard-mind-map/{taskNum}` | 用户编辑(大纲文本) |
|
||||
| `POST` | `/review/standard-mind-map/{taskNum}/recall` | 提交回忆对比 |
|
||||
| `POST` | `/review/standard-mind-map/{taskNum}/find-node` | 匹配最近节点 |
|
||||
| `GET` | `/review/standard-mind-map/{taskNum}/recall-records` | 历史回忆记录 |
|
||||
|
||||
### 4.2 回忆对比请求体
|
||||
|
||||
```json
|
||||
{
|
||||
"recallOutline": "用户回忆的缩进大纲文本\n - 子节点1\n - 子节点2",
|
||||
"focusPath": "根标题 / 分支A / 子节点B"
|
||||
}
|
||||
```
|
||||
|
||||
- `recallOutline`:必填,用户回忆的缩进大纲
|
||||
- `focusPath`:可选,复习起点节点路径。null = 全量,提供时对比范围为该子树
|
||||
|
||||
### 4.3 对比结果结构(CompareResult)
|
||||
|
||||
```json
|
||||
{
|
||||
"matchedTree": {
|
||||
"title": "根节点",
|
||||
"notes": "",
|
||||
"children": [
|
||||
{
|
||||
"title": "命中的知识点",
|
||||
"notes": "MATCHED|完整原文内容",
|
||||
"sourceType": "REPORT",
|
||||
"sourceId": 1,
|
||||
"children": []
|
||||
},
|
||||
{
|
||||
"title": "遗漏的知识点",
|
||||
"notes": "MISSED|完整原文内容",
|
||||
"sourceType": "FRAGMENT",
|
||||
"sourceId": 2,
|
||||
"children": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"extraNodes": [
|
||||
{ "title": "用户额外回忆的知识", "path": "/额外/..." }
|
||||
],
|
||||
"recallRatio": 0.75,
|
||||
"matchedCount": 3,
|
||||
"missedCount": 1,
|
||||
"extraCount": 1,
|
||||
"evaluation": "AI 评价文本(仅 AI 对比时有值)"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 前端组件结构
|
||||
|
||||
```
|
||||
ReviewRecall.vue(主页面)
|
||||
├── Page header(返回、标题、历史记录按钮)
|
||||
├── 复习起点指示(focusPath 显示 + 重选按钮)
|
||||
├── 节点选择确认弹窗(el-dialog)
|
||||
├── 统计卡片(覆盖率/命中/遗漏/额外)
|
||||
├── 回忆历史列表
|
||||
├── 回忆输入(editable MindMapViewer)
|
||||
├── 标准导图 + 对比结果(color-by-compare MindMapViewer)
|
||||
│ ├── 未选择起点时 → selectable 模式
|
||||
│ ├── 已选择起点/已对比 → 着色展示
|
||||
│ └── 编辑模式 → editable 模式
|
||||
└── 遗漏项 + 额外项详情列表
|
||||
```
|
||||
|
||||
### 5.1 MindMapViewer 组件 Props
|
||||
|
||||
| 属性 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `tree` | `MindMapTreeNode \| null` | — | 树数据 |
|
||||
| `editable` | `boolean` | `false` | 是否可编辑 |
|
||||
| `colorByCompare` | `boolean` | `false` | 按 MATCHED/MISSED 着色 |
|
||||
| `height` | `string` | `'480px'` | 画布高度 |
|
||||
| `selectable` | `boolean` | `false` | 节点单击可选择 |
|
||||
| `selectedPath` | `string` | `''` | 当前选中节点路径 |
|
||||
|
||||
### 5.2 MindMapViewer 事件
|
||||
|
||||
| 事件 | 载荷 | 触发时机 |
|
||||
|------|------|----------|
|
||||
| `change` | `outline: string` | 编辑模式下结构变化 |
|
||||
| `node-click` | `{ sourceType, sourceId }` | 点击带溯源标签的节点 |
|
||||
| `node-select` | `{ title, path, childCount }` | selectable 模式下点击节点 |
|
||||
|
||||
### 5.3 MindMapViewer 暴露方法
|
||||
|
||||
```typescript
|
||||
defineExpose({ toOutline })
|
||||
// toOutline() → 缩进大纲文本
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 后端核心工具方法
|
||||
|
||||
### `MindMapTreeTool.java`
|
||||
|
||||
| 方法 | 说明 |
|
||||
|------|------|
|
||||
| `extractSubtree(root, path)` | 按 "/" 分隔路径提取子树,返回深拷贝 |
|
||||
| `findClosestNode(root, content)` | bigram Jaccard 匹配最近节点 |
|
||||
| `getPath(root, targetTitle)` | 获取节点到根的路径字符串 |
|
||||
| `similarityScore(a, b)` | 两段文本的 bigram Jaccard 相似度 |
|
||||
| `mergeTrees(oldRoot, newRoot)` | 按标准化标题合并新旧树 |
|
||||
| `toJson(root, mapper)` | 序列化为 JSON |
|
||||
| `fromJson(json, mapper)` | 从 JSON 反序列化 |
|
||||
| `toOutline(root)` | 树 → 缩进大纲 |
|
||||
| `toFullOutline(root)` | 树 → 完整大纲(含根标题) |
|
||||
| `parseOutline(text)` | 缩进大纲 → 树 |
|
||||
| `flatten(root)` | 前序遍历展平 |
|
||||
| `countNodes(root)` | 节点总数 |
|
||||
| `maxDepth(root)` | 最大深度 |
|
||||
|
||||
### `StandardMindMapServiceImpl.java`
|
||||
|
||||
| 方法 | 说明 |
|
||||
|------|------|
|
||||
| `getOrGenerate(taskNum)` | 获取/自动生成标准导图 |
|
||||
| `regenerate(taskNum)` | 全量重新生成(防并发) |
|
||||
| `incrementalGenerate(taskNum)` | 增量合并(保留用户编辑) |
|
||||
| `updateByOutline(taskNum, outline)` | 用户编辑 |
|
||||
| `recallCompare(taskNum, outline, focusPath)` | 回忆对比 |
|
||||
| `findNode(taskNum, content)` | 查找最近节点 |
|
||||
| `listRecallRecords(taskNum)` | 历史记录 |
|
||||
| `getRecallRecord(id)` | 单条记录详情 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 关键文件索引
|
||||
|
||||
### 前端(`lpt-fe/src/`)
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `components/ReviewRecall.vue` | 回忆复习主页面 |
|
||||
| `components/Review.vue` | 复习总览(任务列表+入口) |
|
||||
| `components/ReviewDetail.vue` | 残片/报告详情页 |
|
||||
| `components/Welcome.vue` | 首页(内含回忆卡片入口) |
|
||||
| `components/MindMapViewer.vue` | 思维导图渲染/编辑/选择组件 |
|
||||
| `api/standardMindMap.ts` | 标准导图 API 封装 |
|
||||
| `api/review.ts` | 复习 feed API |
|
||||
| `api/studySessions.ts` | 学习会话 API |
|
||||
|
||||
### 后端(`learning-progress-tracker/src/main/java/.../`)
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `controller/ReviewController.java` | 复习相关端点 |
|
||||
| `service/StandardMindMapService.java` | 标准导图服务接口 |
|
||||
| `service/impl/StandardMindMapServiceImpl.java` | 服务实现 |
|
||||
| `service/impl/BuiltinMindMapGenerator.java` | 内置规则生成器 |
|
||||
| `service/impl/RemoteAiMindMapClient.java` | AI 导图客户端 |
|
||||
| `service/impl/AiServiceClient.java` | lpt-ai 通用客户端 |
|
||||
| `utils/MindMapNode.java` | 树节点 DTO |
|
||||
| `utils/MindMapTreeTool.java` | 树操作工具类 |
|
||||
| `utils/CompareResult.java` | 对比结果 DTO |
|
||||
| `entity/ReviewStandardMindMapEntity.java` | 标准导图实体 |
|
||||
| `entity/ReviewRecallRecordEntity.java` | 回忆记录实体 |
|
||||
| `db/migration/V20260706_1__add_focus_path_to_recall_records.sql` | focus_path 迁移 |
|
||||
|
||||
### AI 服务(`lpt-ai/src/`)
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `routes/ai.ts` | AI 任务提交/轮询/抓取标题 |
|
||||
| `task-queue.ts` | 异步任务队列 |
|
||||
| `llm/prompts.ts` | prompt 模板(generate-mind-map / compare-recall / aggregate-report) |
|
||||
| `llm/client.ts` | LLM API 客户端 |
|
||||
| `admin/routes.ts` | 管理面板 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 数据流图
|
||||
|
||||
```
|
||||
学习碎片/报告
|
||||
↓ (按 session 分组)
|
||||
BuiltinMindMapGenerator / RemoteAiMindMapClient
|
||||
↓
|
||||
标准思维导图(review_standard_mind_maps)
|
||||
↓ (用户选择节点)
|
||||
extractSubtree(root, focusPath)
|
||||
↓
|
||||
子树(对比基准)
|
||||
↓ AI / BUILTIN 对比 ← 用户回忆大纲
|
||||
↓
|
||||
CompareResult
|
||||
↓ (序列化存储 + 前端渲染)
|
||||
review_recall_records + 着色 MindMapViewer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 历史版本记录
|
||||
|
||||
| Commit | 说明 |
|
||||
|--------|------|
|
||||
| `a636e51` | 新增 sessionNum 追踪 + 维度选择(已回退) |
|
||||
| `e5adb40` | 前端会话选择器(已回退) |
|
||||
| `3c3f682` | 防并发生成 + `mergeTrees` + 增量合 |
|
||||
| `5a5a294` | 前端防抖/生成提示/移除冗余面板 |
|
||||
| `84fe452` | **节点选择交互 + focusPath + findNode(当前)** |
|
||||
| `b18f8b4` | **后端 focusPath + extractSubtree + 回退 session(当前)** |
|
||||
| `ebbbeb4` | fix: Array.map 多参数 bug |
|
||||
|
||||
---
|
||||
|
||||
## 10. 待办/已知问题
|
||||
|
||||
- [ ] AI 生成的导图(`RemoteAiMindMapClient`)因为没有 `sourceId`/`sourceType`,`node-click` 溯源不可用
|
||||
- [ ] `selectable` 模式下,点击无子节点的叶子节点,`childCount` = 0 的确认弹窗体验略奇怪
|
||||
- [ ] `findClosestNode` 的 bigram 相似度对短文本效果有限,可能需要 `notes` 加权优化
|
||||
- [ ] 欢迎页(Welcome.vue)的回忆卡片入口「前往回忆复习」按钮文字和位置可以优化
|
||||
@@ -1,33 +0,0 @@
|
||||
# LPT-FE
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||
|
||||
## 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
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
@@ -1,630 +0,0 @@
|
||||
# LPT 前端架构优化说明
|
||||
|
||||
> 记录前端实现中的关键设计决策和优化策略
|
||||
|
||||
## 一、组件设计优化
|
||||
|
||||
### 1.1 MindMapViewer 多模式设计
|
||||
|
||||
**挑战**:思维导图需要支持三种不同场景
|
||||
- 查看标准导图(只读)
|
||||
- 编辑标准导图(可修改)
|
||||
- 选择复习起点(可点击节点)
|
||||
- 展示对比结果(节点着色)
|
||||
|
||||
**方案**:单组件多模式
|
||||
|
||||
```typescript
|
||||
// MindMapViewer.vue
|
||||
interface Props {
|
||||
tree: MindMapTreeNode | null;
|
||||
editable?: boolean; // 编辑模式
|
||||
selectable?: boolean; // 选择模式
|
||||
colorByCompare?: boolean; // 对比着色模式
|
||||
height?: string;
|
||||
selectedPath?: string;
|
||||
}
|
||||
```
|
||||
|
||||
**模式互斥关系**:
|
||||
- `editable=true` → 用户可修改节点
|
||||
- `selectable=true` → 点击节点触发 `node-select` 事件
|
||||
- `colorByCompare=true` → 根据 `notes` 字段着色(MATCHED|/MISSED|)
|
||||
- 默认 → 只读浏览,点击带 `sourceType` 的节点可溯源
|
||||
|
||||
**收益**:
|
||||
- 代码复用率高(一个组件覆盖所有场景)
|
||||
- API 简洁(通过 props 控制行为)
|
||||
- 维护成本低(修改一处全局生效)
|
||||
|
||||
### 1.2 回忆卡片交互设计
|
||||
|
||||
**需求**:滚动 feed 中点击内容,先让用户回忆再展示答案
|
||||
|
||||
**实现**:两阶段弹窗
|
||||
|
||||
```typescript
|
||||
// Welcome.vue
|
||||
const showRecallDialog = (item: FeedItem) => {
|
||||
// 阶段 1:只显示片段标题
|
||||
recallDialogContent.value = item.content.substring(0, 100) + '...';
|
||||
recallDialogExpanded.value = false;
|
||||
|
||||
// 用户点击"我想起来了"
|
||||
const expand = () => {
|
||||
recallDialogExpanded.value = true;
|
||||
// 阶段 2:展示完整内容 + 同会话其他内容
|
||||
loadFullSession(item.sessionNum);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
**心理学原理**:
|
||||
- 主动回忆 > 被动阅读(Testing Effect)
|
||||
- 认知失调驱动记忆巩固
|
||||
- 答案延迟呈现增强记忆深度
|
||||
|
||||
**收益**:
|
||||
- 提升复习效果
|
||||
- 增加用户参与感
|
||||
- 符合间隔重复理论
|
||||
|
||||
### 1.3 历史记录虚拟滚动
|
||||
|
||||
**问题**:活跃用户可能有 500+ 条学习记录
|
||||
|
||||
**优化前**:
|
||||
```typescript
|
||||
// ❌ 一次性渲染全部
|
||||
<div v-for="session in allSessions">...</div>
|
||||
```
|
||||
|
||||
**优化后**:
|
||||
```typescript
|
||||
// ✅ 分页 + 懒加载
|
||||
<el-pagination
|
||||
:total="total"
|
||||
:page-size="20"
|
||||
@current-change="loadPage"
|
||||
/>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 首屏渲染时间:2.5s → 0.3s
|
||||
- 内存占用:120MB → 15MB
|
||||
- 支持无限历史
|
||||
|
||||
---
|
||||
|
||||
## 二、状态管理优化
|
||||
|
||||
### 2.1 学习会话状态同步
|
||||
|
||||
**场景**:用户在任务 A 学习中,打开新标签页访问任务 B
|
||||
|
||||
**挑战**:多标签页状态不一致
|
||||
|
||||
**方案**:每次进入学习页检测活跃会话
|
||||
|
||||
```typescript
|
||||
// StartTask.vue
|
||||
onMounted(async () => {
|
||||
// 检测是否有其他任务的活跃会话
|
||||
const active = await checkActiveSession();
|
||||
if (active && active.taskNum !== currentTaskNum) {
|
||||
ElMessageBox.confirm(
|
||||
`您有正在进行的学习会话(任务 ${active.taskNum}),是否继续?`,
|
||||
{ type: 'warning' }
|
||||
).then(() => {
|
||||
router.push(`/start-task/${active.taskNum}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 防止数据丢失
|
||||
- 引导用户正确流程
|
||||
- 多标签页一致性
|
||||
|
||||
### 2.2 权重配置实时校验
|
||||
|
||||
**需求**:五个维度权重总和必须为 100%
|
||||
|
||||
**实现**:响应式计算 + 即时反馈
|
||||
|
||||
```typescript
|
||||
// Study.vue
|
||||
const weightSum = computed(() => {
|
||||
return Object.values(weights.value).reduce((sum, w) => sum + w, 0);
|
||||
});
|
||||
|
||||
const isSumValid = computed(() => weightSum.value === 100);
|
||||
|
||||
watch(weightSum, (newSum) => {
|
||||
if (newSum !== 100) {
|
||||
message.warning(`当前总和 ${newSum}%,需调整为 100%`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 即时反馈(无需点保存才知道错误)
|
||||
- 视觉提示(红色警告 + 禁用保存按钮)
|
||||
- 防止无效提交
|
||||
|
||||
### 2.3 Markdown 链接标题缓存
|
||||
|
||||
**场景**:学习材料中有 10 个 URL,每个都要调 `/fetch-title`
|
||||
|
||||
**优化前**:
|
||||
```typescript
|
||||
// ❌ 重复请求
|
||||
for (const url of urls) {
|
||||
const title = await fetchTitle(url);
|
||||
}
|
||||
```
|
||||
|
||||
**优化后**:
|
||||
```typescript
|
||||
// ✅ 内存缓存 + 请求去重
|
||||
const titleCache = new Map<string, Promise<string>>();
|
||||
|
||||
export const getUrlTitle = (url: string) => {
|
||||
if (titleCache.has(url)) {
|
||||
return titleCache.get(url);
|
||||
}
|
||||
const promise = fetchTitle(url);
|
||||
titleCache.set(url, promise);
|
||||
return promise;
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 重复 URL 零请求
|
||||
- 并发请求自动去重(Promise 复用)
|
||||
- 会话内持久化
|
||||
|
||||
---
|
||||
|
||||
## 三、用户体验优化
|
||||
|
||||
### 3.1 学习预期常驻展示
|
||||
|
||||
**需求**:用户学习过程中可随时查看预期,结束时对比
|
||||
|
||||
**实现**:卡片式展示 + 弹窗对比
|
||||
|
||||
```vue
|
||||
<!-- StartTask.vue -->
|
||||
<el-card class="expectation-card" v-if="expectation">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>📋 本次学习预期</span>
|
||||
<el-button text @click="editExpectation">修改</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<p>{{ expectation }}</p>
|
||||
</el-card>
|
||||
```
|
||||
|
||||
结束会话时:
|
||||
```typescript
|
||||
ElMessageBox.confirm(`
|
||||
<p><strong>预期:</strong>${expectation}</p>
|
||||
<p><strong>实际:</strong>${reportContent}</p>
|
||||
<p>是否达成预期?</p>
|
||||
`, { dangerouslyUseHTMLString: true });
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 元认知训练
|
||||
- 学习目标明确
|
||||
- 防止跑偏
|
||||
|
||||
### 3.2 AI 生成进度提示
|
||||
|
||||
**场景**:AI 生成思维导图需要 30-60 秒
|
||||
|
||||
**实现**:分段提示 + 轮询进度
|
||||
|
||||
```typescript
|
||||
// ReviewRecall.vue
|
||||
const generateWithAi = async () => {
|
||||
message.info('正在调用 AI 生成思维导图...');
|
||||
|
||||
const { taskId } = await submitAiTask({
|
||||
type: 'generate-mind-map',
|
||||
params: { taskName, reports, fragments }
|
||||
});
|
||||
|
||||
// 轮询任务状态
|
||||
const poll = setInterval(async () => {
|
||||
const result = await getAiTaskResult(taskId);
|
||||
|
||||
if (result.status === 'running') {
|
||||
message.info(`生成中... ${result.progress || 50}%`);
|
||||
} else if (result.status === 'completed') {
|
||||
message.success('生成完成!');
|
||||
clearInterval(poll);
|
||||
loadStandardMap();
|
||||
} else if (result.status === 'failed') {
|
||||
message.error('生成失败,已降级为内置规则');
|
||||
clearInterval(poll);
|
||||
}
|
||||
}, 2000);
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 降低用户焦虑
|
||||
- 明确系统状态
|
||||
- 减少重复点击
|
||||
|
||||
### 3.3 节点路径面包屑
|
||||
|
||||
**场景**:用户选择复习起点后,需明确当前在导图的哪个位置
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<!-- ReviewRecall.vue -->
|
||||
<el-breadcrumb v-if="focusPath">
|
||||
<el-breadcrumb-item>复习起点</el-breadcrumb-item>
|
||||
<el-breadcrumb-item
|
||||
v-for="part in focusPath.split(' / ')"
|
||||
:key="part"
|
||||
>
|
||||
{{ part }}
|
||||
</el-breadcrumb-item>
|
||||
</el-breadcrumb>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 空间定位清晰
|
||||
- 复习范围明确
|
||||
- 可点击返回上级
|
||||
|
||||
---
|
||||
|
||||
## 四、性能优化
|
||||
|
||||
### 4.1 Markdown 渲染优化
|
||||
|
||||
**挑战**:复杂正则可能导致嵌套 HTML(XSS 风险)
|
||||
|
||||
**方案**:占位符两阶段渲染
|
||||
|
||||
```typescript
|
||||
// utils/markdown.ts
|
||||
export const renderMarkdown = (raw: string): string => {
|
||||
const placeholders = new Map<string, string>();
|
||||
let counter = 0;
|
||||
|
||||
// 阶段 1:提取链接,替换为占位符
|
||||
let stage1 = raw.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, text, url) => {
|
||||
const key = `__LINK_${counter++}__`;
|
||||
placeholders.set(key, `<a href="${url}">${text}</a>`);
|
||||
return key;
|
||||
});
|
||||
|
||||
// 阶段 2:替换占位符为真实 HTML
|
||||
placeholders.forEach((html, key) => {
|
||||
stage1 = stage1.replace(key, html);
|
||||
});
|
||||
|
||||
return stage1;
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 避免正则二次匹配导致的嵌套
|
||||
- 性能提升(单次遍历)
|
||||
- 安全性高(输出可预测)
|
||||
|
||||
### 4.2 防抖与节流
|
||||
|
||||
**场景**:
|
||||
- 搜索框输入(防抖)
|
||||
- 滚动加载(节流)
|
||||
- 权重滑块调整(防抖)
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
import { debounce } from 'lodash-es';
|
||||
|
||||
// 搜索输入
|
||||
const handleSearch = debounce((keyword: string) => {
|
||||
searchTasks(keyword);
|
||||
}, 300);
|
||||
|
||||
// 滚动加载
|
||||
const handleScroll = throttle(() => {
|
||||
if (isBottom()) loadMore();
|
||||
}, 200);
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 减少 API 调用
|
||||
- 降低 CPU 占用
|
||||
- 提升响应速度
|
||||
|
||||
### 4.3 图片懒加载
|
||||
|
||||
**场景**:学习材料中可能包含多张图片
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<img v-lazy="imageUrl" alt="学习材料配图" />
|
||||
```
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
import VueLazyload from 'vue-lazyload';
|
||||
app.use(VueLazyload, {
|
||||
loading: '/placeholder.png',
|
||||
error: '/error.png'
|
||||
});
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 首屏加载快
|
||||
- 节省带宽
|
||||
- 平滑加载体验
|
||||
|
||||
---
|
||||
|
||||
## 五、错误处理
|
||||
|
||||
### 5.1 统一异常拦截
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
// utils/request.ts
|
||||
axios.interceptors.response.use(
|
||||
response => {
|
||||
const { code, message } = response.data;
|
||||
if (code !== 200) {
|
||||
ElMessage.error(message || '请求失败');
|
||||
return Promise.reject(new Error(message));
|
||||
}
|
||||
return response;
|
||||
},
|
||||
error => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('isLoggedIn');
|
||||
router.push('/login');
|
||||
ElMessage.error('登录已过期,请重新登录');
|
||||
} else if (error.response?.status === 403) {
|
||||
ElMessage.error('无权限访问');
|
||||
} else {
|
||||
ElMessage.error(error.message || '网络错误');
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 业务代码无需重复处理
|
||||
- 统一错误提示样式
|
||||
- 自动处理登录过期
|
||||
|
||||
### 5.2 降级 UI
|
||||
|
||||
**场景**:AI 生成失败,自动切换为内置生成
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
const generate = async () => {
|
||||
try {
|
||||
await generateWithAi();
|
||||
} catch (error) {
|
||||
ElNotification({
|
||||
title: 'AI 生成失败',
|
||||
message: '已自动切换为内置规则生成',
|
||||
type: 'warning'
|
||||
});
|
||||
await generateBuiltin();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 用户无感知切换
|
||||
- 功能可用性保障
|
||||
- 明确提示原因
|
||||
|
||||
---
|
||||
|
||||
## 六、可访问性优化
|
||||
|
||||
### 6.1 键盘导航
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<!-- 学习页 -->
|
||||
<div
|
||||
tabindex="0"
|
||||
@keydown.space="togglePause"
|
||||
@keydown.enter="endSession"
|
||||
>
|
||||
<!-- 内容 -->
|
||||
</div>
|
||||
```
|
||||
|
||||
**支持快捷键**:
|
||||
- `Space` - 暂停/继续
|
||||
- `Enter` - 结束会话
|
||||
- `Esc` - 关闭弹窗
|
||||
- `Tab` - 焦点切换
|
||||
|
||||
### 6.2 语义化 HTML
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<!-- ✅ 正确 -->
|
||||
<main>
|
||||
<section aria-label="复习概览">
|
||||
<h2>复习概览</h2>
|
||||
<nav aria-label="任务列表">...</nav>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- ❌ 错误 -->
|
||||
<div class="main">
|
||||
<div class="section">
|
||||
<div class="title">复习概览</div>
|
||||
<div class="list">...</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 屏幕阅读器友好
|
||||
- SEO 优化
|
||||
- 代码可读性高
|
||||
|
||||
### 6.3 色盲友好
|
||||
|
||||
**对比结果着色**:
|
||||
- 匹配节点:绿色 `#c8e6c9` + ✓ 图标
|
||||
- 遗漏节点:红色 `#ffcdd2` + ✗ 图标
|
||||
- 额外节点:蓝色 `#bbdefb` + ★ 图标
|
||||
|
||||
**原则**:不仅依赖颜色,同时使用图标/文字辅助
|
||||
|
||||
---
|
||||
|
||||
## 七、构建优化
|
||||
|
||||
### 7.1 代码分割
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
// router/index.ts
|
||||
const routes = [
|
||||
{
|
||||
path: '/review/recall/:taskNum',
|
||||
component: () => import('@/components/ReviewRecall.vue') // 懒加载
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 首屏包体积:1.2MB → 320KB
|
||||
- 按需加载(用户未访问的页面不下载)
|
||||
|
||||
### 7.2 依赖优化
|
||||
|
||||
**移除未使用依赖**:
|
||||
```bash
|
||||
# 检测未使用的依赖
|
||||
npx depcheck
|
||||
|
||||
# 移除
|
||||
npm uninstall unused-package
|
||||
```
|
||||
|
||||
**tree-shaking**:
|
||||
```typescript
|
||||
// ✅ 按需导入
|
||||
import { debounce } from 'lodash-es';
|
||||
|
||||
// ❌ 全量导入
|
||||
import _ from 'lodash';
|
||||
```
|
||||
|
||||
### 7.3 CDN 加速
|
||||
|
||||
**生产环境**:
|
||||
```html
|
||||
<!-- index.html -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/element-plus/dist/index.full.min.js"></script>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 浏览器缓存复用
|
||||
- 减轻服务器压力
|
||||
- 提升加载速度
|
||||
|
||||
---
|
||||
|
||||
## 八、开发体验优化
|
||||
|
||||
### 8.1 TypeScript 类型安全
|
||||
|
||||
**API 响应类型**:
|
||||
```typescript
|
||||
// api/types.ts
|
||||
export interface StandardMindMapResponse {
|
||||
taskNum: number;
|
||||
content: MindMapTreeNode;
|
||||
outline: string;
|
||||
generatedBy: 'BUILTIN' | 'AI' | 'USER';
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// 调用时自动补全 + 类型检查
|
||||
const res = await getStandardMindMap(taskNum);
|
||||
console.log(res.data.generatedBy); // ✅ 类型安全
|
||||
```
|
||||
|
||||
### 8.2 组件文档
|
||||
|
||||
**JSDoc 注释**:
|
||||
```typescript
|
||||
/**
|
||||
* 思维导图查看/编辑组件
|
||||
* @param tree - 树数据(MindMapTreeNode 格式)
|
||||
* @param editable - 是否可编辑(默认 false)
|
||||
* @param selectable - 是否可选择节点(默认 false)
|
||||
* @param colorByCompare - 是否按对比结果着色(默认 false)
|
||||
* @emits change - 编辑模式下内容变化时触发,参数为新的大纲文本
|
||||
* @emits node-click - 点击带溯源信息的节点时触发
|
||||
* @emits node-select - selectable 模式下点击节点时触发
|
||||
*/
|
||||
```
|
||||
|
||||
### 8.3 开发环境代理
|
||||
|
||||
**解决跨域**:
|
||||
```typescript
|
||||
// vite.config.ts
|
||||
export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 九、性能指标
|
||||
|
||||
| 指标 | 目标 | 实测 |
|
||||
|------|------|------|
|
||||
| 首屏 FCP | <1.5s | 1.2s |
|
||||
| 首屏 LCP | <2.5s | 1.8s |
|
||||
| TTI | <3.5s | 2.9s |
|
||||
| 路由切换 | <300ms | 180ms |
|
||||
| Markdown 渲染(100行) | <50ms | 32ms |
|
||||
| 思维导图渲染(200节点) | <500ms | 380ms |
|
||||
|
||||
---
|
||||
|
||||
## 十、总结
|
||||
|
||||
前端实现中的关键优化:
|
||||
|
||||
1. **组件设计**:单组件多模式、状态管理、交互优化
|
||||
2. **性能优化**:虚拟滚动、懒加载、防抖节流、代码分割
|
||||
3. **用户体验**:进度提示、即时反馈、降级 UI、快捷键
|
||||
4. **工程质量**:TypeScript、错误处理、可访问性、构建优化
|
||||
|
||||
这些优化使 LPT 前端不仅功能完整,而且性能优异、体验流畅、代码可维护。
|
||||
@@ -31,4 +31,44 @@ test.describe('Welcome page', () => {
|
||||
await page.locator('.quick-card').nth(1).locator('button').click();
|
||||
await expect(page).toHaveURL(/\/review/);
|
||||
});
|
||||
|
||||
test('wheel scrolls review ticker manually while hovering', async ({ page }) => {
|
||||
const items = Array.from({ length: 10 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
sessionNum: `S${i + 1}`,
|
||||
taskNum: `T${i + 1}`,
|
||||
taskName: `任务 ${i + 1}`,
|
||||
sourceType: 'FRAGMENT',
|
||||
content: `第 ${i + 1} 条学习残片内容,用来撑起首页滚动区域。`,
|
||||
createdTime: `2026-08-01 10:00:${String(i).padStart(2, '0')}`,
|
||||
}));
|
||||
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: items }),
|
||||
}),
|
||||
);
|
||||
await page.goto('/welcome');
|
||||
|
||||
const track = page.locator('.review-scroll-track');
|
||||
const content = page.locator('.review-scroll-content');
|
||||
await expect(track).toBeVisible();
|
||||
await track.hover();
|
||||
|
||||
const readTime = () =>
|
||||
content.evaluate((el) => {
|
||||
const anim = el.getAnimations()[0];
|
||||
return anim && typeof anim.currentTime === 'number' ? anim.currentTime : -1;
|
||||
});
|
||||
|
||||
const before = await readTime();
|
||||
await page.mouse.wheel(0, 200);
|
||||
await expect.poll(readTime).toBeGreaterThan(before);
|
||||
|
||||
await page.mouse.move(10, 10);
|
||||
const after = await readTime();
|
||||
await expect.poll(readTime).toBeGreaterThan(after);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
continueSession,
|
||||
pauseSession,
|
||||
endSession,
|
||||
abortSession,
|
||||
startOrContinueStudySession,
|
||||
getSessionDetail,
|
||||
} from '@/api/studySessions'
|
||||
@@ -69,6 +70,14 @@ describe('studySessions API', () => {
|
||||
{ content: '自定义结束' }
|
||||
)
|
||||
})
|
||||
it('abortSession sends POST with confirmation phrase', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await abortSession('S001', '我误操作导致开启了本次学习')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/abort',
|
||||
{ confirmation: '我误操作导致开启了本次学习' }
|
||||
)
|
||||
})
|
||||
|
||||
it('startOrContinueStudySession sends GET to correct endpoint', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { sessionNum: 'S002' } })
|
||||
|
||||
@@ -1,112 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
||||
import { reactive, ref } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import Login from '@/components/Login.vue'
|
||||
import router from '@/router'
|
||||
import { login } from '@/api/login'
|
||||
|
||||
// Mock API
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock Element Plus
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { login } from '@/api/login'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
function createTestRouter() {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: { template: '<div/>' } },
|
||||
{ path: '/welcome', component: { template: '<div/>' } },
|
||||
],
|
||||
function mountLogin() {
|
||||
return mount(Login, {
|
||||
shallow: true,
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('Login.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
function createForm(valid = true) {
|
||||
return {
|
||||
validate: (callback: (valid: boolean) => void) => callback(valid),
|
||||
} as any
|
||||
}
|
||||
|
||||
describe('Login.vue', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
describe('isNotEmpty validator', () => {
|
||||
it('calls callback with error message when value is empty', () => {
|
||||
const callback = vi.fn()
|
||||
const rule = { message: '请输入账号!' }
|
||||
// isNotEmpty logic
|
||||
const value = ''
|
||||
if (!value) {
|
||||
callback(rule.message)
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
||||
})
|
||||
it('isNotEmpty validator reports empty value and accepts filled value', () => {
|
||||
const wrapper = mountLogin()
|
||||
const callback = vi.fn()
|
||||
|
||||
it('calls callback without error when value is present', () => {
|
||||
const callback = vi.fn()
|
||||
const rule = { message: '请输入账号!' }
|
||||
const value = 'admin'
|
||||
if (!value) {
|
||||
callback(rule.message)
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
expect(callback).toHaveBeenCalledWith()
|
||||
})
|
||||
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, '', callback)
|
||||
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
||||
|
||||
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, 'admin', callback)
|
||||
expect(callback).toHaveBeenCalledWith()
|
||||
})
|
||||
|
||||
describe('submitForm logic', () => {
|
||||
it('sets localStorage and navigates on successful login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
||||
const router = createTestRouter()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
it('sets localStorage and navigates on successful login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
||||
const wrapper = mountLogin()
|
||||
wrapper.vm.registerData.username = 'admin'
|
||||
wrapper.vm.registerData.password = '123456'
|
||||
|
||||
// Simulate submitForm logic
|
||||
const username = 'admin'
|
||||
const password = '123456'
|
||||
const result = await login(username, password)
|
||||
await wrapper.vm.submitForm(createForm(true))
|
||||
|
||||
if (result.code === 200) {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
ElMessage.success(result.message)
|
||||
await router.push('/welcome')
|
||||
}
|
||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
it('shows error message on failed login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
||||
const wrapper = mountLogin()
|
||||
wrapper.vm.registerData.username = 'admin'
|
||||
wrapper.vm.registerData.password = 'wrong'
|
||||
|
||||
it('shows error message on failed login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
||||
await wrapper.vm.submitForm(createForm(true))
|
||||
|
||||
const result = await login('admin', 'wrong')
|
||||
if (result.code !== 200) {
|
||||
ElMessage.error(result.message)
|
||||
}
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
})
|
||||
it('does not submit again while loading', async () => {
|
||||
let resolveLogin!: (value: any) => void
|
||||
vi.mocked(login).mockImplementation(
|
||||
() => new Promise((resolve) => { resolveLogin = resolve }),
|
||||
)
|
||||
const wrapper = mountLogin()
|
||||
|
||||
it('does not submit when already loading', async () => {
|
||||
const loading = ref(true)
|
||||
// Simulate guard: if (!formEl || loading.value) return;
|
||||
if (loading.value) {
|
||||
// Early return - no API call
|
||||
}
|
||||
expect(login).not.toHaveBeenCalled()
|
||||
})
|
||||
const firstSubmit = wrapper.vm.submitForm(createForm(true))
|
||||
const secondSubmit = wrapper.vm.submitForm(createForm(true))
|
||||
await Promise.resolve()
|
||||
|
||||
expect(login).toHaveBeenCalledTimes(1)
|
||||
|
||||
resolveLogin({ code: 200, message: '登录成功' })
|
||||
await Promise.all([firstSubmit, secondSubmit])
|
||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,106 +1,93 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { computed, ref } from 'vue'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import MyHead from '@/components/MyHead.vue'
|
||||
import router from '@/router'
|
||||
import { logout } from '@/api/login'
|
||||
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn().mockResolvedValue({ code: 200 }),
|
||||
logout: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
async function mountAt(path: string) {
|
||||
await router.push(path)
|
||||
await router.isReady()
|
||||
return mount(MyHead, {
|
||||
shallow: true,
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
import { logout } from '@/api/login'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
describe('MyHead.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
describe('MyHead.vue', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
describe('route-based computed properties', () => {
|
||||
it('isLoginRoute is true when path is /login', () => {
|
||||
const routePath = ref('/login')
|
||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
||||
expect(isLoginRoute.value).toBe(true)
|
||||
})
|
||||
it('derives route-based computed properties from real route', async () => {
|
||||
const loginWrapper = await mountAt('/login')
|
||||
expect(loginWrapper.vm.isLoginRoute).toBe(true)
|
||||
expect(loginWrapper.vm.showBackButton).toBe(false)
|
||||
|
||||
it('isLoginRoute is false for other paths', () => {
|
||||
const routePath = ref('/welcome')
|
||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
||||
expect(isLoginRoute.value).toBe(false)
|
||||
})
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const studyWrapper = await mountAt('/study')
|
||||
expect(studyWrapper.vm.isLoginRoute).toBe(false)
|
||||
expect(studyWrapper.vm.showBackButton).toBe(true)
|
||||
expect(studyWrapper.vm.pageTitle).toBe('学习任务')
|
||||
|
||||
it('showBackButton is true for non-login, non-welcome routes', () => {
|
||||
const routePath = ref('/study')
|
||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
||||
expect(showBackButton.value).toBe(true)
|
||||
})
|
||||
|
||||
it('showBackButton is false on welcome route', () => {
|
||||
const routePath = ref('/welcome')
|
||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
||||
expect(showBackButton.value).toBe(false)
|
||||
})
|
||||
|
||||
it('showBackButton is false on login route', () => {
|
||||
const routePath = ref('/login')
|
||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
||||
expect(showBackButton.value).toBe(false)
|
||||
})
|
||||
|
||||
it('pageTitle is derived from route meta', () => {
|
||||
const meta = { title: '学习任务' }
|
||||
const pageTitle = computed(() => meta?.title as string | undefined)
|
||||
expect(pageTitle.value).toBe('学习任务')
|
||||
})
|
||||
|
||||
it('pageTitle is undefined when no meta title', () => {
|
||||
const meta = {}
|
||||
const pageTitle = computed(() => meta?.title as string | undefined)
|
||||
expect(pageTitle.value).toBeUndefined()
|
||||
})
|
||||
const welcomeWrapper = await mountAt('/welcome')
|
||||
expect(welcomeWrapper.vm.showBackButton).toBe(false)
|
||||
expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
|
||||
})
|
||||
|
||||
describe('handleLogout logic', () => {
|
||||
it('clears login state and navigates to login', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
it('clears login state and navigates to login on logout', async () => {
|
||||
vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const wrapper = await mountAt('/study')
|
||||
|
||||
// Simulate handleLogout
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Backend failure shouldn't block logout
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
await wrapper.vm.handleLogout()
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('clears login state even when API call fails', async () => {
|
||||
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
it('clears login state even when logout API fails', async () => {
|
||||
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const wrapper = await mountAt('/study')
|
||||
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Expected
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
await wrapper.vm.handleLogout()
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('prevents repeated logout while request is pending', async () => {
|
||||
let resolveLogout!: (value: any) => void
|
||||
vi.mocked(logout).mockImplementation(
|
||||
() => new Promise((resolve) => { resolveLogout = resolve }),
|
||||
)
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const wrapper = await mountAt('/study')
|
||||
|
||||
const first = wrapper.vm.handleLogout()
|
||||
const second = wrapper.vm.handleLogout()
|
||||
await Promise.resolve()
|
||||
|
||||
expect(logout).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.vm.loggingOut).toBe(true)
|
||||
|
||||
resolveLogout({ code: 200 })
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(wrapper.vm.loggingOut).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,276 +1,267 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref, reactive } from 'vue'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import StartTask from '@/components/StartTask.vue'
|
||||
import router from '@/router'
|
||||
import {
|
||||
abortSession,
|
||||
continueSession,
|
||||
endSession,
|
||||
getActiveSession,
|
||||
getExpectation,
|
||||
getSessionDetail,
|
||||
pauseSession,
|
||||
startOrContinueStudySession,
|
||||
} from '@/api/studySessions'
|
||||
import { getFragmentsBySession } from '@/api/reportFragments'
|
||||
|
||||
// Mock API
|
||||
vi.mock('@/api/studySessions', () => ({
|
||||
abortSession: vi.fn(),
|
||||
continueSession: vi.fn(),
|
||||
pauseSession: vi.fn(),
|
||||
endSession: vi.fn(),
|
||||
startOrContinueStudySession: vi.fn(),
|
||||
getActiveSession: vi.fn(),
|
||||
getExpectation: vi.fn(),
|
||||
getReportDraft: vi.fn(),
|
||||
getSessionDetail: vi.fn(),
|
||||
getTaskFragments: vi.fn(),
|
||||
getTaskReports: vi.fn(),
|
||||
pauseSession: vi.fn(),
|
||||
startOrContinueStudySession: vi.fn(),
|
||||
upsertExpectation: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/reportFragments', () => ({
|
||||
createFragments: vi.fn(),
|
||||
getFragmentsBySession: vi.fn(),
|
||||
updateFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
import {
|
||||
continueSession,
|
||||
pauseSession,
|
||||
endSession,
|
||||
startOrContinueStudySession,
|
||||
} from '@/api/studySessions'
|
||||
|
||||
const mockedContinueSession = vi.mocked(continueSession)
|
||||
const mockedPauseSession = vi.mocked(pauseSession)
|
||||
const mockedEndSession = vi.mocked(endSession)
|
||||
const mockedStartOrContinue = vi.mocked(startOrContinueStudySession)
|
||||
|
||||
// 模拟 StartTask.vue 中的核心状态和方法
|
||||
function createSessionSimulator() {
|
||||
const taskInfo = reactive({
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING' as string,
|
||||
taskName: '测试任务',
|
||||
taskNum: 'T001',
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
lastStartTime: '',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1500000,
|
||||
systemMessage: '',
|
||||
})
|
||||
|
||||
const timerRunning = ref(true)
|
||||
|
||||
const clear = () => {
|
||||
timerRunning.value = false
|
||||
}
|
||||
|
||||
const runCountdown = (duration: number) => {
|
||||
timerRunning.value = true
|
||||
}
|
||||
|
||||
// 从 StartTask.vue 提取的 stopTimer 逻辑
|
||||
const stopTimer = async () => {
|
||||
const res = await pauseSession(taskInfo.sessionNum)
|
||||
if (res.code === 200) {
|
||||
taskInfo.sessionState = 'PAUSED'
|
||||
}
|
||||
clear()
|
||||
}
|
||||
|
||||
// 从 StartTask.vue 提取的 startTimer 逻辑
|
||||
const startTimer = async () => {
|
||||
if (taskInfo.sessionState === 'PAUSED') {
|
||||
const res = await continueSession(taskInfo.sessionNum)
|
||||
if (res.code === 200) {
|
||||
// ElMessage.success("任务继续")
|
||||
}
|
||||
// loadTaskSession 模拟
|
||||
const sessionRes = await startOrContinueStudySession(taskInfo.taskNum)
|
||||
Object.assign(taskInfo, sessionRes.data)
|
||||
}
|
||||
const duration = taskInfo.pointerPosition || 25 * 60 * 1000
|
||||
runCountdown(duration)
|
||||
}
|
||||
|
||||
// 从 StartTask.vue 提取的 endTimer 逻辑(简化版,跳过 confirm)
|
||||
const endTimer = async (content: string) => {
|
||||
if (!content) return
|
||||
const res = await endSession(taskInfo.sessionNum, content)
|
||||
if (res.code === 200) {
|
||||
if (res.message && res.message !== '请求成功') {
|
||||
// ElMessage.warning(res.message)
|
||||
}
|
||||
}
|
||||
clear()
|
||||
}
|
||||
|
||||
return { taskInfo, timerRunning, stopTimer, startTimer, endTimer, clear }
|
||||
const defaultSessionData = {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'PAUSED',
|
||||
taskName: '测试任务',
|
||||
taskNum: 'T001',
|
||||
taskId: 1,
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
lastStartTime: '',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1_500_000,
|
||||
systemMessage: '',
|
||||
}
|
||||
|
||||
describe('StartTask.vue 暂停/继续逻辑', () => {
|
||||
beforeEach(() => {
|
||||
async function mountTask() {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const testRouter = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{
|
||||
path: '/start-task/:taskNum',
|
||||
component: StartTask,
|
||||
meta: { requiresAuth: true, title: '学习会话' },
|
||||
},
|
||||
],
|
||||
})
|
||||
await testRouter.push('/start-task/T001')
|
||||
await testRouter.isReady()
|
||||
const wrapper = mount(StartTask, {
|
||||
shallow: true,
|
||||
global: {
|
||||
plugins: [ElementPlus, testRouter],
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
describe('StartTask.vue', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
vi.mocked(getActiveSession).mockResolvedValue({ code: 200, data: null } as any)
|
||||
vi.mocked(startOrContinueStudySession).mockResolvedValue({ code: 200, data: defaultSessionData } as any)
|
||||
vi.mocked(getExpectation).mockResolvedValue({ code: 200, data: { description: '本次学习预期' } } as any)
|
||||
vi.mocked(getFragmentsBySession).mockResolvedValue({ code: 200, data: [] } as any)
|
||||
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
describe('stopTimer - 暂停', () => {
|
||||
it('调用 pauseSession API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { stopTimer } = createSessionSimulator()
|
||||
it('stopTimer pauses real session state and refreshes from detail API', async () => {
|
||||
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
vi.mocked(getSessionDetail).mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
sessionState: 'PAUSED',
|
||||
actualTime: 10,
|
||||
effectiveTime: 20,
|
||||
effectivenessRatio: 0.8,
|
||||
pointerPosition: 1_200_000,
|
||||
},
|
||||
} as any)
|
||||
const wrapper = await mountTask()
|
||||
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||
wrapper.vm.timerRunning = true
|
||||
|
||||
await stopTimer()
|
||||
await wrapper.vm.stopTimer()
|
||||
|
||||
expect(mockedPauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||
})
|
||||
|
||||
it('暂停成功后 sessionState 应更新为 PAUSED', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { taskInfo, stopTimer } = createSessionSimulator()
|
||||
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
})
|
||||
|
||||
it('暂停后 timerRunning 应为 false', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { timerRunning, stopTimer } = createSessionSimulator()
|
||||
|
||||
expect(timerRunning.value).toBe(true)
|
||||
await stopTimer()
|
||||
expect(timerRunning.value).toBe(false)
|
||||
})
|
||||
expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(wrapper.vm.taskInfo.actualTime).toBe(10)
|
||||
expect(wrapper.vm.taskInfo.effectiveTime).toBe(20)
|
||||
expect(wrapper.vm.timerRunning).toBe(false)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
describe('startTimer - 继续', () => {
|
||||
it('PAUSED 状态下点击开始,应调用 continueSession API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
pointerPosition: 1500000,
|
||||
},
|
||||
} as any)
|
||||
it('startTimer continues a paused session and reloads session data', async () => {
|
||||
vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
vi.mocked(startOrContinueStudySession).mockResolvedValue({
|
||||
code: 200,
|
||||
data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
|
||||
} as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
// 挂载时后端返回 PAUSED;手动改为 PAUSED 后,startTimer 应触发 continue
|
||||
wrapper.vm.taskInfo.sessionState = 'PAUSED'
|
||||
await wrapper.vm.startTimer()
|
||||
|
||||
// 先暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
|
||||
// 再开始
|
||||
await startTimer()
|
||||
|
||||
expect(mockedContinueSession).toHaveBeenCalledWith('SESSION_001')
|
||||
})
|
||||
|
||||
it('PAUSED 状态下点击开始,应调用 loadTaskSession 刷新数据', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
pointerPosition: 1200000,
|
||||
},
|
||||
} as any)
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
await stopTimer()
|
||||
await startTimer()
|
||||
|
||||
expect(mockedStartOrContinue).toHaveBeenCalledWith('T001')
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
})
|
||||
|
||||
it('ONGOING 状态下点击开始,不应调用 continueSession API', async () => {
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
||||
} as any)
|
||||
|
||||
const { taskInfo, startTimer } = createSessionSimulator()
|
||||
|
||||
// 直接在 ONGOING 状态调用 startTimer
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
await startTimer()
|
||||
|
||||
expect(mockedContinueSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('开始后 timerRunning 应为 true', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
||||
} as any)
|
||||
|
||||
const { timerRunning, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
await stopTimer()
|
||||
expect(timerRunning.value).toBe(false)
|
||||
|
||||
await startTimer()
|
||||
expect(timerRunning.value).toBe(true)
|
||||
})
|
||||
expect(continueSession).toHaveBeenCalledWith('SESSION_001')
|
||||
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(wrapper.vm.timerRunning).toBe(true)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
describe('endTimer - 结束会话', () => {
|
||||
it('调用 endSession API 并传递 content', async () => {
|
||||
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { endTimer } = createSessionSimulator()
|
||||
it('startTimer does not call continue API when session is already ongoing', async () => {
|
||||
const wrapper = await mountTask()
|
||||
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||
|
||||
await endTimer('学习总结内容')
|
||||
await wrapper.vm.startTimer()
|
||||
|
||||
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
||||
})
|
||||
|
||||
it('后端返回 warning 消息时,message 应包含提示信息', async () => {
|
||||
mockedEndSession.mockResolvedValue({
|
||||
code: 200,
|
||||
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
||||
} as any)
|
||||
|
||||
const { endTimer } = createSessionSimulator()
|
||||
const res = await endSession('SESSION_001', '内容')
|
||||
|
||||
expect(res.message).toBe('本次有效学习时间不足10分钟,不计入总学习时间')
|
||||
expect(res.message).not.toBe('请求成功')
|
||||
})
|
||||
|
||||
it('content 为空时不调用 API', async () => {
|
||||
const { endTimer } = createSessionSimulator()
|
||||
|
||||
await endTimer('')
|
||||
|
||||
expect(mockedEndSession).not.toHaveBeenCalled()
|
||||
})
|
||||
expect(continueSession).not.toHaveBeenCalled()
|
||||
expect(wrapper.vm.timerRunning).toBe(true)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
describe('完整暂停→继续→暂停流程', () => {
|
||||
it('多次暂停/继续应正确更新状态和调用 API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
||||
} as any)
|
||||
it('redirects to another active task when one exists', async () => {
|
||||
vi.mocked(getActiveSession).mockResolvedValue({
|
||||
code: 200,
|
||||
data: { taskNum: 'T002', taskName: '其他任务', sessionNum: 'S002' },
|
||||
} as any)
|
||||
const wrapper = await mountTask()
|
||||
await flushPromises()
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
expect(startOrContinueStudySession).not.toHaveBeenCalled()
|
||||
expect(router.currentRoute.value.path).toBe('/start-task/T002')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
// 初始状态
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
it('endTimer refuses empty content without calling API', async () => {
|
||||
const wrapper = await mountTask()
|
||||
|
||||
// 第一次暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
|
||||
await wrapper.vm.endTimer('')
|
||||
|
||||
// 继续
|
||||
await startTimer()
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(mockedContinueSession).toHaveBeenCalledTimes(1)
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
|
||||
expect(endSession).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
// 第二次暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(mockedPauseSession).toHaveBeenCalledTimes(2)
|
||||
it('endTimer ends session and navigates to study page', async () => {
|
||||
vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
// 再次继续
|
||||
await startTimer()
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(mockedContinueSession).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
await wrapper.vm.endTimer('学习总结内容')
|
||||
|
||||
expect(endSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('任务结束')
|
||||
expect(localStorage.getItem('activeSession')).toBeNull()
|
||||
expect(router.currentRoute.value.path).toBe('/study')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('endTimer shows warning message returned by backend', async () => {
|
||||
vi.mocked(endSession).mockResolvedValue({
|
||||
code: 200,
|
||||
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
||||
} as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
await wrapper.vm.endTimer('学习总结内容')
|
||||
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('本次有效学习时间不足10分钟,不计入总学习时间')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('supports a full pause -> continue -> pause flow', async () => {
|
||||
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
vi.mocked(getSessionDetail).mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20 },
|
||||
} as any)
|
||||
vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
vi.mocked(startOrContinueStudySession).mockResolvedValue({
|
||||
code: 200,
|
||||
data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
|
||||
} as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||
wrapper.vm.timerRunning = true
|
||||
await wrapper.vm.stopTimer()
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(pauseSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
await wrapper.vm.startTimer()
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(continueSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
await wrapper.vm.stopTimer()
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(pauseSession).toHaveBeenCalledTimes(2)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('confirmAbort aborts session with correct phrase and navigates to study page', async () => {
|
||||
vi.mocked(abortSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
wrapper.vm.abortConfirmation = '我误操作导致开启了本次学习'
|
||||
await wrapper.vm.confirmAbort()
|
||||
|
||||
expect(abortSession).toHaveBeenCalledWith('SESSION_001', '我误操作导致开启了本次学习')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('本次学习已关闭,未产生任何数据')
|
||||
expect(localStorage.getItem('activeSession')).toBeNull()
|
||||
expect(router.currentRoute.value.path).toBe('/study')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('confirmAbort refuses wrong phrase without calling API', async () => {
|
||||
const wrapper = await mountTask()
|
||||
|
||||
wrapper.vm.abortConfirmation = '不是确认语'
|
||||
await wrapper.vm.confirmAbort()
|
||||
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('确认语输入不正确,请重新输入')
|
||||
expect(abortSession).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('confirmAbort shows backend message when session has fragments and stays on page', async () => {
|
||||
vi.mocked(abortSession).mockRejectedValue({
|
||||
code: 400,
|
||||
message: '这次学习已经产生了学习残片,不能按误操作结束了哦',
|
||||
} as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
wrapper.vm.abortConfirmation = '我误操作导致开启了本次学习'
|
||||
await wrapper.vm.confirmAbort()
|
||||
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('这次学习已经产生了学习残片,不能按误操作结束了哦')
|
||||
expect(router.currentRoute.value.path).not.toBe('/study')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,126 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref, reactive } from 'vue'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import TaskForm from '@/components/TaskForm.vue'
|
||||
import router from '@/router'
|
||||
import request from '@/utils/request'
|
||||
import { getTaskApplications } from '@/api/tasks'
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { ElMessage } from 'element-plus'
|
||||
vi.mock('@/api/tasks', () => ({
|
||||
getTaskApplications: vi.fn(),
|
||||
createTaskApplication: vi.fn(),
|
||||
updateTaskApplication: vi.fn(),
|
||||
deleteTaskApplication: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('TaskForm.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.mock('@/utils/fetchTitle', () => ({
|
||||
getUrlTitle: vi.fn().mockResolvedValue(''),
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/markdown', () => ({
|
||||
renderMarkdown: vi.fn(() => '<p>preview</p>'),
|
||||
}))
|
||||
|
||||
async function mountAt(path: string) {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
await router.push(path)
|
||||
await router.isReady()
|
||||
return mount(TaskForm, {
|
||||
shallow: true,
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('TaskForm.vue', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
vi.mocked(getTaskApplications).mockResolvedValue({ code: 200, data: [] })
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
describe('priorityOptions', () => {
|
||||
it('contains values 0-5', () => {
|
||||
const priorityOptions = [0, 1, 2, 3, 4, 5]
|
||||
expect(priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
|
||||
expect(priorityOptions.length).toBe(6)
|
||||
it('uses real priority options and initial state', async () => {
|
||||
const wrapper = await mountAt('/add-task')
|
||||
|
||||
expect(wrapper.vm.priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
|
||||
expect(wrapper.vm.priority).toEqual({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
})
|
||||
|
||||
describe('priority state management', () => {
|
||||
it('initializes with all zeros', () => {
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
it('builds create payload from real form state and navigates to study', async () => {
|
||||
vi.mocked(request.post).mockResolvedValue({ code: 200, message: '创建任务成功' })
|
||||
const wrapper = await mountAt('/add-task')
|
||||
wrapper.vm.taskName = '学习递归'
|
||||
wrapper.vm.taskDescription = '理解递归的基本概念'
|
||||
wrapper.vm.materialUrl = 'https://example.com/recursion'
|
||||
wrapper.vm.priority.urgency = 3
|
||||
wrapper.vm.priority.importance = 4
|
||||
wrapper.vm.priority.contentDifficulty = 2
|
||||
wrapper.vm.priority.futureValue = 5
|
||||
wrapper.vm.priority.subjectivePriority = 3
|
||||
|
||||
expect(priority.urgency).toBe(0)
|
||||
expect(priority.importance).toBe(0)
|
||||
expect(priority.contentDifficulty).toBe(0)
|
||||
expect(priority.futureValue).toBe(0)
|
||||
expect(priority.subjectivePriority).toBe(0)
|
||||
})
|
||||
wrapper.vm.createTask()
|
||||
await flushPromises()
|
||||
|
||||
it('updates individual priority fields', () => {
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
|
||||
priority.urgency = 3
|
||||
priority.importance = 5
|
||||
|
||||
expect(priority.urgency).toBe(3)
|
||||
expect(priority.importance).toBe(5)
|
||||
expect(priority.contentDifficulty).toBe(0)
|
||||
expect(request.post).toHaveBeenCalledWith('/tasks', {
|
||||
taskName: '学习递归',
|
||||
taskDescription: '理解递归的基本概念',
|
||||
materialUrl: 'https://example.com/recursion',
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 3,
|
||||
})
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('创建任务成功')
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
|
||||
})
|
||||
|
||||
describe('task payload construction', () => {
|
||||
it('builds correct create payload', () => {
|
||||
const taskName = ref('学习递归')
|
||||
const taskDescription = ref('理解递归的基本概念')
|
||||
const materialURL = ref('https://example.com/recursion')
|
||||
const priority = reactive({
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 3,
|
||||
})
|
||||
|
||||
const payload = {
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
materialURL: materialURL.value,
|
||||
...priority,
|
||||
}
|
||||
|
||||
expect(payload).toEqual({
|
||||
taskName: '学习递归',
|
||||
taskDescription: '理解递归的基本概念',
|
||||
materialURL: 'https://example.com/recursion',
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('builds correct update payload with id', () => {
|
||||
const taskId = 42
|
||||
const taskName = ref('更新后的任务')
|
||||
const taskDescription = ref('')
|
||||
const materialURL = ref('')
|
||||
const priority = reactive({
|
||||
urgency: 1,
|
||||
importance: 2,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 3,
|
||||
subjectivePriority: 4,
|
||||
})
|
||||
|
||||
const payload = {
|
||||
id: taskId,
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
materialURL: materialURL.value,
|
||||
...priority,
|
||||
}
|
||||
|
||||
expect(payload.id).toBe(42)
|
||||
expect(payload.taskName).toBe('更新后的任务')
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadTask data mapping', () => {
|
||||
it('maps API response to form fields correctly', () => {
|
||||
const apiData = {
|
||||
it('loads update data from real API and maps it into form state', async () => {
|
||||
vi.mocked(request.get).mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
taskNum: 'T001',
|
||||
taskName: '学习DP',
|
||||
taskDescription: '动态规划',
|
||||
materialUrl: 'https://example.com/dp',
|
||||
@@ -129,52 +107,54 @@ describe('TaskForm.vue logic', () => {
|
||||
contentDifficulty: 3,
|
||||
futureValue: 4,
|
||||
subjectivePriority: 2,
|
||||
}
|
||||
|
||||
const taskName = ref('')
|
||||
const taskDescription = ref('')
|
||||
const materialURL = ref('')
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
|
||||
// Simulate loadTask mapping
|
||||
taskName.value = apiData.taskName
|
||||
taskDescription.value = apiData.taskDescription
|
||||
materialURL.value = apiData.materialURL || apiData.materialUrl || ''
|
||||
priority.urgency = apiData.urgency
|
||||
priority.importance = apiData.importance
|
||||
priority.contentDifficulty = apiData.contentDifficulty
|
||||
priority.futureValue = apiData.futureValue
|
||||
priority.subjectivePriority = apiData.subjectivePriority
|
||||
|
||||
expect(taskName.value).toBe('学习DP')
|
||||
expect(materialURL.value).toBe('https://example.com/dp')
|
||||
expect(priority.urgency).toBe(4)
|
||||
expect(priority.importance).toBe(5)
|
||||
},
|
||||
})
|
||||
|
||||
it('handles materialURL with camelCase variant', () => {
|
||||
const apiData = { materialURL: 'https://example.com/a', materialUrl: 'https://example.com/b' }
|
||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
||||
expect(result).toBe('https://example.com/a')
|
||||
})
|
||||
const wrapper = await mountAt('/update-task/42')
|
||||
await flushPromises()
|
||||
|
||||
it('falls back to empty string when no material URL', () => {
|
||||
const apiData = {} as any
|
||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
||||
expect(result).toBe('')
|
||||
expect(wrapper.vm.isUpdateMode).toBe(true)
|
||||
expect(wrapper.vm.taskNum).toBe('T001')
|
||||
expect(wrapper.vm.taskName).toBe('学习DP')
|
||||
expect(wrapper.vm.taskDescription).toBe('动态规划')
|
||||
expect(wrapper.vm.materialUrl).toBe('https://example.com/dp')
|
||||
expect(wrapper.vm.priority).toEqual({
|
||||
urgency: 4,
|
||||
importance: 5,
|
||||
contentDifficulty: 3,
|
||||
futureValue: 4,
|
||||
subjectivePriority: 2,
|
||||
})
|
||||
})
|
||||
|
||||
describe('redirect after successful action', () => {
|
||||
it('navigates to study page after create/update', () => {
|
||||
const pushTarget = '/study'
|
||||
expect(pushTarget).toBe('/study')
|
||||
it('builds update payload with id and navigates to study', async () => {
|
||||
vi.mocked(request.get).mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
taskNum: 'T001',
|
||||
taskName: '学习DP',
|
||||
taskDescription: '动态规划',
|
||||
materialUrl: '',
|
||||
urgency: 1,
|
||||
importance: 2,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 3,
|
||||
subjectivePriority: 4,
|
||||
},
|
||||
})
|
||||
vi.mocked(request.put).mockResolvedValue({ code: 200, message: '更新任务成功' })
|
||||
|
||||
const wrapper = await mountAt('/update-task/42')
|
||||
await flushPromises()
|
||||
wrapper.vm.taskName = '更新后的任务'
|
||||
wrapper.vm.updateTask()
|
||||
await flushPromises()
|
||||
|
||||
expect(request.put).toHaveBeenCalledWith('/tasks/42', expect.objectContaining({
|
||||
id: 42,
|
||||
taskName: '更新后的任务',
|
||||
}))
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('更新任务成功')
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,155 +1,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const mockInfo = vi.fn()
|
||||
const mockSuccess = vi.fn()
|
||||
const mockError = vi.fn()
|
||||
const mockWarning = vi.fn()
|
||||
const mockConfirm = vi.fn()
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: mockSuccess,
|
||||
error: mockError,
|
||||
warning: mockWarning,
|
||||
info: mockInfo,
|
||||
},
|
||||
ElMessageBox: {
|
||||
confirm: (...args: any[]) => mockConfirm(...args),
|
||||
},
|
||||
}))
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
import { useStudyFragment } from '@/components/composables/fragment'
|
||||
|
||||
vi.mock('@/api/reportFragments', () => ({
|
||||
createFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
|
||||
describe('useStudyFragment composable logic', () => {
|
||||
describe('useStudyFragment', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockConfirm.mockResolvedValue('confirm')
|
||||
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
|
||||
})
|
||||
|
||||
it('openFragmentDialog resets content and shows dialog', () => {
|
||||
const fragmentContent = ref('old content')
|
||||
const fragmentsDialogVisible = ref(false)
|
||||
const { fragmentsDialogVisible, fragmentContent, openFragmentDialog } = useStudyFragment()
|
||||
fragmentContent.value = 'old content'
|
||||
|
||||
fragmentContent.value = ''
|
||||
fragmentsDialogVisible.value = true
|
||||
openFragmentDialog()
|
||||
|
||||
expect(fragmentContent.value).toBe('')
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('closeFragmentDialog hides dialog on confirm', async () => {
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
it('closeFragmentDialog hides dialog after confirm', async () => {
|
||||
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
|
||||
fragmentsDialogVisible.value = true
|
||||
|
||||
await mockConfirm('确定取消生成吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(() => {
|
||||
fragmentsDialogVisible.value = false
|
||||
mockInfo('已取消生成')
|
||||
})
|
||||
await closeFragmentDialog()
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
expect(mockInfo).toHaveBeenCalledWith('已取消生成')
|
||||
expect(ElMessage.info).toHaveBeenCalledWith('已取消生成')
|
||||
})
|
||||
|
||||
it('closeFragmentDialog keeps dialog open on cancel', async () => {
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
mockConfirm.mockRejectedValue('cancel')
|
||||
it('closeFragmentDialog keeps dialog open when user cancels', async () => {
|
||||
vi.mocked(ElMessageBox.confirm).mockRejectedValue('cancel')
|
||||
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
|
||||
fragmentsDialogVisible.value = true
|
||||
|
||||
try {
|
||||
await mockConfirm('确定取消生成吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(() => {
|
||||
fragmentsDialogVisible.value = false
|
||||
})
|
||||
} catch {
|
||||
// User cancelled
|
||||
}
|
||||
await closeFragmentDialog()
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment warns if content is empty', async () => {
|
||||
const fragmentContent = ref(' ')
|
||||
it('confirmGenerateFragment warns when content is empty', async () => {
|
||||
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = ' '
|
||||
|
||||
if (!fragmentContent.value.trim()) {
|
||||
mockWarning('请输入学习内容!')
|
||||
}
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
expect(mockWarning).toHaveBeenCalledWith('请输入学习内容!')
|
||||
expect(result).toBe(false)
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习内容!')
|
||||
expect(createFragments).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment calls API and shows success', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
|
||||
const fragmentContent = ref('学习了递归算法')
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
const { fragmentContent, fragmentsDialogVisible, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习了递归算法'
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
const res = await createFragments('S001', fragmentContent.value)
|
||||
if (res.code === 200) {
|
||||
mockSuccess('学习残片生成成功!')
|
||||
fragmentsDialogVisible.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
|
||||
expect(mockSuccess).toHaveBeenCalledWith('学习残片生成成功!')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('学习残片生成成功!')
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles API failure', async () => {
|
||||
it('confirmGenerateFragment handles business failure', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
|
||||
const fragmentContent = ref('学习内容')
|
||||
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习内容'
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
const res = await createFragments('S001', fragmentContent.value)
|
||||
if (res.code !== 200) {
|
||||
mockError(res.message || '生成学习残片失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
expect(mockError).toHaveBeenCalledWith('生成失败')
|
||||
expect(result).toBe(false)
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('生成失败')
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles network error', async () => {
|
||||
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
|
||||
const fragmentContent = ref('学习内容')
|
||||
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习内容'
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
try {
|
||||
await createFragments('S001', fragmentContent.value)
|
||||
} catch (error: any) {
|
||||
mockError(error.message || '请求失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
expect(mockError).toHaveBeenCalledWith('网络超时')
|
||||
expect(result).toBe(false)
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('网络超时')
|
||||
})
|
||||
|
||||
it('prevents duplicate submission while creating fragment', async () => {
|
||||
let resolveCreate!: (value: any) => void
|
||||
vi.mocked(createFragments).mockImplementation(
|
||||
() => new Promise((resolve) => { resolveCreate = resolve }),
|
||||
)
|
||||
const { fragmentContent, creatingFragment, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习内容'
|
||||
|
||||
const first = confirmGenerateFragment('S001')
|
||||
const second = confirmGenerateFragment('S001')
|
||||
await Promise.resolve()
|
||||
|
||||
expect(createFragments).toHaveBeenCalledTimes(1)
|
||||
expect(creatingFragment.value).toBe(true)
|
||||
|
||||
resolveCreate({ code: 200 })
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(creatingFragment.value).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,88 +1,56 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
// We test the timer composable logic directly since it's a pure Vue composable
|
||||
// Extract the logic to test it in isolation
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { useTimer } from '@/components/composables/useTimer'
|
||||
|
||||
describe('useTimer', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
// Test the core timer logic that the composable uses
|
||||
it('formatTime converts seconds to HH:MM:SS', () => {
|
||||
const formatTime = (totalSeconds: number): string => {
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
|
||||
}
|
||||
it('syncDisplay writes formatted remaining time', () => {
|
||||
const { timerMinutes, timerSeconds, timerIsOver, syncDisplay } = useTimer()
|
||||
|
||||
expect(formatTime(0)).toBe('00:00:00')
|
||||
expect(formatTime(61)).toBe('00:01:01')
|
||||
expect(formatTime(3661)).toBe('01:01:01')
|
||||
expect(formatTime(59)).toBe('00:00:59')
|
||||
expect(formatTime(3600)).toBe('01:00:00')
|
||||
syncDisplay(61_000)
|
||||
expect(timerMinutes.value).toBe(1)
|
||||
expect(timerSeconds.value).toBe(1)
|
||||
expect(timerIsOver.value).toBe(false)
|
||||
|
||||
syncDisplay(0)
|
||||
expect(timerMinutes.value).toBe(0)
|
||||
expect(timerSeconds.value).toBe(0)
|
||||
expect(timerIsOver.value).toBe(true)
|
||||
})
|
||||
|
||||
it('formatTime handles large values', () => {
|
||||
const formatTime = (totalSeconds: number): string => {
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
|
||||
}
|
||||
it('runCountdown decreases remaining time and stops at zero', () => {
|
||||
const { timerMinutes, timerSeconds, timerRunning, timerIsOver, runCountdown, clear } = useTimer()
|
||||
|
||||
expect(formatTime(86399)).toBe('23:59:59')
|
||||
expect(formatTime(100000)).toBe('27:46:40')
|
||||
runCountdown(3000)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(timerMinutes.value).toBe(0)
|
||||
expect(timerSeconds.value).toBe(2)
|
||||
expect(timerRunning.value).toBe(true)
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(timerSeconds.value).toBe(0)
|
||||
expect(timerRunning.value).toBe(false)
|
||||
expect(timerIsOver.value).toBe(true)
|
||||
|
||||
clear()
|
||||
})
|
||||
|
||||
it('timer increments elapsedSeconds over time', () => {
|
||||
let elapsed = 0
|
||||
const interval = setInterval(() => {
|
||||
elapsed++
|
||||
}, 1000)
|
||||
it('notifies when countdown completes', () => {
|
||||
const { runCountdown, clear } = useTimer()
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
expect(elapsed).toBe(3)
|
||||
runCountdown(1000)
|
||||
vi.advanceTimersByTime(1000)
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(5)
|
||||
|
||||
clearInterval(interval)
|
||||
})
|
||||
|
||||
it('timer can be paused and resumed', () => {
|
||||
let elapsed = 0
|
||||
let intervalId: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const start = () => {
|
||||
if (!intervalId) {
|
||||
intervalId = setInterval(() => { elapsed++ }, 1000)
|
||||
}
|
||||
}
|
||||
const pause = () => {
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId)
|
||||
intervalId = null
|
||||
}
|
||||
}
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(2)
|
||||
|
||||
pause()
|
||||
vi.advanceTimersByTime(3000)
|
||||
expect(elapsed).toBe(2) // Should not change while paused
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(4)
|
||||
|
||||
pause()
|
||||
expect(ElMessageBox.alert).toHaveBeenCalled()
|
||||
clear()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,90 +1,36 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
||||
|
||||
// We test the guard logic by importing the router and simulating navigation
|
||||
// The router in src/router/index.ts uses createWebHistory which requires DOM,
|
||||
// so we'll test the guard logic by recreating the key patterns.
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import router from '@/router'
|
||||
|
||||
describe('route guards', () => {
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
function buildRouter() {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: { template: '<div/>' }, meta: { requiresAuth: false } },
|
||||
{ path: '/welcome', component: { template: '<div/>' }, meta: { requiresAuth: true } },
|
||||
{ path: '/study', component: { template: '<div/>' }, meta: { requiresAuth: true } },
|
||||
{ path: '/', redirect: '/login' },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
it('redirects unauthenticated user from protected route to /login', async () => {
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/welcome')
|
||||
await router.isReady()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('allows authenticated user to access protected route', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/welcome')
|
||||
await router.isReady()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('allows unauthenticated access to /login', async () => {
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('root path redirects to /login', async () => {
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/')
|
||||
await router.isReady()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
})
|
||||
|
||||
+27
-12
@@ -1,14 +1,29 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
// Mock Element Plus components globally
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
ElMessageBox: {
|
||||
confirm: vi.fn().mockResolvedValue('confirm'),
|
||||
},
|
||||
}))
|
||||
// 只 mock Element Plus 的服务,组件保持真实实现,方便测试里挂载真实组件
|
||||
vi.mock('element-plus', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('element-plus')>()
|
||||
return {
|
||||
...actual,
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
ElMessageBox: {
|
||||
confirm: vi.fn().mockResolvedValue('confirm'),
|
||||
alert: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
// jsdom 没有 Audio,组件和 useTimer 需要用到
|
||||
class MockAudio {
|
||||
loop = false
|
||||
currentTime = 0
|
||||
play = vi.fn().mockResolvedValue(undefined)
|
||||
pause = vi.fn()
|
||||
}
|
||||
|
||||
vi.stubGlobal('Audio', MockAudio)
|
||||
|
||||
@@ -22,15 +22,6 @@ vi.mock('axios', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
|
||||
describe('request utility', () => {
|
||||
@@ -125,7 +116,7 @@ describe('request utility', () => {
|
||||
})
|
||||
|
||||
it('should throw for unsupported method', () => {
|
||||
expect(() => request.request('patch', '/test', null)).toThrow('请求方法 patch 未实现')
|
||||
expect(() => request.request('patch', '/test', null)).toThrow('该功能暂不可用,请刷新后重试')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,7 +12,6 @@ export interface StandardMindMap {
|
||||
generator: "BUILTIN" | "AI" | "USER" | "USER_MERGE";
|
||||
generatorVersion?: string;
|
||||
sourceReportCount: number;
|
||||
sourceFragmentCount: number;
|
||||
generatedTime?: string;
|
||||
createdTime?: string;
|
||||
lastModifiedTime?: string;
|
||||
|
||||
@@ -14,6 +14,11 @@ export const endSession = (sessionNum: string, content: string = "任务结束")
|
||||
return request.post(`/study-sessions/${sessionNum}/study-sessions/ended`, { content });
|
||||
};
|
||||
|
||||
/** 误操作结束学习会话:需输入确认语,严格零数据关闭(删除会话与预期) */
|
||||
export const abortSession = (sessionNum: string, confirmation: string) => {
|
||||
return request.post(`/study-sessions/${sessionNum}/study-sessions/abort`, { confirmation });
|
||||
};
|
||||
|
||||
export const startOrContinueStudySession = (taskNum: string) => {
|
||||
return request.get(`/tasks/${taskNum}/study-sessions/start-or-continue`);
|
||||
};
|
||||
|
||||
+6
-3
@@ -38,20 +38,23 @@ a:hover {
|
||||
/* 按钮操作区统一规范:窄屏下操作按钮纵向全宽 */
|
||||
.action-row .el-button,
|
||||
.edit-actions .el-button,
|
||||
.fragment-edit-actions .el-button {
|
||||
.fragment-edit-actions .el-button,
|
||||
.task-actions .el-button {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.action-row,
|
||||
.edit-actions,
|
||||
.fragment-edit-actions {
|
||||
.fragment-edit-actions,
|
||||
.task-actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-row .el-button,
|
||||
.edit-actions .el-button,
|
||||
.fragment-edit-actions .el-button {
|
||||
.fragment-edit-actions .el-button,
|
||||
.task-actions .el-button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,8 @@ const submitForm = async (formEl: FormInstance | undefined) => {
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
defineExpose({ registerData, loading, submitForm, isNotEmpty });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
type="success"
|
||||
plain
|
||||
class="logout-btn"
|
||||
:loading="loggingOut"
|
||||
@click="handleLogout"
|
||||
>
|
||||
退出登录
|
||||
@@ -28,7 +29,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, ref } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import router from "@/router";
|
||||
@@ -38,18 +39,26 @@ const route = useRoute();
|
||||
const isLoginRoute = computed(() => route.path === "/login");
|
||||
const showBackButton = computed(() => route.path !== "/login" && route.path !== "/welcome");
|
||||
const pageTitle = computed(() => route.meta?.title as string | undefined);
|
||||
const loggingOut = ref(false);
|
||||
|
||||
const handleLogout = async () => {
|
||||
if (loggingOut.value) return;
|
||||
loggingOut.value = true;
|
||||
try {
|
||||
await logout();
|
||||
} catch {
|
||||
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
|
||||
} finally {
|
||||
try {
|
||||
await logout();
|
||||
} catch {
|
||||
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
|
||||
}
|
||||
localStorage.removeItem("isLoggedIn");
|
||||
ElMessage.success("已退出登录");
|
||||
await router.push("/login");
|
||||
} finally {
|
||||
loggingOut.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({ isLoginRoute, showBackButton, pageTitle, loggingOut, handleLogout });
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
+13
-24
@@ -1,18 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import {
|
||||
getReviewTaskStats,
|
||||
getTaskReview,
|
||||
type ReviewFeedItem,
|
||||
type ReviewTaskStats,
|
||||
} from "@/api/review";
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const loading = ref(false);
|
||||
const openingTaskNum = ref("");
|
||||
const tasks = ref<ReviewTaskStats[]>([]);
|
||||
|
||||
const summary = computed(() => ({
|
||||
@@ -40,21 +36,9 @@ const loadTasks = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const openTaskReview = async (row: ReviewTaskStats) => {
|
||||
const openTaskReview = (row: ReviewTaskStats) => {
|
||||
if (!row.taskNum) return;
|
||||
openingTaskNum.value = row.taskNum;
|
||||
try {
|
||||
const res = await getTaskReview(row.taskNum);
|
||||
const items: ReviewFeedItem[] = res?.data || [];
|
||||
const first = items[0];
|
||||
if (!first) {
|
||||
ElMessage.info("该任务暂无可复习内容");
|
||||
return;
|
||||
}
|
||||
router.push(`/review/detail/${first.sourceType.toLowerCase()}/${first.id}`);
|
||||
} finally {
|
||||
openingTaskNum.value = "";
|
||||
}
|
||||
router.push(`/review/detail/task/${encodeURIComponent(row.taskNum)}`);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
@@ -89,7 +73,6 @@ onMounted(() => {
|
||||
v-for="row in tasks"
|
||||
:key="row.taskNum"
|
||||
class="surface-card task-card"
|
||||
@click="openTaskReview(row)"
|
||||
>
|
||||
<div class="task-head">
|
||||
<strong>{{ row.taskName }}</strong>
|
||||
@@ -106,16 +89,15 @@ onMounted(() => {
|
||||
text
|
||||
type="success"
|
||||
size="small"
|
||||
:loading="openingTaskNum === row.taskNum"
|
||||
@click.stop="openTaskReview(row)"
|
||||
@click="openTaskReview(row)"
|
||||
>
|
||||
查看记录
|
||||
</el-button>
|
||||
<el-button
|
||||
text
|
||||
class="recall-button"
|
||||
type="success"
|
||||
size="small"
|
||||
@click.stop="router.push(`/review/recall/${row.taskNum}`)"
|
||||
@click="router.push(`/review/recall/${row.taskNum}`)"
|
||||
>
|
||||
回忆复习
|
||||
</el-button>
|
||||
@@ -172,7 +154,6 @@ onMounted(() => {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.task-head strong {
|
||||
@@ -193,6 +174,8 @@ onMounted(() => {
|
||||
|
||||
.task-actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
@@ -201,4 +184,10 @@ onMounted(() => {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.task-actions .recall-button {
|
||||
order: -1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -9,34 +9,29 @@ import {
|
||||
} from "@/api/review";
|
||||
import { getSessionDetail } from "@/api/studySessions";
|
||||
import { updateFragments } from "@/api/reportFragments";
|
||||
import { findNode } from "@/api/standardMindMap";
|
||||
import { ElMessage } from "element-plus";
|
||||
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
/** 调用 findNode API 匹配标准导图中的最近节点,跳转到回忆页 */
|
||||
const goToRecall = async () => {
|
||||
if (!content.value || !content.value.trim()) {
|
||||
router.push(`/review/recall/${taskNum.value}`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await findNode(taskNum.value, content.value.substring(0, 500));
|
||||
const data = res?.data;
|
||||
if (data?.path) {
|
||||
router.push(`/review/recall/${taskNum.value}?focusPath=${encodeURIComponent(data.path)}`);
|
||||
} else {
|
||||
router.push(`/review/recall/${taskNum.value}`);
|
||||
}
|
||||
} catch {
|
||||
router.push(`/review/recall/${taskNum.value}`);
|
||||
/** 直接进入回忆复习页,节点匹配交给目标页加载后处理 */
|
||||
const goToRecall = () => {
|
||||
const tn = taskNum.value;
|
||||
if (!tn) return;
|
||||
if (content.value && content.value.trim()) {
|
||||
router.push(`/review/recall/${tn}?focusContent=${encodeURIComponent(content.value.substring(0, 500))}`);
|
||||
} else {
|
||||
router.push(`/review/recall/${tn}`);
|
||||
}
|
||||
};
|
||||
|
||||
const contentType = computed(() => route.params.type as string);
|
||||
const contentId = computed(() => Number(route.params.id));
|
||||
const isTaskMode = computed(() => !!route.params.taskNum);
|
||||
const activeType = ref<string | undefined>(undefined);
|
||||
const activeId = ref<number | undefined>(undefined);
|
||||
const contentType = computed(() => isTaskMode.value ? activeType.value : (route.params.type as string));
|
||||
const contentId = computed(() => isTaskMode.value ? activeId.value ?? 0 : Number(route.params.id));
|
||||
const taskModeTaskNum = computed(() => route.params.taskNum as string | undefined);
|
||||
|
||||
const loading = ref(true);
|
||||
const content = ref("");
|
||||
@@ -118,7 +113,19 @@ const loadDetail = async () => {
|
||||
taskNum.value = "";
|
||||
sessionInfo.value = null;
|
||||
taskSessions.value = [];
|
||||
if (isTaskMode.value) {
|
||||
activeType.value = undefined;
|
||||
activeId.value = undefined;
|
||||
}
|
||||
try {
|
||||
if (isTaskMode.value && taskModeTaskNum.value) {
|
||||
const taskRes = await getTaskReview(taskModeTaskNum.value);
|
||||
const items: ReviewFeedItem[] = taskRes?.data || [];
|
||||
const first = items[0];
|
||||
if (!first) return;
|
||||
activeType.value = first.sourceType.toLowerCase();
|
||||
activeId.value = first.id;
|
||||
}
|
||||
let res;
|
||||
if (contentType.value === "report") {
|
||||
res = await getReportDetail(contentId.value);
|
||||
@@ -194,8 +201,12 @@ const saveEdit = async () => {
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [contentType.value, contentId.value],
|
||||
() => [route.params.type, route.params.id, route.params.taskNum],
|
||||
() => {
|
||||
if (!isTaskMode.value) {
|
||||
activeType.value = undefined;
|
||||
activeId.value = undefined;
|
||||
}
|
||||
loadDetail();
|
||||
},
|
||||
{ immediate: true },
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { ref, onMounted, computed } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
findNode,
|
||||
getStandardMindMap,
|
||||
regenerateStandardMindMap,
|
||||
recallCompare,
|
||||
@@ -31,6 +32,7 @@ const hasCompared = ref(false);
|
||||
|
||||
// 起点节点选择
|
||||
const focusPath = ref((route.query.focusPath as string) || "");
|
||||
const focusContent = ref((route.query.focusContent as string) || "");
|
||||
const focusConfirmVisible = ref(false);
|
||||
const selectedNodeInfo = ref<{ title: string; path: string; childCount: number } | null>(null);
|
||||
|
||||
@@ -114,6 +116,17 @@ const loadData = async () => {
|
||||
try {
|
||||
const res = await getStandardMindMap(taskNum.value);
|
||||
standard.value = res?.data || null;
|
||||
if (focusContent.value && standard.value) {
|
||||
try {
|
||||
const nodeRes = await findNode(taskNum.value, focusContent.value.substring(0, 500));
|
||||
const data = nodeRes?.data;
|
||||
if (data?.path) {
|
||||
focusPath.value = data.path;
|
||||
}
|
||||
} catch {
|
||||
// 匹配失败时仍可进入回忆页
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
standard.value = null;
|
||||
} finally {
|
||||
@@ -382,7 +395,7 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="recall-page">
|
||||
<section class="recall-page" v-loading="loading">
|
||||
<!-- 顶部操作栏 -->
|
||||
<div class="page-header">
|
||||
<h2>回忆复习</h2>
|
||||
@@ -541,7 +554,7 @@ onMounted(() => {
|
||||
<div v-else-if="standardExpanded" class="standard-content">
|
||||
<div class="standard-meta">
|
||||
<span>来源:{{ standard.generator }}</span>
|
||||
<span>参考:{{ standard.sourceReportCount }} 份报告 + {{ standard.sourceFragmentCount }} 份残片</span>
|
||||
<span>参考:{{ standard.sourceReportCount }} 份学习报告</span>
|
||||
</div>
|
||||
<p v-if="!focusPath && !hasCompared" class="select-hint">
|
||||
点击导图节点即可选择复习起点,选好后凭记忆在上方补全知识点。
|
||||
|
||||
+182
-38
@@ -5,8 +5,10 @@ import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import request from "@/utils/request";
|
||||
import { useTimer } from "@/components/composables/useTimer";
|
||||
import {
|
||||
abortSession,
|
||||
continueSession,
|
||||
endSession,
|
||||
getActiveSession,
|
||||
getSessionDetail,
|
||||
pauseSession,
|
||||
startOrContinueStudySession,
|
||||
@@ -24,8 +26,21 @@ const {
|
||||
openFragmentDialog,
|
||||
closeFragmentDialog,
|
||||
confirmGenerateFragment,
|
||||
creatingFragment,
|
||||
} = useStudyFragment();
|
||||
|
||||
const pageLoading = ref(true);
|
||||
const timerActionLoading = ref(false);
|
||||
const endingSession = ref(false);
|
||||
// 误操作结束(零数据关闭)
|
||||
const MISOPERATION_PHRASE = "我误操作导致开启了本次学习";
|
||||
const abortDialogVisible = ref(false);
|
||||
const abortConfirmation = ref("");
|
||||
const abortingSession = ref(false);
|
||||
const canAbortSession = computed(
|
||||
() => taskInfo.value.sessionState !== "ENDED" && fragmentsList.value.length === 0,
|
||||
);
|
||||
|
||||
const summaryDialogVisible = ref(false);
|
||||
const summaryContent = ref("");
|
||||
const summaryPreview = ref(false);
|
||||
@@ -306,39 +321,51 @@ const statusText = computed(() => {
|
||||
});
|
||||
|
||||
const startTimer = async () => {
|
||||
if (taskInfo.value.sessionState === "PAUSED") {
|
||||
const res = await continueSession(taskInfo.value.sessionNum);
|
||||
if (res.code === 200) ElMessage.success("任务继续");
|
||||
await loadTaskSession();
|
||||
if (timerActionLoading.value) return;
|
||||
timerActionLoading.value = true;
|
||||
try {
|
||||
if (taskInfo.value.sessionState === "PAUSED") {
|
||||
const res = await continueSession(taskInfo.value.sessionNum);
|
||||
if (res.code === 200) ElMessage.success("任务继续");
|
||||
await loadTaskSession();
|
||||
}
|
||||
// 手动开始 → 清除休息状态
|
||||
localStorage.removeItem(BREAK_END_KEY.value);
|
||||
isBreak.value = false;
|
||||
const duration = taskInfo.value.pointerPosition || 25 * 60 * 1000;
|
||||
runCountdown(duration);
|
||||
} finally {
|
||||
timerActionLoading.value = false;
|
||||
}
|
||||
// 手动开始 → 清除休息状态
|
||||
localStorage.removeItem(BREAK_END_KEY.value);
|
||||
isBreak.value = false;
|
||||
const duration = taskInfo.value.pointerPosition || 25 * 60 * 1000;
|
||||
runCountdown(duration);
|
||||
};
|
||||
|
||||
const stopTimer = async () => {
|
||||
const res = await pauseSession(taskInfo.value.sessionNum);
|
||||
if (res.code === 200) {
|
||||
ElMessage.success("任务暂停");
|
||||
// 重新获取会话数据,同步后端计算后的时间字段
|
||||
try {
|
||||
const detail = await getSessionDetail(taskInfo.value.sessionNum);
|
||||
if (detail?.data) {
|
||||
const d = detail.data;
|
||||
taskInfo.value.sessionState = d.sessionState ?? "PAUSED";
|
||||
taskInfo.value.actualTime = d.actualTime ?? 0;
|
||||
taskInfo.value.effectiveTime = d.effectiveTime ?? 0;
|
||||
taskInfo.value.effectivenessRatio = d.effectivenessRatio ?? 0;
|
||||
taskInfo.value.startTime = d.startTime ?? taskInfo.value.startTime;
|
||||
taskInfo.value.endTime = d.endTime ?? "";
|
||||
taskInfo.value.lastStartTime = d.lastStartTime ?? "";
|
||||
taskInfo.value.pointerPosition = d.pointerPosition ?? 0;
|
||||
if (timerActionLoading.value) return;
|
||||
timerActionLoading.value = true;
|
||||
try {
|
||||
const res = await pauseSession(taskInfo.value.sessionNum);
|
||||
if (res.code === 200) {
|
||||
ElMessage.success("任务暂停");
|
||||
// 重新获取会话数据,同步后端计算后的时间字段
|
||||
try {
|
||||
const detail = await getSessionDetail(taskInfo.value.sessionNum);
|
||||
if (detail?.data) {
|
||||
const d = detail.data;
|
||||
taskInfo.value.sessionState = d.sessionState ?? "PAUSED";
|
||||
taskInfo.value.actualTime = d.actualTime ?? 0;
|
||||
taskInfo.value.effectiveTime = d.effectiveTime ?? 0;
|
||||
taskInfo.value.effectivenessRatio = d.effectivenessRatio ?? 0;
|
||||
taskInfo.value.startTime = d.startTime ?? taskInfo.value.startTime;
|
||||
taskInfo.value.endTime = d.endTime ?? "";
|
||||
taskInfo.value.lastStartTime = d.lastStartTime ?? "";
|
||||
taskInfo.value.pointerPosition = d.pointerPosition ?? 0;
|
||||
}
|
||||
} catch {
|
||||
taskInfo.value.sessionState = "PAUSED";
|
||||
}
|
||||
} catch {
|
||||
taskInfo.value.sessionState = "PAUSED";
|
||||
}
|
||||
} finally {
|
||||
timerActionLoading.value = false;
|
||||
}
|
||||
clear();
|
||||
clearBreakState();
|
||||
@@ -364,6 +391,8 @@ const endTimer = async (content: string) => {
|
||||
// 用户取消结束会话,不做任何操作
|
||||
return;
|
||||
}
|
||||
if (endingSession.value) return;
|
||||
endingSession.value = true;
|
||||
|
||||
try {
|
||||
const res = await endSession(taskInfo.value.sessionNum, content);
|
||||
@@ -382,6 +411,8 @@ const endTimer = async (content: string) => {
|
||||
await router.push("/study");
|
||||
} catch {
|
||||
ElMessage.error("结束会话失败,请重试");
|
||||
} finally {
|
||||
endingSession.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -410,6 +441,41 @@ const closeSummaryDialog = () => {
|
||||
summaryDialogVisible.value = false;
|
||||
if (summaryLoadingTimer) { clearInterval(summaryLoadingTimer); summaryLoadingTimer = null; }
|
||||
};
|
||||
const openAbortDialog = () => {
|
||||
abortConfirmation.value = "";
|
||||
abortDialogVisible.value = true;
|
||||
};
|
||||
|
||||
const closeExpectationAndOpenAbort = () => {
|
||||
expectationDialogVisible.value = false;
|
||||
openAbortDialog();
|
||||
};
|
||||
|
||||
const confirmAbort = async () => {
|
||||
if (abortConfirmation.value.trim() !== MISOPERATION_PHRASE) {
|
||||
ElMessage.warning("确认语输入不正确,请重新输入");
|
||||
return;
|
||||
}
|
||||
if (abortingSession.value) return;
|
||||
abortingSession.value = true;
|
||||
try {
|
||||
const res = await abortSession(taskInfo.value.sessionNum, abortConfirmation.value.trim());
|
||||
if (res.code === 200) {
|
||||
ElMessage.success("本次学习已关闭,未产生任何数据");
|
||||
clear();
|
||||
clearBreakState();
|
||||
localStorage.removeItem("activeSession");
|
||||
await router.push("/study");
|
||||
} else {
|
||||
ElMessage.error(res.message || "误操作结束失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || "误操作结束失败,请重试");
|
||||
}
|
||||
finally {
|
||||
abortingSession.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const restTimer = async () => {
|
||||
await stopTimer();
|
||||
@@ -434,6 +500,27 @@ const restTimer = async () => {
|
||||
|
||||
const loadTaskSession = async () => {
|
||||
try {
|
||||
const activeRes = await getActiveSession();
|
||||
const active = activeRes?.data;
|
||||
if (active?.taskNum && active.taskNum !== taskNum) {
|
||||
let goToActive = false;
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`你还有一个未完成的学习任务「${active.taskName}」(${active.sessionNum}),是否前往继续?`,
|
||||
"有其他任务正在进行",
|
||||
{ confirmButtonText: "前往继续", cancelButtonText: "取消", type: "warning" },
|
||||
);
|
||||
goToActive = true;
|
||||
} catch {
|
||||
// 用户取消,不开始当前任务
|
||||
}
|
||||
if (goToActive) {
|
||||
router.push(`/start-task/${encodeURIComponent(active.taskNum)}`);
|
||||
} else {
|
||||
ElMessage.warning("请先完成进行中的任务后再开始");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const res = await startOrContinueStudySession(taskNum);
|
||||
Object.assign(taskInfo.value, res.data);
|
||||
await loadExpectation();
|
||||
@@ -519,12 +606,16 @@ const saveExpectation = async () => {
|
||||
};
|
||||
|
||||
const initPage = async () => {
|
||||
const hasPermission = await checkAudioPermission();
|
||||
if (!hasPermission) {
|
||||
const activated = await requestAudioPermission();
|
||||
if (!activated) return;
|
||||
try {
|
||||
const hasPermission = await checkAudioPermission();
|
||||
if (!hasPermission) {
|
||||
const activated = await requestAudioPermission();
|
||||
if (!activated) return;
|
||||
}
|
||||
await loadTaskSession();
|
||||
} finally {
|
||||
pageLoading.value = false;
|
||||
}
|
||||
await loadTaskSession();
|
||||
};
|
||||
|
||||
// 碎片列表
|
||||
@@ -594,11 +685,25 @@ onUnmounted(() => {
|
||||
}
|
||||
clear();
|
||||
});
|
||||
|
||||
defineExpose({
|
||||
taskInfo,
|
||||
timerRunning,
|
||||
timerIsOver,
|
||||
startTimer,
|
||||
stopTimer,
|
||||
endTimer,
|
||||
openAbortDialog,
|
||||
confirmAbort,
|
||||
abortConfirmation,
|
||||
syncDisplay,
|
||||
clear,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<section class="start-page">
|
||||
<section class="start-page" v-loading="pageLoading">
|
||||
<el-alert
|
||||
v-if="showResumeHint"
|
||||
title="已恢复上次的学习会话,继续学习吧"
|
||||
@@ -702,12 +807,13 @@ onUnmounted(() => {
|
||||
<el-button @click="openFragmentDialog">生成残片</el-button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<el-button type="success" @click="startTimer" :disabled="timerRunning">开始</el-button>
|
||||
<el-button @click="stopTimer" :disabled="!timerRunning" v-if="!timerIsOver">暂停</el-button>
|
||||
<el-button type="success" @click="startTimer" :disabled="timerRunning" :loading="timerActionLoading">开始</el-button>
|
||||
<el-button @click="stopTimer" :disabled="!timerRunning" :loading="timerActionLoading" v-if="!timerIsOver">暂停</el-button>
|
||||
<el-button @click="openFragmentDialog">生成残片</el-button>
|
||||
<el-button v-if="timerIsOver" plain type="success" @click="restTimer">休息</el-button>
|
||||
<el-button v-if="timerIsOver" plain type="success" @click="restTimer" :loading="timerActionLoading">休息</el-button>
|
||||
</template>
|
||||
<el-button type="danger" plain @click="openSummaryDialog">结束会话</el-button>
|
||||
<el-button v-if="canAbortSession" text type="danger" @click="openAbortDialog">误操作结束</el-button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
@@ -788,7 +894,7 @@ onUnmounted(() => {
|
||||
/>
|
||||
<template #footer>
|
||||
<el-button @click="closeFragmentDialog">取消</el-button>
|
||||
<el-button type="success" @click="confirmGenerateFragment(taskInfo.sessionNum)">确定生成</el-button>
|
||||
<el-button type="success" :loading="creatingFragment" @click="confirmGenerateFragment(taskInfo.sessionNum)">确定生成</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
@@ -808,6 +914,7 @@ onUnmounted(() => {
|
||||
:rows="4"
|
||||
/>
|
||||
<template #footer>
|
||||
<el-button v-if="!expectationSaved" text type="danger" @click="closeExpectationAndOpenAbort">误操作结束</el-button>
|
||||
<el-button v-if="expectationSaved" @click="expectationDialogVisible = false">取消</el-button>
|
||||
<el-button type="success" :loading="savingExpectation" @click="saveExpectation">确定</el-button>
|
||||
</template>
|
||||
@@ -848,7 +955,33 @@ onUnmounted(() => {
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="closeSummaryDialog">取消</el-button>
|
||||
<el-button type="success" @click="endTimer(summaryContent)">确认结束</el-button>
|
||||
<el-button type="success" :loading="endingSession" @click="endTimer(summaryContent)">确认结束</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="abortDialogVisible"
|
||||
title="误操作结束"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="false"
|
||||
>
|
||||
<p class="dialog-hint">本次学习会话尚未产生学习残片,可以零数据关闭。关闭后会话与学习预期将被删除,不会留下任何学习记录。</p>
|
||||
<p class="dialog-hint">如果是误操作开启了本次学习,请输入以下内容以确认:</p>
|
||||
<div class="abort-phrase">{{ MISOPERATION_PHRASE }}</div>
|
||||
<el-input
|
||||
v-model="abortConfirmation"
|
||||
placeholder="请输入上方确认语"
|
||||
@keyup.enter="confirmAbort"
|
||||
/>
|
||||
<template #footer>
|
||||
<el-button @click="abortDialogVisible = false">取消</el-button>
|
||||
<el-button
|
||||
type="danger"
|
||||
:loading="abortingSession"
|
||||
:disabled="abortConfirmation.trim() !== MISOPERATION_PHRASE"
|
||||
@click="confirmAbort"
|
||||
>确认误操作结束</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
@@ -1240,4 +1373,15 @@ onUnmounted(() => {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.abort-phrase {
|
||||
margin-bottom: 12px;
|
||||
padding: 8px 12px;
|
||||
border: 1px dashed var(--el-color-danger);
|
||||
border-radius: 6px;
|
||||
color: var(--el-color-danger);
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
+29
-31
@@ -4,7 +4,6 @@ import request from "@/utils/request";
|
||||
import router from "@/router";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { getReviewTaskStatsByTask } from "@/api/review";
|
||||
import { getActiveSession } from "@/api/studySessions";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { applicationStatusOptions } from "@/utils/taskApplication";
|
||||
|
||||
@@ -45,6 +44,9 @@ const pageSize = 20;
|
||||
const taskApplications = ref<TaskApplication[]>([]);
|
||||
const applicationsLoading = ref(false);
|
||||
const appUrlTitles = ref<Record<number, string>>({});
|
||||
const updatingApplicationId = ref<number | null>(null);
|
||||
const removingTask = ref(false);
|
||||
const weightsLoading = ref(false);
|
||||
|
||||
const selectedTask = computed(() =>
|
||||
tasks.value.find((item) => item.taskId === selectedTaskId.value) || null
|
||||
@@ -105,6 +107,8 @@ async function loadTaskApplications(taskNum: string) {
|
||||
}
|
||||
|
||||
const changeApplicationStatus = async (item: TaskApplication) => {
|
||||
if (updatingApplicationId.value !== null) return;
|
||||
updatingApplicationId.value = item.id;
|
||||
try {
|
||||
await updateTaskApplication(item.id, {
|
||||
title: item.title,
|
||||
@@ -118,6 +122,8 @@ const changeApplicationStatus = async (item: TaskApplication) => {
|
||||
if (selectedTask.value) {
|
||||
await loadTaskApplications(selectedTask.value.taskNum);
|
||||
}
|
||||
} finally {
|
||||
updatingApplicationId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -179,30 +185,12 @@ const handlePageChange = (page: number) => {
|
||||
fetchTasks(page);
|
||||
};
|
||||
|
||||
const startTask = async () => {
|
||||
const startTask = () => {
|
||||
if (!selectedTask.value) {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
return;
|
||||
}
|
||||
const taskNum = selectedTask.value.taskNum;
|
||||
try {
|
||||
const res = await getActiveSession(taskNum);
|
||||
if (res?.code === 200 && res.data) {
|
||||
// 有其他任务的活跃会话
|
||||
const active = res.data;
|
||||
ElMessageBox.confirm(
|
||||
`你还有一个未完成的学习任务「${active.taskName}」(${active.sessionNum}),是否前往继续?`,
|
||||
"有其他任务正在进行",
|
||||
{ confirmButtonText: "前往继续", cancelButtonText: "取消", type: "warning" }
|
||||
).then(() => {
|
||||
router.push(`/start-task/${encodeURIComponent(active.taskNum)}`);
|
||||
}).catch(() => {});
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 查询失败不阻塞,直接跳转
|
||||
}
|
||||
router.push(`/start-task/${encodeURIComponent(taskNum)}`);
|
||||
router.push(`/start-task/${encodeURIComponent(selectedTask.value.taskNum)}`);
|
||||
};
|
||||
|
||||
const addTask = () => {
|
||||
@@ -222,6 +210,8 @@ const removeTask = async () => {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
return;
|
||||
}
|
||||
if (removingTask.value) return;
|
||||
removingTask.value = true;
|
||||
const target = selectedTask.value;
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除任务「${target.title}」?关联的学习会话、学习报告、应用场景等数据将被一并删除。`, "确认删除", {
|
||||
@@ -229,14 +219,16 @@ const removeTask = async () => {
|
||||
cancelButtonText: "取消",
|
||||
type: "warning",
|
||||
});
|
||||
const res = await request.del(`/tasks/${target.taskId}`, {});
|
||||
if (res.code === 200) {
|
||||
ElMessage.success(`任务 ${target.title} 删除成功`);
|
||||
tasks.value = tasks.value.filter((item) => item.taskId !== target.taskId);
|
||||
selectedTaskId.value = tasks.value[0]?.taskId ?? null;
|
||||
}
|
||||
} catch {
|
||||
return; // 用户取消
|
||||
}
|
||||
const res = await request.del(`/tasks/${target.taskId}`, {});
|
||||
if (res.code === 200) {
|
||||
ElMessage.success(`任务 ${target.title} 删除成功`);
|
||||
tasks.value = tasks.value.filter((item) => item.taskId !== target.taskId);
|
||||
selectedTaskId.value = tasks.value[0]?.taskId ?? null;
|
||||
// 用户取消或删除失败,保持页面状态
|
||||
} finally {
|
||||
removingTask.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -256,6 +248,8 @@ const weightsSum = computed(() =>
|
||||
);
|
||||
|
||||
const openWeightsDialog = async () => {
|
||||
if (weightsLoading.value) return;
|
||||
weightsLoading.value = true;
|
||||
try {
|
||||
const res = await getPriorityWeights();
|
||||
const data = res?.data;
|
||||
@@ -267,8 +261,10 @@ const openWeightsDialog = async () => {
|
||||
}
|
||||
} catch {
|
||||
// 读取失败时保持默认值
|
||||
} finally {
|
||||
weightsLoading.value = false;
|
||||
weightsDialogVisible.value = true;
|
||||
}
|
||||
weightsDialogVisible.value = true;
|
||||
};
|
||||
|
||||
const saveWeights = async () => {
|
||||
@@ -404,6 +400,8 @@ onMounted(() => {
|
||||
v-model="item.status"
|
||||
size="small"
|
||||
class="application-status"
|
||||
:loading="updatingApplicationId === item.id"
|
||||
:disabled="updatingApplicationId !== null"
|
||||
@change="changeApplicationStatus(item)"
|
||||
>
|
||||
<el-option
|
||||
@@ -432,8 +430,8 @@ onMounted(() => {
|
||||
<el-button type="success" size="large" @click="startTask">开始任务</el-button>
|
||||
<el-button @click="addTask">添加任务</el-button>
|
||||
<el-button @click="changeTask">更新任务</el-button>
|
||||
<el-button @click="openWeightsDialog">权重配置</el-button>
|
||||
<el-button type="danger" @click="removeTask">删除任务</el-button>
|
||||
<el-button :loading="weightsLoading" @click="openWeightsDialog">权重配置</el-button>
|
||||
<el-button type="danger" :loading="removingTask" @click="removeTask">删除任务</el-button>
|
||||
</aside>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
+130
-77
@@ -40,7 +40,11 @@ const applicationLoading = ref(false);
|
||||
const appUrlTitles = ref<Record<number, string>>({});
|
||||
const applicationDialogVisible = ref(false);
|
||||
const applicationSaving = ref(false);
|
||||
const deletingApplicationId = ref<number | null>(null);
|
||||
const editingApplicationId = ref<number | null>(null);
|
||||
const pageLoading = ref(false);
|
||||
const submitting = ref(false);
|
||||
const previewLoading = ref(false);
|
||||
const applicationForm = ref<{
|
||||
title: string;
|
||||
description: string;
|
||||
@@ -135,13 +139,19 @@ const editApplication = (item: TaskApplication) => {
|
||||
};
|
||||
|
||||
const removeApplication = async (item: TaskApplication) => {
|
||||
await deleteTaskApplication(item.id);
|
||||
ElMessage.success("应用场景已删除");
|
||||
if (editingApplicationId.value === item.id) {
|
||||
resetApplicationForm();
|
||||
}
|
||||
if (taskNum.value) {
|
||||
await loadApplications(taskNum.value);
|
||||
if (deletingApplicationId.value !== null) return;
|
||||
deletingApplicationId.value = item.id;
|
||||
try {
|
||||
await deleteTaskApplication(item.id);
|
||||
ElMessage.success("应用场景已删除");
|
||||
if (editingApplicationId.value === item.id) {
|
||||
resetApplicationForm();
|
||||
}
|
||||
if (taskNum.value) {
|
||||
await loadApplications(taskNum.value);
|
||||
}
|
||||
} finally {
|
||||
deletingApplicationId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -168,71 +178,80 @@ const convertMaterialUrls = async () => {
|
||||
materialUrl.value = result;
|
||||
};
|
||||
|
||||
const createTask = () => {
|
||||
convertMaterialUrls().then(() => {
|
||||
request
|
||||
.post("/tasks", {
|
||||
const createTask = async () => {
|
||||
if (submitting.value) return;
|
||||
submitting.value = true;
|
||||
try {
|
||||
await convertMaterialUrls();
|
||||
const result = await request.post("/tasks", {
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
materialUrl: materialUrl.value,
|
||||
...priority.value,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("创建任务成功");
|
||||
router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务创建失败:" + result.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const loadTask = () => {
|
||||
if (taskId !== null) {
|
||||
request.get(`/tasks/${taskId}`, {}).then((result) => {
|
||||
if (result.code === 200) {
|
||||
const data = result.data;
|
||||
taskNum.value = data.taskNum || "";
|
||||
taskName.value = data.taskName;
|
||||
taskDescription.value = data.taskDescription;
|
||||
materialUrl.value = data.materialUrl || "";
|
||||
priority.value = {
|
||||
urgency: data.urgency,
|
||||
importance: data.importance,
|
||||
contentDifficulty: data.contentDifficulty,
|
||||
futureValue: data.futureValue,
|
||||
subjectivePriority: data.subjectivePriority,
|
||||
};
|
||||
if (taskNum.value) {
|
||||
loadApplications(taskNum.value);
|
||||
}
|
||||
} else {
|
||||
ElMessage.error(`任务加载失败:${result.message}`);
|
||||
}
|
||||
});
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("创建任务成功");
|
||||
await router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务创建失败:" + result.message);
|
||||
}
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const updateTask = () => {
|
||||
convertMaterialUrls().then(() => {
|
||||
request
|
||||
.put("/tasks/" + taskId, {
|
||||
const loadTask = async () => {
|
||||
if (taskId === null) return;
|
||||
pageLoading.value = true;
|
||||
try {
|
||||
const result = await request.get(`/tasks/${taskId}`, {});
|
||||
if (result.code === 200) {
|
||||
const data = result.data;
|
||||
taskNum.value = data.taskNum || "";
|
||||
taskName.value = data.taskName;
|
||||
taskDescription.value = data.taskDescription;
|
||||
materialUrl.value = data.materialUrl || "";
|
||||
priority.value = {
|
||||
urgency: data.urgency,
|
||||
importance: data.importance,
|
||||
contentDifficulty: data.contentDifficulty,
|
||||
futureValue: data.futureValue,
|
||||
subjectivePriority: data.subjectivePriority,
|
||||
};
|
||||
if (taskNum.value) {
|
||||
loadApplications(taskNum.value);
|
||||
}
|
||||
} else {
|
||||
ElMessage.error(`任务加载失败:${result.message}`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error?.message || "任务加载失败,请重试");
|
||||
} finally {
|
||||
pageLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const updateTask = async () => {
|
||||
if (submitting.value) return;
|
||||
submitting.value = true;
|
||||
try {
|
||||
await convertMaterialUrls();
|
||||
const result = await request.put("/tasks/" + taskId, {
|
||||
id: taskId,
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
materialUrl: materialUrl.value,
|
||||
...priority.value,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("更新任务成功");
|
||||
router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务更新失败:" + result.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("更新任务成功");
|
||||
await router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务更新失败:" + result.message);
|
||||
}
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const cancelTask = () => {
|
||||
@@ -240,16 +259,17 @@ const cancelTask = () => {
|
||||
router.push({ name: "study" });
|
||||
};
|
||||
|
||||
const submitTask = () => {
|
||||
const submitTask = async () => {
|
||||
if (submitting.value) return;
|
||||
switch (route.name) {
|
||||
case "add-task":
|
||||
createTask();
|
||||
await createTask();
|
||||
break;
|
||||
case "update-task":
|
||||
updateTask();
|
||||
await updateTask();
|
||||
break;
|
||||
default:
|
||||
ElMessage.error("未知操作类型");
|
||||
ElMessage.error("该功能暂不可用,请刷新后重试");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -275,23 +295,48 @@ const showPreview = ref(false);
|
||||
const materialPreview = ref("");
|
||||
|
||||
async function previewMaterial() {
|
||||
showPreview.value = true;
|
||||
const raw = materialUrl.value || "";
|
||||
if (!raw.trim()) { materialPreview.value = ""; return; }
|
||||
const titles: Record<string, string> = {};
|
||||
const bareUrls = new Set<string>();
|
||||
raw.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
bareUrls.add(url.replace(/[.。,,;;!!??)】」』\]]+$/, ""));
|
||||
return url;
|
||||
});
|
||||
const results = await Promise.all([...bareUrls].map(async (u) => ({ u, t: await getUrlTitle(u) })));
|
||||
results.forEach(({ u, t }) => { titles[u] = t; });
|
||||
materialPreview.value = renderMarkdown(raw, titles);
|
||||
if (previewLoading.value) return;
|
||||
previewLoading.value = true;
|
||||
try {
|
||||
const raw = materialUrl.value || "";
|
||||
if (!raw.trim()) {
|
||||
materialPreview.value = "";
|
||||
showPreview.value = true;
|
||||
return;
|
||||
}
|
||||
const titles: Record<string, string> = {};
|
||||
const bareUrls = new Set<string>();
|
||||
raw.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
bareUrls.add(url.replace(/[.。,,;;!!??)】」』\]]+$/, ""));
|
||||
return url;
|
||||
});
|
||||
const results = await Promise.all([...bareUrls].map(async (u) => ({ u, t: await getUrlTitle(u) })));
|
||||
results.forEach(({ u, t }) => { titles[u] = t; });
|
||||
materialPreview.value = renderMarkdown(raw, titles);
|
||||
showPreview.value = true;
|
||||
} finally {
|
||||
previewLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
priorityOptions,
|
||||
priority,
|
||||
taskNum,
|
||||
taskName,
|
||||
taskDescription,
|
||||
materialUrl,
|
||||
isUpdateMode,
|
||||
loadTask,
|
||||
createTask,
|
||||
updateTask,
|
||||
submitTask,
|
||||
convertMaterialUrls,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="task-form-page">
|
||||
<section class="task-form-page" v-loading="pageLoading">
|
||||
<el-form label-position="top" class="surface-card form-shell">
|
||||
<div class="group">
|
||||
<h3>基础信息</h3>
|
||||
@@ -310,6 +355,7 @@ async function previewMaterial() {
|
||||
text
|
||||
size="small"
|
||||
type="primary"
|
||||
:loading="previewLoading"
|
||||
@click="previewMaterial()"
|
||||
>预览</el-button>
|
||||
<el-button
|
||||
@@ -387,7 +433,14 @@ async function previewMaterial() {
|
||||
</el-link>
|
||||
<div class="application-actions">
|
||||
<el-button text type="primary" size="small" @click="editApplication(item)">编辑</el-button>
|
||||
<el-button text type="danger" size="small" @click="removeApplication(item)">删除</el-button>
|
||||
<el-button
|
||||
text
|
||||
type="danger"
|
||||
size="small"
|
||||
:loading="deletingApplicationId === item.id"
|
||||
:disabled="deletingApplicationId !== null"
|
||||
@click="removeApplication(item)"
|
||||
>删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -420,7 +473,7 @@ async function previewMaterial() {
|
||||
</el-dialog>
|
||||
|
||||
<div class="action-row">
|
||||
<el-button type="success" size="large" @click="submitTask">{{ buttonName }}</el-button>
|
||||
<el-button type="success" size="large" :loading="submitting" @click="submitTask">{{ buttonName }}</el-button>
|
||||
<el-button size="large" @click="cancelTask">取消</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
|
||||
+175
-141
@@ -1,63 +1,39 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import router from "@/router";
|
||||
import { getReviewFeed, type ReviewFeedItem } from "@/api/review";
|
||||
import { getReviewFeed, getTaskReview, type ReviewFeedItem } from "@/api/review";
|
||||
|
||||
const reviewItems = ref<ReviewFeedItem[]>([]);
|
||||
const isHovering = ref(false);
|
||||
const contentRef = ref<HTMLElement | null>(null);
|
||||
const AUTO_SCROLL_DURATION = 150_000;
|
||||
let autoScroll: Animation | null = null;
|
||||
|
||||
interface SessionGroup {
|
||||
interface FragmentChip {
|
||||
id: number;
|
||||
sessionNum: string;
|
||||
taskName: string;
|
||||
taskNum: string;
|
||||
content: string;
|
||||
hasReport: boolean;
|
||||
navigateType: string;
|
||||
navigateId: number;
|
||||
}
|
||||
|
||||
// 按 sessionNum 分组,一个会话展示为一个 chip
|
||||
const sessionGroups = computed<SessionGroup[]>(() => {
|
||||
const map = new Map<string, ReviewFeedItem[]>();
|
||||
for (const item of reviewItems.value) {
|
||||
const list = map.get(item.sessionNum) || [];
|
||||
list.push(item);
|
||||
map.set(item.sessionNum, list);
|
||||
}
|
||||
const truncateContent = (content: string, maxLength = 120) =>
|
||||
content.length > maxLength ? content.substring(0, maxLength) + "..." : content;
|
||||
|
||||
const groups: SessionGroup[] = [];
|
||||
for (const [sessionNum, items] of map) {
|
||||
const first = items[0];
|
||||
const report = items.find(i => i.sourceType === "REPORT");
|
||||
const fragments = items.filter(i => i.sourceType === "FRAGMENT");
|
||||
|
||||
const rawContent = report?.content || fragments.map(f => f.content).join(";");
|
||||
const content = rawContent.length > 120
|
||||
? rawContent.substring(0, 120) + "..."
|
||||
: rawContent;
|
||||
|
||||
groups.push({
|
||||
sessionNum,
|
||||
taskName: first.taskName,
|
||||
taskNum: first.taskNum,
|
||||
content,
|
||||
hasReport: !!report,
|
||||
navigateType: report ? "report" : "fragment",
|
||||
navigateId: report ? report.id : (fragments[0]?.id ?? 0),
|
||||
});
|
||||
}
|
||||
|
||||
groups.sort((a, b) => {
|
||||
const aItem = reviewItems.value.find(i => i.sessionNum === a.sessionNum);
|
||||
const bItem = reviewItems.value.find(i => i.sessionNum === b.sessionNum);
|
||||
return (bItem?.createdTime || "").localeCompare(aItem?.createdTime || "");
|
||||
});
|
||||
|
||||
return groups;
|
||||
});
|
||||
// 滚动条只展示学习残片,每条残片单独作为 chip
|
||||
const fragmentChips = computed<FragmentChip[]>(() =>
|
||||
reviewItems.value
|
||||
.filter(item => item.sourceType === "FRAGMENT")
|
||||
.map(item => ({
|
||||
id: item.id,
|
||||
sessionNum: item.sessionNum,
|
||||
taskName: item.taskName,
|
||||
taskNum: item.taskNum,
|
||||
content: truncateContent(item.content),
|
||||
})),
|
||||
);
|
||||
|
||||
// 复制一份实现无缝循环
|
||||
const duplicatedGroups = computed(() => [...sessionGroups.value, ...sessionGroups.value]);
|
||||
const duplicatedChips = computed(() => [...fragmentChips.value, ...fragmentChips.value]);
|
||||
|
||||
const loadReviewFeed = async () => {
|
||||
try {
|
||||
@@ -68,52 +44,72 @@ const loadReviewFeed = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 回忆卡片:点击滚动内容先尝试回忆,再看原文
|
||||
const recallCard = ref<{ visible: boolean; group: SessionGroup | null; revealed: boolean }>({
|
||||
// 回忆卡片:点击残片先尝试回忆,再展开该会话的报告和其他残片进行对照
|
||||
const recallCard = ref<{
|
||||
visible: boolean;
|
||||
fragment: FragmentChip | null;
|
||||
report: ReviewFeedItem | null;
|
||||
fragments: ReviewFeedItem[];
|
||||
revealed: boolean;
|
||||
loadingSession: boolean;
|
||||
loadError: string;
|
||||
}>({
|
||||
visible: false,
|
||||
group: null,
|
||||
fragment: null,
|
||||
report: null,
|
||||
fragments: [],
|
||||
revealed: false,
|
||||
loadingSession: false,
|
||||
loadError: "",
|
||||
});
|
||||
|
||||
// 当前回忆卡片对应会话的全部记录
|
||||
const recallSessionItems = computed(() => {
|
||||
const group = recallCard.value.group;
|
||||
if (!group) return [];
|
||||
return reviewItems.value.filter((i) => i.sessionNum === group.sessionNum);
|
||||
});
|
||||
|
||||
const goToReviewDetail = (group: SessionGroup) => {
|
||||
recallCard.value = { visible: true, group, revealed: false };
|
||||
const openRecallCard = (fragment: FragmentChip) => {
|
||||
recallCard.value = {
|
||||
visible: true,
|
||||
fragment,
|
||||
report: null,
|
||||
fragments: [],
|
||||
revealed: false,
|
||||
loadingSession: false,
|
||||
loadError: "",
|
||||
};
|
||||
};
|
||||
|
||||
const revealRecallContent = () => {
|
||||
recallCard.value.revealed = true;
|
||||
const revealRecallContent = async () => {
|
||||
const fragment = recallCard.value.fragment;
|
||||
if (!fragment || recallCard.value.loadingSession || recallCard.value.revealed) return;
|
||||
if (recallCard.value.report || recallCard.value.fragments.length > 0) {
|
||||
recallCard.value.revealed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
recallCard.value.loadingSession = true;
|
||||
recallCard.value.loadError = "";
|
||||
try {
|
||||
const res = await getTaskReview(fragment.taskNum);
|
||||
const items: ReviewFeedItem[] = (res?.data || []).filter(
|
||||
(item: ReviewFeedItem) => item.sessionNum === fragment.sessionNum,
|
||||
);
|
||||
recallCard.value.report = items.find((item: ReviewFeedItem) => item.sourceType === "REPORT") || null;
|
||||
recallCard.value.fragments = items.filter((item: ReviewFeedItem) => item.sourceType === "FRAGMENT");
|
||||
recallCard.value.revealed = true;
|
||||
} catch {
|
||||
recallCard.value.loadError = "展开对照内容加载失败,请稍后重试";
|
||||
} finally {
|
||||
recallCard.value.loadingSession = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openRecallDetail = () => {
|
||||
const group = recallCard.value.group;
|
||||
if (!group) return;
|
||||
/** 从回忆卡片跳转到回忆复习页,节点匹配交给目标页加载后处理 */
|
||||
const goToRecallFromCard = () => {
|
||||
const fragment = recallCard.value.fragment;
|
||||
if (!fragment) return;
|
||||
recallCard.value.visible = false;
|
||||
router.push(`/review/detail/${group.navigateType}/${group.navigateId}`);
|
||||
};
|
||||
|
||||
/** 从回忆卡片跳转到回忆复习页(先匹配标准导图节点) */
|
||||
const goToRecallFromCard = async () => {
|
||||
const group = recallCard.value.group;
|
||||
if (!group) return;
|
||||
recallCard.value.visible = false;
|
||||
const tn = group.taskNum;
|
||||
const content = group.content || "";
|
||||
const tn = fragment.taskNum;
|
||||
const content = fragment.content || "";
|
||||
if (tn && content) {
|
||||
try {
|
||||
const { findNode } = await import("@/api/standardMindMap");
|
||||
const res = await findNode(tn, content.substring(0, 500));
|
||||
const data = res?.data;
|
||||
if (data?.path) {
|
||||
router.push(`/review/recall/${tn}?focusPath=${encodeURIComponent(data.path)}`);
|
||||
return;
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
router.push(`/review/recall/${tn}?focusContent=${encodeURIComponent(content)}`);
|
||||
} else if (tn) {
|
||||
router.push(`/review/recall/${tn}`);
|
||||
} else {
|
||||
router.push("/review");
|
||||
@@ -128,8 +124,50 @@ const startReview = () => {
|
||||
router.push("/review");
|
||||
};
|
||||
|
||||
const handleTrackWheel = (event: WheelEvent) => {
|
||||
const anim = autoScroll;
|
||||
const content = contentRef.value;
|
||||
if (!anim || !content) return;
|
||||
|
||||
anim.pause();
|
||||
|
||||
const rawDelta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
|
||||
const delta = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? rawDelta * 16 : rawDelta;
|
||||
if (!delta) return;
|
||||
|
||||
// 一屏内容的宽度对应一轮自动滚动
|
||||
const loopWidth = content.scrollWidth / 2;
|
||||
if (!loopWidth) return;
|
||||
|
||||
const current = anim.currentTime;
|
||||
if (typeof current !== "number") return;
|
||||
anim.currentTime = Math.min(
|
||||
Math.max(current + (delta / loopWidth) * AUTO_SCROLL_DURATION, 0),
|
||||
AUTO_SCROLL_DURATION,
|
||||
);
|
||||
};
|
||||
|
||||
const pauseAutoScroll = () => {
|
||||
autoScroll?.pause();
|
||||
};
|
||||
|
||||
const resumeAutoScroll = () => {
|
||||
autoScroll?.play();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadReviewFeed();
|
||||
autoScroll = contentRef.value?.animate(
|
||||
[
|
||||
{ transform: "translateX(0)" },
|
||||
{ transform: "translateX(-50%)" },
|
||||
],
|
||||
{ duration: AUTO_SCROLL_DURATION, iterations: Infinity, easing: "linear" },
|
||||
) || null;
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
autoScroll?.cancel();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -139,26 +177,27 @@ onMounted(() => {
|
||||
<div class="review-scroll-section surface-card">
|
||||
<div class="review-scroll-header">
|
||||
<span class="color-legend">
|
||||
<span class="dot dot-report"></span> 学习报告
|
||||
<span class="dot dot-fragment"></span> 学习残片
|
||||
</span>
|
||||
</div>
|
||||
<div class="review-scroll-track">
|
||||
<div
|
||||
class="review-scroll-track"
|
||||
@mouseenter="pauseAutoScroll"
|
||||
@mouseleave="resumeAutoScroll"
|
||||
@wheel.prevent="handleTrackWheel"
|
||||
>
|
||||
<div
|
||||
ref="contentRef"
|
||||
class="review-scroll-content"
|
||||
:class="{ paused: isHovering }"
|
||||
@mouseenter="isHovering = true"
|
||||
@mouseleave="isHovering = false"
|
||||
>
|
||||
<span
|
||||
v-for="(group, index) in duplicatedGroups"
|
||||
v-for="(chip, index) in duplicatedChips"
|
||||
:key="index"
|
||||
class="review-chip"
|
||||
:class="group.hasReport ? 'has-report' : 'fragments-only'"
|
||||
@click="goToReviewDetail(group)"
|
||||
class="review-chip fragment-chip"
|
||||
@click="openRecallCard(chip)"
|
||||
>
|
||||
<strong class="chip-task">{{ group.taskName }}</strong>
|
||||
<span class="chip-content">{{ group.content }}</span>
|
||||
<strong class="chip-task">{{ chip.taskName }}</strong>
|
||||
<span class="chip-content">{{ chip.content }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -191,36 +230,53 @@ onMounted(() => {
|
||||
<!-- 回忆卡片:先回忆,再对照 -->
|
||||
<el-dialog
|
||||
v-model="recallCard.visible"
|
||||
:title="recallCard.group?.taskName || '回忆一下'"
|
||||
:title="recallCard.fragment?.taskName || '回忆一下'"
|
||||
width="560px"
|
||||
class="recall-card-dialog"
|
||||
>
|
||||
<template v-if="recallCard.group">
|
||||
<template v-if="recallCard.fragment">
|
||||
<p class="recall-question">
|
||||
这次学习共有 {{ recallSessionItems.length }} 条记录。看着下面这个片段,先试着回忆:当时还学了什么?
|
||||
看着下面这个残片,先试着回忆:当时还学了什么?
|
||||
</p>
|
||||
<blockquote class="recall-snippet">{{ recallCard.group.content }}</blockquote>
|
||||
<blockquote class="recall-snippet">{{ recallCard.fragment.content }}</blockquote>
|
||||
<p v-if="recallCard.loadError" class="recall-error">{{ recallCard.loadError }}</p>
|
||||
|
||||
<div v-if="recallCard.revealed" class="recall-full-list">
|
||||
<div v-if="recallCard.report" class="recall-full-item">
|
||||
<span class="recall-item-tag tag-report">报告</span>
|
||||
<span class="recall-item-content">{{ recallCard.report.content }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-for="item in recallSessionItems"
|
||||
:key="`${item.sourceType}-${item.id}`"
|
||||
v-for="item in recallCard.fragments"
|
||||
:key="item.id"
|
||||
class="recall-full-item"
|
||||
:class="{ 'is-clicked': item.id === recallCard.fragment?.id }"
|
||||
>
|
||||
<span class="recall-item-tag" :class="item.sourceType === 'REPORT' ? 'tag-report' : 'tag-fragment'">
|
||||
{{ item.sourceType === "REPORT" ? "报告" : "残片" }}
|
||||
</span>
|
||||
<span class="recall-item-tag tag-fragment">残片</span>
|
||||
<span class="recall-item-content">{{ item.content }}</span>
|
||||
</div>
|
||||
<el-empty
|
||||
v-if="!recallCard.report && recallCard.fragments.length === 0"
|
||||
description="暂未找到该会话的对照内容"
|
||||
:image-size="48"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<el-button v-if="!recallCard.revealed" type="success" plain @click="revealRecallContent">
|
||||
回忆好了,展开对照
|
||||
<el-button
|
||||
v-if="!recallCard.revealed"
|
||||
type="success"
|
||||
plain
|
||||
:loading="recallCard.loadingSession"
|
||||
@click="revealRecallContent"
|
||||
>
|
||||
展开对照
|
||||
</el-button>
|
||||
<el-button v-else type="success" plain @click="openRecallDetail">进入详情页</el-button>
|
||||
<el-button type="success" @click="goToRecallFromCard">前往回忆复习</el-button>
|
||||
<el-button @click="recallCard.visible = false">关闭</el-button>
|
||||
<el-button v-if="!recallCard.revealed" @click="recallCard.visible = false">关闭</el-button>
|
||||
<template v-else>
|
||||
<el-button type="success" @click="goToRecallFromCard">前往回忆复习</el-button>
|
||||
<el-button @click="recallCard.visible = false">关闭</el-button>
|
||||
</template>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
@@ -297,10 +353,6 @@ onMounted(() => {
|
||||
margin-right: 3px;
|
||||
}
|
||||
|
||||
.dot-report {
|
||||
background: var(--green-600);
|
||||
}
|
||||
|
||||
.dot-fragment {
|
||||
background: #e6a23c;
|
||||
}
|
||||
@@ -315,20 +367,6 @@ onMounted(() => {
|
||||
display: inline-flex;
|
||||
gap: 14px;
|
||||
white-space: nowrap;
|
||||
animation: review-ticker 150s linear infinite;
|
||||
}
|
||||
|
||||
.review-scroll-content.paused {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
@keyframes review-ticker {
|
||||
0% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.review-chip {
|
||||
@@ -338,7 +376,7 @@ onMounted(() => {
|
||||
padding: 8px 16px;
|
||||
background: var(--surface-strong);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-left: 3px solid transparent;
|
||||
border-left: 3px solid #e6a23c;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, box-shadow 0.2s;
|
||||
@@ -346,23 +384,8 @@ onMounted(() => {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.review-chip.has-report {
|
||||
border-left-color: var(--green-600);
|
||||
}
|
||||
|
||||
.review-chip.fragments-only {
|
||||
border-left-color: #e6a23c;
|
||||
}
|
||||
|
||||
.review-chip:hover {
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.review-chip.has-report:hover {
|
||||
background: #e8f5e9;
|
||||
}
|
||||
|
||||
.review-chip.fragments-only:hover {
|
||||
background: #fff8e1;
|
||||
}
|
||||
|
||||
@@ -401,6 +424,12 @@ onMounted(() => {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.recall-error {
|
||||
margin: 0 0 10px;
|
||||
color: var(--el-color-danger, #f56c6c);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.recall-full-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -419,6 +448,11 @@ onMounted(() => {
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.recall-full-item.is-clicked {
|
||||
background: #fff8e1;
|
||||
border-color: #e6a23c;
|
||||
}
|
||||
|
||||
.recall-item-tag {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
|
||||
@@ -5,6 +5,7 @@ import {createFragments} from '@/api/reportFragments';
|
||||
export const useStudyFragment = () => {
|
||||
const fragmentsDialogVisible = ref(false);
|
||||
const fragmentContent = ref('');
|
||||
const creatingFragment = ref(false);
|
||||
|
||||
const openFragmentDialog = () => {
|
||||
fragmentContent.value = '';
|
||||
@@ -26,23 +27,24 @@ export const useStudyFragment = () => {
|
||||
};
|
||||
|
||||
const confirmGenerateFragment = async (sessionNum: string): Promise<boolean> => {
|
||||
if (creatingFragment.value) return false;
|
||||
if (!fragmentContent.value.trim()) {
|
||||
ElMessage.warning('请输入学习内容!');
|
||||
return false;
|
||||
}
|
||||
|
||||
creatingFragment.value = true;
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
});
|
||||
} catch {
|
||||
ElMessage.info('已取消生成');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
});
|
||||
} catch {
|
||||
ElMessage.info('已取消生成');
|
||||
return false;
|
||||
}
|
||||
const res = await createFragments(sessionNum, fragmentContent.value);
|
||||
if (res.code === 200) {
|
||||
ElMessage.success('学习残片生成成功!');
|
||||
@@ -55,12 +57,15 @@ export const useStudyFragment = () => {
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '请求失败');
|
||||
return false;
|
||||
} finally {
|
||||
creatingFragment.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
fragmentsDialogVisible,
|
||||
fragmentContent,
|
||||
creatingFragment,
|
||||
openFragmentDialog,
|
||||
closeFragmentDialog,
|
||||
confirmGenerateFragment,
|
||||
|
||||
@@ -27,6 +27,11 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import("@/components/Review.vue"),
|
||||
meta: { requiresAuth: true, title: "复习总览" },
|
||||
},
|
||||
{
|
||||
path: "/review/detail/task/:taskNum",
|
||||
component: () => import("@/components/ReviewDetail.vue"),
|
||||
meta: { requiresAuth: true, title: "复习详情" },
|
||||
},
|
||||
{
|
||||
path: "/review/detail/:type/:id",
|
||||
component: () => import("@/components/ReviewDetail.vue"),
|
||||
|
||||
@@ -32,14 +32,14 @@ const handleError = (error: any) => {
|
||||
}
|
||||
|
||||
if (error.response) {
|
||||
const backendMessage = error.response?.data?.message || JSON.stringify(error.response?.data);
|
||||
ElMessage.error(`请求失败,服务器返回: ${backendMessage}`);
|
||||
const backendMessage = error.response?.data?.message;
|
||||
ElMessage.error(backendMessage || "请求失败了,请稍后再试");
|
||||
} else if (error.request) {
|
||||
ElMessage.error("请求未收到响应,请检查接口运行状态");
|
||||
ElMessage.error("请求失败了,请检查网络后重试");
|
||||
} else {
|
||||
ElMessage.error(error.message || "请求失败");
|
||||
ElMessage.error("请求失败了,请稍后再试");
|
||||
}
|
||||
throw new Error("网络不通畅,请检查您的网络连接或服务器状态");
|
||||
throw new Error("请求失败了,请稍后再试");
|
||||
};
|
||||
|
||||
const validateResponse = (res: any) => {
|
||||
@@ -88,8 +88,8 @@ const del = (url: string, params: Record<string, any> = {}, config: any = {}) =>
|
||||
};
|
||||
|
||||
const requestNotImplemented = (method: string) => {
|
||||
ElMessage.error(`请求方法 ${method} 未实现`);
|
||||
throw new Error(`请求方法 ${method} 未实现`);
|
||||
ElMessage.error("该功能暂不可用,请刷新后重试");
|
||||
throw new Error("该功能暂不可用,请刷新后重试");
|
||||
};
|
||||
|
||||
const request = (method: string, url: string, paramsOrData: any) => {
|
||||
|
||||
Reference in New Issue
Block a user