Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99a1b16196 | ||
|
|
132cb706d7 | ||
|
|
66c3c68394 | ||
|
|
c638f7d9c1 | ||
|
|
5a32ad00ed | ||
|
|
939a135519 | ||
|
|
854a94d7a3 | ||
|
|
d9a0b55da0 | ||
|
|
5a382d95e4 | ||
|
|
38243eac82 | ||
|
|
fae27e7c20 | ||
|
|
cc4c20e77b | ||
|
|
1254e3d5d0 | ||
|
|
5569921df6 | ||
|
|
8c8924d652 | ||
|
|
b96cad9683 | ||
|
|
c898c0a8c7 | ||
|
|
45e6663568 | ||
|
|
d33bc11014 | ||
|
|
f1fcae0dac | ||
|
|
468bba8670 | ||
|
|
96cc57ae06 | ||
|
|
f37a92c240 | ||
|
|
fe45ec0f76 | ||
|
|
d01b6dcaa3 | ||
|
|
4e8aa15b71 | ||
|
|
370d8e7769 | ||
|
|
be4db68550 | ||
|
|
c95e593cf1 | ||
|
|
9ed53aa4bc | ||
|
|
4d9b3c0b02 | ||
|
|
605495fd53 | ||
|
|
eb992a47b7 | ||
|
|
2a36e28f74 | ||
|
|
e82a87d104 | ||
|
|
f408076187 | ||
|
|
7610b34621 | ||
|
|
6595ed0dfc | ||
|
|
f71abdd000 | ||
|
|
9bba684fb2 | ||
|
|
8d5c9db47f | ||
|
|
b8b0b73cd8 | ||
|
|
81f91b320a | ||
|
|
de45c8039c | ||
|
|
c2493e4c71 | ||
|
|
0059e0ec71 | ||
|
|
96d574b99f | ||
|
|
69861d54bb | ||
|
|
769d26fa97 | ||
|
|
04df078fcf | ||
|
|
bcec8512f4 | ||
|
|
297320446c |
@@ -0,0 +1,4 @@
|
||||
# 行尾规范:文本文件统一 LF,Windows 批处理保留 CRLF
|
||||
* text=auto eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
@@ -74,6 +74,104 @@ lpt-fe/src/
|
||||
- `MindMapViewer.vue` 支持只读、编辑、selectable、colorByCompare 模式;selectable 模式下点击节点 emit `node-select`。
|
||||
- ReviewRecall 中 `standardExpanded` 展开后节点可点击,用于选择复习起点。
|
||||
|
||||
## 前端代码标准
|
||||
|
||||
### 交互防抖与加载原则
|
||||
|
||||
- 点击后需要跳转到其他页面时,应立刻执行跳转,不要在跳转前等待接口返回;目标页面在数据未加载完成时必须展示页面级 loading。
|
||||
- 点击后不跳转页面时,触发接口的按钮必须自身展示 loading 或在请求期间禁用,防止网络慢时被多次触发。
|
||||
- 登录、创建/更新、结束会话等必须确认后端成功的操作属于例外:按钮先进入 loading,成功后再跳转。
|
||||
- 同一异步动作执行期间必须通过 loading 或 disabled 阻止重复触发,不能只依赖路由跳转后的页面卸载。
|
||||
|
||||
### 按钮规范
|
||||
|
||||
- 主操作 / 卡片 CTA:`size="large"`(实测 40px 高、15px 字),如 Study 开始任务、Welcome 快速入口。
|
||||
- 区块工具栏 / 页内操作:默认尺寸(32px 高、14px 字),如 Review 刷新、ReviewRecall 面板操作。
|
||||
- 表格/列表行内操作:`size="small"`(28px 高、13px 字;不得再调小)。
|
||||
- 弹窗 footer:默认尺寸;确认按钮 `type="success"`,取消按钮默认;危险操作统一 `type="danger"`。
|
||||
- 正向/保存语义统一 `success`,次级编辑语义可用 `primary`,不要在同一功能上混用。
|
||||
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css` 的 `.action-row / .edit-actions / .fragment-edit-actions / .task-actions`。
|
||||
|
||||
### 颜色与主题
|
||||
|
||||
- 禁止在组件内写颜色字面量:新增颜色先加到 `src/assets/base.css` 的 `:root`,组件只用 `var(--x)`。语义色已提供 `--accent-warning / --accent-warning-soft / --accent-warning-strong / --accent-success-soft / --accent-success-softer / --accent-success-strong / --accent-success-text`。
|
||||
- Element Plus 主题色在 `src/assets/main.css` 的 `:root` 覆盖(`--el-color-success` / `--el-color-primary` 指向 `--green-700`),全站按钮/标签/开关自动生效,不要在组件里逐个覆盖 EP 组件色。
|
||||
- `src/main.ts` 中自定义样式必须写在 `import 'element-plus/dist/index.css'` **之后**,否则主题覆盖会被 EP 覆盖。
|
||||
- 实底主色统一用满足 WCAG AA(白字对比度 ≥4.5:1)的 `--green-700`;`--green-600` 仅用于文字/链接。
|
||||
- 颜色字面量不得出现在 JS/模板表达式里(如 `:color="'#xxx'"` 引 CSS 变量会失效),需要动态色时保留字面量或改用 CSS 类。
|
||||
|
||||
### 卡片列表交互
|
||||
|
||||
- 卡片列表的卡片整体可点击进入详情:外层加 `role="link" tabindex="0"` 与 `aria-label`,并绑定 `@click` 及 `@keydown.enter/@keydown.space.prevent`。
|
||||
- 卡片内的附加按钮必须 `@click.stop`,避免被卡片点击吞掉(如 Review 的「回忆复习」)。
|
||||
- 卡片操作使用右对齐操作簇(`justify-content: flex-end`),**禁止用 `space-between` 把两个按钮拉到卡片两端**。
|
||||
- 加载失败必须区分于空数据:保留一个 `loadFailed` 状态,失败时给出可读提示 + 重试按钮,重试前先重置该状态;不要只靠 `finally` 关 loading 导致空白页。
|
||||
|
||||
### 移动端适配
|
||||
|
||||
- 断点约定:按钮/弹窗使用 768px,卡片与汇总布局使用 900px。
|
||||
- 弹窗:窄屏宽度 `calc(100% - 24px)`,body 允许纵向滚动,footer 按钮等宽;全局规则位于 `main.css` 的 `@media (max-width: 768px)`,新增弹窗不需要再逐页适配。
|
||||
- 多按钮弹窗(如 Welcome 回忆卡片)在窄屏纵向堆叠。
|
||||
- 列表页优先使用卡片列表而非 `el-table`,桌面与移动端视觉统一,参考 `Review.vue` 的 `.task-list`。
|
||||
- 文案不缩写:使用完整字段名,如 `学习报告数量`、`学习残片数量`,不使用 `报告数`、`残片数`。
|
||||
|
||||
### 代码整洁
|
||||
|
||||
- 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)不进入业务代码。
|
||||
|
||||
### 请求层与类型规范
|
||||
|
||||
- 所有接口封装必须放在 `src/api/`,组件内禁止直接拼 URL 调用 `request`(历史遗留的裸调用在改动到时迁移)。
|
||||
- request 层统一返回 `Promise<ApiResponse<T>>`:新增接口必须显式标注泛型 `T`,组件消费 `res.data` 时应有明确类型,禁止把后端字段拼错暴露到运行期。
|
||||
- 默认超时 30 秒;AI 聚合类接口(残片生成、思维导图生成/对比、报告草稿、结束会话)在 api 层显式覆写 `{ timeout: 300_000 }`,不要调大全局默认值。
|
||||
- 组件解构响应时使用 `res?.data` 判空兜底;`ApiResponse` 从 `@/utils/request` 导入复用。
|
||||
|
||||
### 组合式函数复用
|
||||
|
||||
- “已等待 N 秒”类秒表计时统一使用 `useElapsedSeconds`,禁止组件内手写 `setInterval` 秒数递增。
|
||||
- 页面新增功能域时先抽 composable(参考 `useSessionHistory` / `useSummaryReport` / `useSessionExpectation`),不要继续膨胀 StartTask 等大页面组件。
|
||||
- 通用解析器、格式化工具放 `src/utils/`,不埋在组件内(如大纲文本转树应放 utils)。
|
||||
|
||||
### 测试规范(分层策略)
|
||||
|
||||
测试按「金字塔」分层组织,新增功能优先补中间层:
|
||||
|
||||
| 层 | 位置 | 职责 | 风格 |
|
||||
|----|------|------|------|
|
||||
| 逻辑单测 | `src/__tests__/{api,composables,utils,router}/` | 纯函数、composable、request 封装 | 直接调用,快、准 |
|
||||
| **交互式集成测试** | `src/__tests__/integration/` | 页面关键用户路径 | 真实挂载 + 模拟点击 + DOM 断言 |
|
||||
| E2E | `e2e/` | 真实浏览器回归 | Playwright + `page.route` 拦后端 |
|
||||
|
||||
### 交互式集成测试要求
|
||||
|
||||
- 必须真实挂载组件(不 `shallow`),通过 `trigger('click')`、`setValue()`、`find('…')` 模拟并断言用户可见行为;禁止 `wrapper.vm.xxx()` 直调内部方法作为主要测试手段(历史遗留的 vm 直调在改动到时迁移)。
|
||||
- 页面关键路径必须有集成测试:登录、学习会话暂停/继续、任务创建/更新、回忆对比等新增关键流程同步补 `integration/*.spec.ts`。
|
||||
- 只断言应用自身行为(API 调用参数、提示、路由、状态文案),不要重复验证 Element Plus 内部行为;jsdom 下 EP 的 callback 式表单校验不可靠(空表单也可能判有效),「校验拦截」类断言由 e2e 在真实浏览器覆盖。
|
||||
- 已知兼容问题:`el-tag` 在 jsdom + VTU 全量挂载时 vnode mounted 钩子崩溃(EP 2.8),集成测试统一 `stubs: { ElTag: true }`;依赖 mind-elixir 的 `MindMapViewer` 用可编程 stub(提供 `toOutline`)。
|
||||
- E2E 定位优先使用角色与可访问名称(`getByRole('button', { name })`、`getByPlaceholder`),仅断言 EP 内部 UI(校验错误、消息弹层)时才用类选择器;改文案不应导致大面积碎测。
|
||||
|
||||
### 逻辑单测要求
|
||||
|
||||
- 单元测试必须直接测试真实代码:直接调用 composable、挂载真实组件、使用真实路由;禁止把组件或 composable 的逻辑复制到测试里再自测。
|
||||
- 测试中可以 mock 外部依赖(API、Element Plus 服务、Audio 等),但被测逻辑本身必须来自生产模块。
|
||||
- `script setup` 内部状态需要测试访问时,通过 `defineExpose` 暴露,而不是在测试里重写一份相同逻辑。
|
||||
|
||||
### 覆盖率
|
||||
|
||||
- `npm run test:coverage` 输出 v8 覆盖率报告(`coverage/`),阈值配置在 `vite.config.ts`,作为棘轮只升不降:任何低于阈值的改动不允许提交。
|
||||
- 提升覆盖率优先补集成测试与零覆盖模块(当前缺口:Review、ReviewDetail、fetchTitle、markdown 渲染分支),不为凑数写快照式断言。
|
||||
|
||||
### 提交前检查
|
||||
|
||||
- 运行 `npm run type-check`、`npm run lint`(0 error 才可提交;`no-explicit-any` 允许存量警告,新代码避免 any)、`npm run test`、`npm run build`。
|
||||
- **不要用 `npx vue-tsc --noEmit` 作为检查手段**:`tsconfig.json` 是 solution 风格(`files: []` + 仅 `references`),该命令会解析到根配置而检查 0 个源文件,永远假绿。Docker 构建跑的是 `npm run type-check`(`vue-tsc --build --force`,走 project references),只有它才真正校验。
|
||||
- 提交信息按 Git 提交规范使用中文短句;样式类改动用 `style:`,清理类用 `refactor:` / `chore:`。
|
||||
|
||||
## 开发配置
|
||||
|
||||
- 开发端口:5158
|
||||
@@ -88,14 +186,16 @@ npm run dev
|
||||
npm run build
|
||||
npm run test
|
||||
npm run test:e2e
|
||||
npx vue-tsc --noEmit
|
||||
npm run type-check
|
||||
npm run lint
|
||||
npm run test:coverage
|
||||
```
|
||||
|
||||
编译检查也可以使用:
|
||||
|
||||
```bash
|
||||
npx vite build
|
||||
npx vue-tsc --noEmit
|
||||
npm run type-check
|
||||
```
|
||||
|
||||
## Docker
|
||||
|
||||
@@ -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 前端不仅功能完整,而且性能优异、体验流畅、代码可维护。
|
||||
+8
-8
@@ -17,11 +17,11 @@ test.describe('Login page', () => {
|
||||
// Element Plus inputs
|
||||
const inputs = page.locator('.el-input');
|
||||
await expect(inputs).toHaveCount(2);
|
||||
await expect(page.locator('.submit-btn')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '进入系统' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows validation errors when fields are empty', async ({ page }) => {
|
||||
await page.locator('.submit-btn').click();
|
||||
await page.getByRole('button', { name: '进入系统' }).click();
|
||||
// Element Plus validation shows error messages
|
||||
await expect(page.locator('.el-form-item__error').first()).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
@@ -42,11 +42,11 @@ test.describe('Login page', () => {
|
||||
);
|
||||
|
||||
// Fill in inputs using Element Plus el-input inner input
|
||||
const usernameInput = page.locator('.el-form-item').filter({ hasText: '账号' }).locator('input');
|
||||
const passwordInput = page.locator('.el-form-item').filter({ hasText: '密码' }).locator('input');
|
||||
const usernameInput = page.getByPlaceholder('请输入账号');
|
||||
const passwordInput = page.getByPlaceholder('请输入密码');
|
||||
await usernameInput.fill('wronguser');
|
||||
await passwordInput.fill('wrongpass');
|
||||
await page.locator('.submit-btn').click();
|
||||
await page.getByRole('button', { name: '进入系统' }).click();
|
||||
|
||||
// Element Plus error message appears in a popup
|
||||
await expect(page.locator('.el-message--error')).toBeVisible({ timeout: 5000 });
|
||||
@@ -67,11 +67,11 @@ test.describe('Login page', () => {
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
const usernameInput = page.locator('.el-form-item').filter({ hasText: '账号' }).locator('input');
|
||||
const passwordInput = page.locator('.el-form-item').filter({ hasText: '密码' }).locator('input');
|
||||
const usernameInput = page.getByPlaceholder('请输入账号');
|
||||
const passwordInput = page.getByPlaceholder('请输入密码');
|
||||
await usernameInput.fill('admin');
|
||||
await passwordInput.fill('password123');
|
||||
await page.locator('.submit-btn').click();
|
||||
await page.getByRole('button', { name: '进入系统' }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/welcome/, { timeout: 10_000 });
|
||||
const isLoggedIn = await page.evaluate(() => localStorage.getItem('isLoggedIn'));
|
||||
|
||||
+37
-3
@@ -41,12 +41,14 @@ test.describe('Review page', () => {
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('displays summary metrics and task table', async ({ page }) => {
|
||||
test('displays summary metrics and task list', async ({ page }) => {
|
||||
await expect(page.locator('.metric-card')).toHaveCount(3);
|
||||
// Check metric values
|
||||
await expect(page.locator('.metric-card').first().locator('strong')).toContainText('2');
|
||||
// Check table rows
|
||||
await expect(page.locator('.el-table__row')).toHaveCount(2);
|
||||
// 任务以卡片列表展示(不再是 el-table)
|
||||
await expect(page.locator('.task-card')).toHaveCount(2);
|
||||
await expect(page.getByText('学习 Vue3')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '回忆复习' })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test('shows empty state when no tasks', async ({ page }) => {
|
||||
@@ -61,5 +63,37 @@ test.describe('Review page', () => {
|
||||
await page.goto('/review');
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.metric-card').first().locator('strong')).toContainText('0');
|
||||
await expect(page.getByText('暂无复习任务')).toBeVisible();
|
||||
});
|
||||
|
||||
test('接口失败时提示加载失败而不是显示空列表', async ({ page }) => {
|
||||
await page.route('**/api/review/tasks**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 500, message: '服务异常', data: null }),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/review');
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
|
||||
await expect(page.getByText('复习数据加载失败,请稍后重试')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '重新加载' })).toBeVisible();
|
||||
await expect(page.getByText('暂无复习任务')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('详情页返回按钮为「返回总览」并回到复习总览', async ({ page }) => {
|
||||
await page.route('**/api/review/task/**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ code: 200, data: [] }) }),
|
||||
);
|
||||
|
||||
await page.locator('.task-card').first().click();
|
||||
await expect(page).toHaveURL(/\/review\/detail\/task\/T001/, { timeout: 5000 });
|
||||
|
||||
const backBtn = page.locator('.head .back-btn');
|
||||
await expect(backBtn).toHaveText('← 返回总览');
|
||||
await backBtn.click();
|
||||
await expect(page).toHaveURL(/\/review$/, { timeout: 5000 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,7 +115,7 @@ test.describe('StartTask - 暂停后继续', () => {
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
|
||||
// 点击暂停按钮
|
||||
await page.locator('button', { hasText: '暂停' }).click();
|
||||
await page.getByRole('button', { name: '暂停' }).click();
|
||||
|
||||
// 验证暂停 API 被调用
|
||||
expect(apiCalls).toContain('pause');
|
||||
@@ -124,7 +124,7 @@ test.describe('StartTask - 暂停后继续', () => {
|
||||
await expect(page.locator('.status-text')).toContainText('已暂停');
|
||||
|
||||
// 点击开始按钮
|
||||
await page.locator('button', { hasText: '开始' }).click();
|
||||
await page.getByRole('button', { name: '开始' }).click();
|
||||
|
||||
// 验证 continue API 被调用
|
||||
expect(apiCalls).toContain('continue');
|
||||
@@ -159,7 +159,7 @@ test.describe('StartTask - 暂停后继续', () => {
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
|
||||
// ONGOING 状态下,开始按钮是 disabled 的,不应触发 continue
|
||||
const startBtn = page.locator('button', { hasText: '开始' });
|
||||
const startBtn = page.getByRole('button', { name: '开始' });
|
||||
await expect(startBtn).toBeDisabled();
|
||||
|
||||
// continue API 不应被调用
|
||||
@@ -187,18 +187,18 @@ test.describe('StartTask - 暂停后继续', () => {
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
|
||||
// 暂停
|
||||
await page.locator('button', { hasText: '暂停' }).click();
|
||||
await page.getByRole('button', { name: '暂停' }).click();
|
||||
await expect(page.locator('.status-text')).toContainText('已暂停');
|
||||
|
||||
// 结束会话
|
||||
await page.locator('button', { hasText: '结束会话' }).click();
|
||||
await page.getByRole('button', { name: '结束会话' }).click();
|
||||
|
||||
// 在弹窗中输入总结内容
|
||||
await page.locator('.el-dialog textarea').fill('测试总结');
|
||||
await page.locator('.el-dialog button', { hasText: '确认结束' }).click();
|
||||
await page.getByRole('dialog').getByRole('button', { name: '确认结束' }).click();
|
||||
|
||||
// 确认第二个弹窗("确定要结束本次学习会话吗?")
|
||||
const confirmBtn = page.locator('.el-message-box__btns button', { hasText: '确定' });
|
||||
const confirmBtn = page.getByRole('dialog').getByRole('button', { name: '确定' });
|
||||
await confirmBtn.waitFor({ timeout: 5000 });
|
||||
await confirmBtn.click();
|
||||
|
||||
|
||||
+4
-4
@@ -76,12 +76,12 @@ test.describe('Study page', () => {
|
||||
});
|
||||
|
||||
test('clicking add navigates to add-task form', async ({ page }) => {
|
||||
await page.locator('.action-card').locator('button', { hasText: '添加任务' }).click();
|
||||
await page.getByRole('button', { name: '添加任务' }).click();
|
||||
await expect(page).toHaveURL(/\/add-task/);
|
||||
});
|
||||
|
||||
test('clicking update navigates to update-task form', async ({ page }) => {
|
||||
await page.locator('.action-card').locator('button', { hasText: '更新任务' }).click();
|
||||
await page.getByRole('button', { name: '更新任务' }).click();
|
||||
await expect(page).toHaveURL(/\/update-task/);
|
||||
});
|
||||
|
||||
@@ -97,9 +97,9 @@ test.describe('Study page', () => {
|
||||
});
|
||||
});
|
||||
|
||||
await page.locator('.action-card').locator('button', { hasText: '删除任务' }).click();
|
||||
await page.getByRole('button', { name: '删除任务' }).click();
|
||||
// 处理确认弹窗
|
||||
const confirmBtn = page.locator('.el-message-box__btns button:has-text("确定删除")');
|
||||
const confirmBtn = page.getByRole('dialog').getByRole('button', { name: '确定删除' });
|
||||
await confirmBtn.waitFor({ timeout: 3000 });
|
||||
await confirmBtn.click();
|
||||
await expect(page.locator('.task-list-item')).toHaveCount(1, { timeout: 5000 });
|
||||
|
||||
@@ -20,7 +20,7 @@ test.describe('Task form', () => {
|
||||
await loginAndGo(page, '/add-task');
|
||||
await expect(page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input')).toHaveValue('');
|
||||
await expect(page.locator('.el-form-item').filter({ hasText: '任务描述' }).locator('textarea')).toHaveValue('');
|
||||
await expect(page.locator('.action-row button').first()).toContainText('添加');
|
||||
await expect(page.getByRole('button', { name: '添加', exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('submitting add-task sends POST and navigates to /study', async ({ page }) => {
|
||||
@@ -36,9 +36,9 @@ test.describe('Task form', () => {
|
||||
});
|
||||
await loginAndGo(page, '/add-task');
|
||||
|
||||
await page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input').fill('新学习任务');
|
||||
await page.locator('.el-form-item').filter({ hasText: '任务描述' }).locator('textarea').fill('这是一个测试任务');
|
||||
await page.locator('.action-row button').first().click();
|
||||
await page.getByPlaceholder('例如:Vue3 组件通信实践').fill('新学习任务');
|
||||
await page.getByPlaceholder('请输入任务描述').fill('这是一个测试任务');
|
||||
await page.getByRole('button', { name: '添加', exact: true }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/study/, { timeout: 10_000 });
|
||||
});
|
||||
@@ -75,18 +75,18 @@ test.describe('Task form', () => {
|
||||
});
|
||||
|
||||
await loginAndGo(page, '/update-task/1');
|
||||
await expect(page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input')).toHaveValue('已有任务');
|
||||
await expect(page.locator('.action-row button').first()).toContainText('更新');
|
||||
await expect(page.getByPlaceholder('例如:Vue3 组件通信实践')).toHaveValue('已有任务');
|
||||
await expect(page.getByRole('button', { name: '更新', exact: true })).toBeVisible();
|
||||
|
||||
await page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input').fill('更新后的任务');
|
||||
await page.locator('.action-row button').first().click();
|
||||
await page.getByPlaceholder('例如:Vue3 组件通信实践').fill('更新后的任务');
|
||||
await page.getByRole('button', { name: '添加', exact: true }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/study/, { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('cancel navigates back to /study', async ({ page }) => {
|
||||
await loginAndGo(page, '/add-task');
|
||||
await page.locator('.action-row button').nth(1).click();
|
||||
await page.getByRole('button', { name: '取消' }).click();
|
||||
await expect(page).toHaveURL(/\/study/);
|
||||
});
|
||||
});
|
||||
|
||||
+42
-2
@@ -23,12 +23,52 @@ test.describe('Welcome page', () => {
|
||||
});
|
||||
|
||||
test('clicking start study navigates to /study', async ({ page }) => {
|
||||
await page.locator('.quick-card').first().locator('button').click();
|
||||
await page.getByRole('button', { name: '开始学习' }).click();
|
||||
await expect(page).toHaveURL(/\/study/);
|
||||
});
|
||||
|
||||
test('clicking start review navigates to /review', async ({ page }) => {
|
||||
await page.locator('.quick-card').nth(1).locator('button').click();
|
||||
await page.getByRole('button', { name: '开始复习' }).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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import js from '@eslint/js'
|
||||
import pluginVue from 'eslint-plugin-vue'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: [
|
||||
'dist/**',
|
||||
'node_modules/**',
|
||||
'test-results/**',
|
||||
'playwright-report/**',
|
||||
'env.d.ts',
|
||||
],
|
||||
},
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
...pluginVue.configs['flat/essential'],
|
||||
{
|
||||
files: ['**/*.vue'],
|
||||
languageOptions: {
|
||||
parserOptions: { parser: tseslint.parser },
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
// 页面级组件与路由表同名(Study/Review/Login…),命名约定见 AGENTS.md
|
||||
'vue/multi-word-component-names': 'off',
|
||||
// 渐进收敛:存量代码仍有 any,新代码约束见 AGENTS.md
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
},
|
||||
},
|
||||
]
|
||||
Generated
+2882
-1443
File diff suppressed because it is too large
Load Diff
+9
-4
@@ -10,38 +10,43 @@
|
||||
"build:production": "vite build --mode production",
|
||||
"build": "vite build --mode production",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint src",
|
||||
"lint:fix": "eslint src --fix",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build --force",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:e2e": "npx playwright test",
|
||||
"test:e2e:ui": "playwright test --ui"
|
||||
},
|
||||
"dependencies": {
|
||||
"async-validator": "^4.2.5",
|
||||
"axios": "^1.7.7",
|
||||
"css-loader": "^7.1.2",
|
||||
"element-plus": "^2.8.7",
|
||||
"marked": "^18.0.5",
|
||||
"mind-elixir": "^5.13.0",
|
||||
"normalize": "^0.3.1",
|
||||
"normalize.css": "^8.0.1",
|
||||
"style-loader": "^4.0.0",
|
||||
"vue": "^3.5.12",
|
||||
"vue-router": "^4.4.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@playwright/test": "^1.60.0",
|
||||
"@tsconfig/node20": "^20.1.4",
|
||||
"@types/jsdom": "^28.0.3",
|
||||
"@types/node": "^20.17.0",
|
||||
"@vitejs/plugin-vue": "^5.1.4",
|
||||
"@vitest/coverage-v8": "^2.1.9",
|
||||
"@vue/test-utils": "^2.4.10",
|
||||
"@vue/tsconfig": "^0.5.1",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-plugin-vue": "^9.33.0",
|
||||
"globals": "^17.11.0",
|
||||
"jsdom": "^24.1.3",
|
||||
"npm-run-all2": "^7.0.1",
|
||||
"tsx": "^4.23.0",
|
||||
"typescript": "~5.6.0",
|
||||
"typescript-eslint": "^8.68.0",
|
||||
"vite": "^5.4.10",
|
||||
"vitest": "^2.1.9",
|
||||
"vue-tsc": "^2.1.6"
|
||||
|
||||
Generated
-67
@@ -11,21 +11,12 @@ dependencies:
|
||||
axios:
|
||||
specifier: ^1.7.7
|
||||
version: 1.16.1
|
||||
css-loader:
|
||||
specifier: ^7.1.2
|
||||
version: 7.1.4(webpack@5.107.2)
|
||||
element-plus:
|
||||
specifier: ^2.8.7
|
||||
version: 2.14.0(vue@3.5.34)
|
||||
normalize:
|
||||
specifier: ^0.3.1
|
||||
version: 0.3.1
|
||||
normalize.css:
|
||||
specifier: ^8.0.1
|
||||
version: 8.0.1
|
||||
style-loader:
|
||||
specifier: ^4.0.0
|
||||
version: 4.0.0(webpack@5.107.2)
|
||||
vue:
|
||||
specifier: ^3.5.12
|
||||
version: 3.5.34(typescript@5.6.3)
|
||||
@@ -58,9 +49,6 @@ devDependencies:
|
||||
jsdom:
|
||||
specifier: ^24.1.3
|
||||
version: 24.1.3
|
||||
npm-run-all2:
|
||||
specifier: ^7.0.1
|
||||
version: 7.0.2
|
||||
typescript:
|
||||
specifier: ~5.6.0
|
||||
version: 5.6.3
|
||||
@@ -1271,29 +1259,6 @@ packages:
|
||||
shebang-command: 2.0.0
|
||||
which: 2.0.2
|
||||
|
||||
/css-loader@7.1.4(webpack@5.107.2):
|
||||
resolution: {integrity: sha512-vv3J9tlOl04WjiMvHQI/9tmIrCxVrj6PFbHemBB1iihpeRbi/I4h033eoFIhwxBBqLhI0KYFS7yvynBFhIZfTw==}
|
||||
engines: {node: '>= 18.12.0'}
|
||||
peerDependencies:
|
||||
'@rspack/core': 0.x || ^1.0.0 || ^2.0.0-0
|
||||
webpack: ^5.27.0
|
||||
peerDependenciesMeta:
|
||||
'@rspack/core':
|
||||
optional: true
|
||||
webpack:
|
||||
optional: true
|
||||
dependencies:
|
||||
icss-utils: 5.1.0(postcss@8.5.15)
|
||||
postcss: 8.5.15
|
||||
postcss-modules-extract-imports: 3.1.0(postcss@8.5.15)
|
||||
postcss-modules-local-by-default: 4.2.0(postcss@8.5.15)
|
||||
postcss-modules-scope: 3.2.1(postcss@8.5.15)
|
||||
postcss-modules-values: 4.0.0(postcss@8.5.15)
|
||||
postcss-value-parser: 4.2.0
|
||||
semver: 7.8.1
|
||||
webpack: 5.107.2(postcss@8.5.15)
|
||||
dev: false
|
||||
|
||||
/cssesc@3.0.0:
|
||||
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
|
||||
engines: {node: '>=4'}
|
||||
@@ -1931,34 +1896,11 @@ packages:
|
||||
resolution: {integrity: sha512-qizSNPO93t1YUuUhP22btGOo3chcvDFqFaj2TRybP0DMxkHOCTYwp3n34fel4a31ORXy4m1Xq0Gyqpb5m33qIg==}
|
||||
dev: false
|
||||
|
||||
/normalize@0.3.1:
|
||||
resolution: {integrity: sha512-DfyFcERXw4cjxUBgmATdxnCipRFoRvj0tNo+MWwjhebV9GZz2HYoNkXodEqS565uomk0CxEs90nEwrmj+aI9RQ==}
|
||||
dependencies:
|
||||
stylus: 0.64.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
dev: false
|
||||
|
||||
/npm-normalize-package-bin@4.0.0:
|
||||
resolution: {integrity: sha512-TZKxPvItzai9kN9H/TkmCtx/ZN/hvr3vUycjlfmH0ootY9yFBzNOpiXAdIn1Iteqsvk4lQn6B5PTrt+n6h8k/w==}
|
||||
engines: {node: ^18.17.0 || >=20.5.0}
|
||||
dev: true
|
||||
|
||||
/npm-run-all2@7.0.2:
|
||||
resolution: {integrity: sha512-7tXR+r9hzRNOPNTvXegM+QzCuMjzUIIq66VDunL6j60O4RrExx32XUhlrS7UK4VcdGw5/Wxzb3kfNcFix9JKDA==}
|
||||
engines: {node: ^18.17.0 || >=20.5.0, npm: '>= 9'}
|
||||
hasBin: true
|
||||
dependencies:
|
||||
ansi-styles: 6.2.3
|
||||
cross-spawn: 7.0.6
|
||||
memorystream: 0.3.1
|
||||
minimatch: 9.0.9
|
||||
pidtree: 0.6.0
|
||||
read-package-json-fast: 4.0.0
|
||||
shell-quote: 1.8.4
|
||||
which: 5.0.0
|
||||
dev: true
|
||||
|
||||
/nwsapi@2.2.23:
|
||||
resolution: {integrity: sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==}
|
||||
dev: true
|
||||
@@ -2283,15 +2225,6 @@ packages:
|
||||
dependencies:
|
||||
ansi-regex: 6.2.2
|
||||
|
||||
/style-loader@4.0.0(webpack@5.107.2):
|
||||
resolution: {integrity: sha512-1V4WqhhZZgjVAVJyt7TdDPZoPBPNHbekX4fWnCJL1yQukhCeZhJySUL+gL9y6sNdN95uEOS83Y55SqHcP7MzLA==}
|
||||
engines: {node: '>= 18.12.0'}
|
||||
peerDependencies:
|
||||
webpack: ^5.27.0
|
||||
dependencies:
|
||||
webpack: 5.107.2(postcss@8.5.15)
|
||||
dev: false
|
||||
|
||||
/stylus@0.64.0:
|
||||
resolution: {integrity: sha512-ZIdT8eUv8tegmqy1tTIdJv9We2DumkNZFdCF5mz/Kpq3OcTaxSuCAYZge6HKK2CmNC02G1eJig2RV7XTw5hQrA==}
|
||||
engines: {node: '>=16'}
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ const route = useRoute();
|
||||
</Transition>
|
||||
</RouterView>
|
||||
</el-main>
|
||||
<el-footer class="shell-footer">
|
||||
<el-footer v-if="route.path === '/login'" class="shell-footer">
|
||||
<MyFooter />
|
||||
</el-footer>
|
||||
</el-container>
|
||||
|
||||
@@ -22,10 +22,14 @@ describe('reportFragments API', () => {
|
||||
it('createFragments sends POST with sessionNum and content', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
const result = await createFragments('S001', '学习了递归')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/report-fragments', {
|
||||
sessionNum: 'S001',
|
||||
content: '学习了递归',
|
||||
})
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/report-fragments',
|
||||
{
|
||||
sessionNum: 'S001',
|
||||
content: '学习了递归',
|
||||
},
|
||||
{ timeout: 300000 },
|
||||
)
|
||||
expect(result).toEqual({ code: 200, data: { id: 1 } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
continueSession,
|
||||
pauseSession,
|
||||
endSession,
|
||||
abortSession,
|
||||
startOrContinueStudySession,
|
||||
getSessionDetail,
|
||||
} from '@/api/studySessions'
|
||||
@@ -57,7 +58,8 @@ describe('studySessions API', () => {
|
||||
await endSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/ended',
|
||||
{ content: '任务结束' }
|
||||
{ content: '任务结束' },
|
||||
{ timeout: 300000 }
|
||||
)
|
||||
})
|
||||
|
||||
@@ -66,7 +68,16 @@ describe('studySessions API', () => {
|
||||
await endSession('S001', '自定义结束')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/ended',
|
||||
{ content: '自定义结束' }
|
||||
{ content: '自定义结束' },
|
||||
{ timeout: 300000 }
|
||||
)
|
||||
})
|
||||
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: '我误操作导致开启了本次学习' }
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -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,142 @@
|
||||
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'
|
||||
// 真实挂载:shallow 会存根化 el-button 且不渲染插槽,无法断言按钮文案与点击行为
|
||||
async function mountRealAt(path: string) {
|
||||
await router.push(path)
|
||||
await router.isReady()
|
||||
return mount(MyHead, { global: { plugins: [ElementPlus, router] } })
|
||||
}
|
||||
|
||||
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('默认返回首页,复习详情按路由 meta 返回总览', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
it('isLoginRoute is false for other paths', () => {
|
||||
const routePath = ref('/welcome')
|
||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
||||
expect(isLoginRoute.value).toBe(false)
|
||||
})
|
||||
const studyWrapper = await mountRealAt('/study')
|
||||
expect(studyWrapper.find('.back-btn').text()).toBe('← 返回首页')
|
||||
await studyWrapper.find('.back-btn').trigger('click')
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/welcome'))
|
||||
studyWrapper.unmount()
|
||||
|
||||
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 taskDetailWrapper = await mountRealAt('/review/detail/task/T1')
|
||||
expect(taskDetailWrapper.find('.back-btn').text()).toBe('← 返回总览')
|
||||
await taskDetailWrapper.find('.back-btn').trigger('click')
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/review'))
|
||||
taskDetailWrapper.unmount()
|
||||
})
|
||||
|
||||
describe('handleLogout logic', () => {
|
||||
it('clears login state and navigates to login', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
it('多入口详情页优先返回来路,无历史时兜底到上级', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const backSpy = vi.spyOn(router, 'back').mockImplementation(() => {})
|
||||
|
||||
// Simulate handleLogout
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Backend failure shouldn't block logout
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
// 从回忆复习页进入:存在历史,回退到实际来路
|
||||
await mountRealAt('/review/recall/T1')
|
||||
const fromRecall = await mountRealAt('/review/detail/report/9')
|
||||
expect(fromRecall.find('.back-btn').text()).toBe('← 返回上一页')
|
||||
await fromRecall.find('.back-btn').trigger('click')
|
||||
expect(backSpy).toHaveBeenCalledTimes(1)
|
||||
fromRecall.unmount()
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
// 直接深链或刷新进入:没有历史,回退到该页声明的上级
|
||||
window.history.replaceState(
|
||||
{ back: null, current: '/review/detail/report/9', forward: null, position: 0 },
|
||||
'',
|
||||
)
|
||||
const deepLink = mount(MyHead, { global: { plugins: [ElementPlus, router] } })
|
||||
expect(deepLink.find('.back-btn').text()).toBe('← 返回上一页')
|
||||
await deepLink.find('.back-btn').trigger('click')
|
||||
expect(backSpy).toHaveBeenCalledTimes(1)
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/review'))
|
||||
deepLink.unmount()
|
||||
|
||||
it('clears login state even when API call fails', async () => {
|
||||
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
backSpy.mockRestore()
|
||||
})
|
||||
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Expected
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
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)
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
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('学习任务')
|
||||
|
||||
const welcomeWrapper = await mountAt('/welcome')
|
||||
expect(welcomeWrapper.vm.showBackButton).toBe(false)
|
||||
expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
|
||||
})
|
||||
|
||||
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')
|
||||
|
||||
await wrapper.vm.handleLogout()
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
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')
|
||||
|
||||
await wrapper.vm.handleLogout()
|
||||
|
||||
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,269 @@
|
||||
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)
|
||||
// 后端返回 0.8,UI 统一按百分比展示
|
||||
expect(wrapper.vm.taskInfo.effectivenessRatio).toBe('80.0%')
|
||||
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'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import Welcome from '@/components/Welcome.vue'
|
||||
import { getReviewFeed } from '@/api/review'
|
||||
import { BASE_SPEED_PX_PER_SEC, NARROW_SPEED_FACTOR } from '@/utils/autoScroll'
|
||||
|
||||
vi.mock('@/api/review', () => ({
|
||||
getReviewFeed: vi.fn(),
|
||||
getTaskReview: vi.fn(),
|
||||
}))
|
||||
|
||||
const makeFragment = (id: number) => ({
|
||||
id,
|
||||
sessionNum: `SESSION_${id}`,
|
||||
taskName: `任务${id}`,
|
||||
taskNum: `T${id}`,
|
||||
sourceType: 'FRAGMENT',
|
||||
content: `残片内容${id}`,
|
||||
})
|
||||
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/', component: { template: '<div />' } },
|
||||
{ path: '/welcome', component: { template: '<div />' } },
|
||||
{ path: '/study', component: { template: '<div />' } },
|
||||
{ path: '/review', component: { template: '<div />' } },
|
||||
],
|
||||
})
|
||||
|
||||
/** jsdom 不实现 Web Animations API,用可控桩替代 */
|
||||
interface AnimStub {
|
||||
keyframes: unknown
|
||||
options: { duration: number; iterations: number; easing: string }
|
||||
currentTime: number
|
||||
paused: boolean
|
||||
cancel: ReturnType<typeof vi.fn>
|
||||
pause: ReturnType<typeof vi.fn>
|
||||
play: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
let animations: AnimStub[] = []
|
||||
let animateSpy: ReturnType<typeof vi.fn>
|
||||
|
||||
/**
|
||||
* jsdom 不做布局,用宽度桩模拟渲染结果:
|
||||
* scrollWidth = 单份内容宽 × 当前已渲染份数(由 DOM 里的 chip 数量推得),
|
||||
* clientWidth = 轨道宽度。
|
||||
*/
|
||||
const stubLayout = (perCopyWidth: number, trackWidth: number) => {
|
||||
Object.defineProperty(HTMLElement.prototype, 'scrollWidth', {
|
||||
configurable: true,
|
||||
get(this: HTMLElement) {
|
||||
if (!this.classList?.contains('review-scroll-content')) return 0
|
||||
const renderedChips = this.querySelectorAll('.review-chip').length
|
||||
return perCopyWidth * (renderedChips / SOURCE_CHIP_COUNT)
|
||||
},
|
||||
})
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientWidth', {
|
||||
configurable: true,
|
||||
get(this: HTMLElement) {
|
||||
return this.classList?.contains('review-scroll-track') ? trackWidth : 0
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** mock 数据里的残留条数,用于把“份数”换算回“条数” */
|
||||
const SOURCE_CHIP_COUNT = 2
|
||||
/** 从渲染结果反推当前份数 */
|
||||
const renderedRepeatCount = (wrapper: { findAll: (s: string) => unknown[] }) =>
|
||||
wrapper.findAll('.review-chip').length / SOURCE_CHIP_COUNT
|
||||
|
||||
const mountWelcome = async () => {
|
||||
const wrapper = mount(Welcome, { global: { plugins: [router, ElementPlus] } })
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
animations = []
|
||||
animateSpy = vi.fn((keyframes: unknown, options: AnimStub['options']) => {
|
||||
const anim: AnimStub = {
|
||||
keyframes,
|
||||
options,
|
||||
currentTime: 0,
|
||||
paused: false,
|
||||
cancel: vi.fn(),
|
||||
pause: vi.fn(function (this: AnimStub) { this.paused = true }),
|
||||
play: vi.fn(function (this: AnimStub) { this.paused = false }),
|
||||
}
|
||||
animations.push(anim)
|
||||
return anim as unknown as Animation
|
||||
})
|
||||
Element.prototype.animate = animateSpy as unknown as Element['animate']
|
||||
vi.mocked(getReviewFeed).mockResolvedValue({ code: 200, data: [makeFragment(1), makeFragment(2)] })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
// @ts-expect-error 清理原型上的自定义布局桩
|
||||
delete HTMLElement.prototype.scrollWidth
|
||||
// @ts-expect-error 清理原型上的自定义布局桩
|
||||
delete HTMLElement.prototype.clientWidth
|
||||
})
|
||||
|
||||
describe('Welcome 首页滚动条', () => {
|
||||
it('内容超过一屏时按基准速度建立动画,时长由恒速换算', async () => {
|
||||
stubLayout(4000, 1000) // 单份 4000px,60px/s → 66666ms
|
||||
await mountWelcome()
|
||||
|
||||
expect(animateSpy).toHaveBeenCalledTimes(1)
|
||||
const options = animations[0].options
|
||||
expect(options.iterations).toBe(Infinity)
|
||||
expect(options.easing).toBe('linear')
|
||||
expect(options.duration).toBeCloseTo((4000 / BASE_SPEED_PX_PER_SEC) * 1000)
|
||||
})
|
||||
|
||||
it('速度与内容量无关:内容翻倍只让时长翻倍', async () => {
|
||||
stubLayout(4000, 1000)
|
||||
await mountWelcome()
|
||||
const few = animations[0].options.duration
|
||||
|
||||
animations = []
|
||||
animateSpy.mockClear()
|
||||
stubLayout(40000, 1000)
|
||||
await mountWelcome()
|
||||
const many = animations[0].options.duration
|
||||
|
||||
expect(many / few).toBeCloseTo(10)
|
||||
})
|
||||
|
||||
it('内容不足一屏时仍然滚动,且按单份宽度换算时长', async () => {
|
||||
stubLayout(300, 1000) // 单份 300px,远小于轨道
|
||||
await mountWelcome()
|
||||
|
||||
expect(animateSpy).toHaveBeenCalled()
|
||||
expect(animations[animations.length - 1].options.duration)
|
||||
.toBeCloseTo((300 / BASE_SPEED_PX_PER_SEC) * 1000)
|
||||
})
|
||||
|
||||
it('内容比轨道窄时补足份数后重建动画,避免循环露白', async () => {
|
||||
stubLayout(300, 1000) // 单份 300px、轨道 1000px → ceil(1000/300)+1 = 5 份
|
||||
const wrapper = await mountWelcome()
|
||||
|
||||
expect(renderedRepeatCount(wrapper)).toBe(5)
|
||||
expect(animateSpy).toHaveBeenCalledTimes(1)
|
||||
// 位移按份数换算:100% / 5 = 20%
|
||||
expect(animations[0].keyframes).toEqual([
|
||||
{ transform: 'translateX(0)' },
|
||||
{ transform: 'translateX(-20%)' },
|
||||
])
|
||||
})
|
||||
|
||||
it('内容足够宽时保持最少两份,不会反复重建', async () => {
|
||||
stubLayout(4000, 1000)
|
||||
const wrapper = await mountWelcome()
|
||||
|
||||
expect(renderedRepeatCount(wrapper)).toBe(2)
|
||||
expect(animateSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('窄屏(手机)按系数降速', async () => {
|
||||
stubLayout(4000, 375)
|
||||
await mountWelcome()
|
||||
|
||||
const speed = 4000 / (animations[0].options.duration / 1000)
|
||||
expect(speed).toBeCloseTo(BASE_SPEED_PX_PER_SEC * NARROW_SPEED_FACTOR)
|
||||
})
|
||||
|
||||
it('滚轮按速度换算手动位移,并夹在一轮时长内', async () => {
|
||||
stubLayout(4000, 1000)
|
||||
const wrapper = await mountWelcome()
|
||||
const track = wrapper.find('.review-scroll-track')
|
||||
|
||||
await track.trigger('wheel', { deltaY: BASE_SPEED_PX_PER_SEC, deltaMode: 0 })
|
||||
// 滚动 60px = 1 秒动画时间
|
||||
expect(animations[0].currentTime).toBeCloseTo(1000)
|
||||
|
||||
await track.trigger('wheel', { deltaY: -100000, deltaMode: 0 })
|
||||
expect(animations[0].currentTime).toBe(0)
|
||||
})
|
||||
|
||||
it('手指左右拖动共用同一套换算,拖动后恢复播放', async () => {
|
||||
stubLayout(4000, 1000)
|
||||
const wrapper = await mountWelcome()
|
||||
const track = wrapper.find('.review-scroll-track')
|
||||
|
||||
await track.trigger('touchstart', { touches: [{ clientX: 300 }] })
|
||||
expect(animations[0].paused).toBe(true)
|
||||
|
||||
await track.trigger('touchmove', { touches: [{ clientX: 360 }] })
|
||||
expect(animations[0].currentTime).toBeCloseTo(1000)
|
||||
|
||||
await track.trigger('touchend')
|
||||
expect(animations[0].paused).toBe(false)
|
||||
})
|
||||
|
||||
it('拖动后松开不会误触打开回忆卡片', async () => {
|
||||
stubLayout(4000, 1000)
|
||||
const wrapper = await mountWelcome()
|
||||
const track = wrapper.find('.review-scroll-track')
|
||||
|
||||
await track.trigger('touchstart', { touches: [{ clientX: 300 }] })
|
||||
await track.trigger('touchmove', { touches: [{ clientX: 400 }] })
|
||||
await wrapper.find('.review-chip').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.recall-question').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('点击残片(未拖动)会打开回忆卡片', async () => {
|
||||
stubLayout(4000, 1000)
|
||||
const wrapper = await mountWelcome()
|
||||
|
||||
await wrapper.find('.review-chip').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.recall-question').exists()).toBe(true)
|
||||
expect(wrapper.find('.recall-snippet').text()).toContain('残片内容1')
|
||||
})
|
||||
|
||||
it('卸载时取消动画并移除窗口监听', async () => {
|
||||
const removeSpy = vi.spyOn(window, 'removeEventListener')
|
||||
stubLayout(4000, 1000)
|
||||
const wrapper = await mountWelcome()
|
||||
|
||||
wrapper.unmount()
|
||||
|
||||
expect(animations[0].cancel).toHaveBeenCalled()
|
||||
expect(removeSpy).toHaveBeenCalledWith('resize', expect.any(Function))
|
||||
removeSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { useElapsedSeconds } from '@/components/composables/useElapsedSeconds'
|
||||
|
||||
describe('useElapsedSeconds', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
it('start 从 0 开始每秒递增', () => {
|
||||
const { seconds, start, stop } = useElapsedSeconds()
|
||||
|
||||
start()
|
||||
expect(seconds.value).toBe(0)
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
expect(seconds.value).toBe(3)
|
||||
stop()
|
||||
})
|
||||
|
||||
it('重复 start 会归零并重新计时', () => {
|
||||
const { seconds, start, stop } = useElapsedSeconds()
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(5000)
|
||||
|
||||
start()
|
||||
expect(seconds.value).toBe(0)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(seconds.value).toBe(1)
|
||||
stop()
|
||||
})
|
||||
|
||||
it('stop 停止递增但保留秒数', () => {
|
||||
const { seconds, start, stop } = useElapsedSeconds()
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
stop()
|
||||
expect(seconds.value).toBe(2)
|
||||
|
||||
vi.advanceTimersByTime(5000)
|
||||
expect(seconds.value).toBe(2)
|
||||
})
|
||||
|
||||
it('reset 停止并归零', () => {
|
||||
const { seconds, start, reset } = useElapsedSeconds()
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
reset()
|
||||
expect(seconds.value).toBe(0)
|
||||
|
||||
vi.advanceTimersByTime(5000)
|
||||
expect(seconds.value).toBe(0)
|
||||
})
|
||||
|
||||
it('在组件内使用时卸载自动清理定时器', async () => {
|
||||
const { mount } = await import('@vue/test-utils')
|
||||
const { defineComponent, h } = await import('vue')
|
||||
|
||||
let exposed!: ReturnType<typeof useElapsedSeconds>
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
exposed = useElapsedSeconds()
|
||||
return () => h('div')
|
||||
},
|
||||
})
|
||||
const wrapper = mount(Host)
|
||||
|
||||
exposed.start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(exposed.seconds.value).toBe(2)
|
||||
|
||||
wrapper.unmount()
|
||||
vi.advanceTimersByTime(5000)
|
||||
expect(exposed.seconds.value).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus, { ElMessage } from 'element-plus'
|
||||
import Login from '@/components/Login.vue'
|
||||
import router from '@/router'
|
||||
import { login } from '@/api/login'
|
||||
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}))
|
||||
|
||||
/**
|
||||
* 交互式集成测试:真实挂载 Login,通过 setValue / trigger('click') 模拟用户行为,
|
||||
* 断言提交链路(凭证传递、成功/失败分支、localStorage 与路由结果)。
|
||||
*
|
||||
* 注意:jsdom 下 Element Plus 的 callback 式表单校验不可靠(空表单也可能判有效),
|
||||
* “空账号被校验拦截”这类行为由 e2e/login.spec 在真实浏览器中覆盖,此处不重复断言。
|
||||
*/
|
||||
describe('Login 交互流程(集成)', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
const mountLogin = async () => {
|
||||
const wrapper = mount(Login, {
|
||||
global: { plugins: [ElementPlus, router] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
const findSubmitButton = (wrapper: ReturnType<typeof mount> extends Promise<infer T> ? T : never) =>
|
||||
wrapper.findAll('button').find((b) => b.text().includes('进入系统'))!
|
||||
|
||||
it('填写账号密码后点击“进入系统”,提交凭证并跳转 /welcome', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
||||
const wrapper = await mountLogin()
|
||||
|
||||
await wrapper.find('input[placeholder="请输入账号"]').setValue('admin')
|
||||
await wrapper.find('input[placeholder="请输入密码"]').setValue('123456')
|
||||
await findSubmitButton(wrapper).trigger('click')
|
||||
// /welcome 是懒加载路由,动态 import 需要宏任务,用 waitFor 轮询等待到达
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/welcome'))
|
||||
|
||||
expect(login).toHaveBeenCalledWith('admin', '123456')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('后端返回失败时提示错误、不写登录标记、不跳转', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 500, message: '账号或密码错误' } as any)
|
||||
const wrapper = await mountLogin()
|
||||
|
||||
await wrapper.find('input[placeholder="请输入账号"]').setValue('admin')
|
||||
await wrapper.find('input[placeholder="请输入密码"]').setValue('wrong-pass')
|
||||
await findSubmitButton(wrapper).trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(login).toHaveBeenCalledWith('admin', 'wrong-pass')
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('账号或密码错误')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import Review from '@/components/Review.vue'
|
||||
import { getReviewTaskStats } from '@/api/review'
|
||||
|
||||
vi.mock('@/api/review', () => ({
|
||||
getReviewTaskStats: vi.fn(),
|
||||
getReviewFeed: vi.fn(),
|
||||
getTaskReview: vi.fn(),
|
||||
}))
|
||||
|
||||
const tasks = [
|
||||
{
|
||||
taskNum: 'T001',
|
||||
taskName: '学习 Vue3 组合式 API',
|
||||
reportCount: 3,
|
||||
fragmentCount: 5,
|
||||
effectiveTime: 9000,
|
||||
},
|
||||
{
|
||||
taskNum: 'T002',
|
||||
taskName: 'TypeScript 类型体操',
|
||||
reportCount: 1,
|
||||
fragmentCount: 2,
|
||||
effectiveTime: 4500,
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* 交互式集成测试:真实挂载 Review 总览页,
|
||||
* 覆盖卡片进入详情、回忆复习跳转、加载失败提示三条用户可见路径。
|
||||
*/
|
||||
describe('Review 交互流程(集成)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const mountReview = async () => {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/review', name: 'review', component: Review },
|
||||
{ path: '/review/detail/task/:taskNum', name: 'review-detail', component: { template: '<div />' } },
|
||||
{ path: '/review/recall/:taskNum', name: 'review-recall', component: { template: '<div />' } },
|
||||
],
|
||||
})
|
||||
await router.push('/review')
|
||||
await router.isReady()
|
||||
|
||||
const wrapper = mount(Review, {
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
// el-tag 在 jsdom + VTU 下 vnode mounted 钩子崩溃(EP 2.8 已知问题),纯视觉组件,stub 掉
|
||||
stubs: { ElTag: true },
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
return { wrapper, router }
|
||||
}
|
||||
|
||||
it('点击卡片空白处进入该任务的复习详情', async () => {
|
||||
vi.mocked(getReviewTaskStats).mockResolvedValue({ code: 200, data: tasks })
|
||||
const { wrapper, router } = await mountReview()
|
||||
|
||||
expect(wrapper.findAll('.task-card')).toHaveLength(2)
|
||||
await wrapper.findAll('.task-card')[1].trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/review/detail/task/T002')
|
||||
})
|
||||
|
||||
it('键盘 Enter 与 Space 也能进入详情', async () => {
|
||||
vi.mocked(getReviewTaskStats).mockResolvedValue({ code: 200, data: tasks })
|
||||
const { wrapper, router } = await mountReview()
|
||||
|
||||
await wrapper.findAll('.task-card')[0].trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/review/detail/task/T001')
|
||||
|
||||
await router.push('/review')
|
||||
await flushPromises()
|
||||
await wrapper.findAll('.task-card')[0].trigger('keydown', { key: ' ' })
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/review/detail/task/T001')
|
||||
})
|
||||
|
||||
it('点击「回忆复习」进入回忆页,且不被卡片点击覆盖', async () => {
|
||||
vi.mocked(getReviewTaskStats).mockResolvedValue({ code: 200, data: tasks })
|
||||
const { wrapper, router } = await mountReview()
|
||||
|
||||
await wrapper.find('.recall-button').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/review/recall/T001')
|
||||
})
|
||||
|
||||
it('卡片暴露 role 与 aria-label,具备可访问语义', async () => {
|
||||
vi.mocked(getReviewTaskStats).mockResolvedValue({ code: 200, data: tasks })
|
||||
const { wrapper } = await mountReview()
|
||||
|
||||
const card = wrapper.findAll('.task-card')[0]
|
||||
expect(card.attributes('role')).toBe('link')
|
||||
expect(card.attributes('tabindex')).toBe('0')
|
||||
expect(card.attributes('aria-label')).toContain('学习 Vue3 组合式 API')
|
||||
})
|
||||
|
||||
it('接口失败时提示加载失败并提供重试,而不是显示空列表', async () => {
|
||||
vi.mocked(getReviewTaskStats).mockRejectedValue({ code: 500, message: '服务异常' })
|
||||
const { wrapper } = await mountReview()
|
||||
|
||||
expect(wrapper.text()).toContain('复习数据加载失败,请稍后重试')
|
||||
expect(wrapper.text()).not.toContain('暂无复习任务')
|
||||
expect(wrapper.find('button').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('重试按钮会重新请求接口,成功后展示卡片列表', async () => {
|
||||
vi.mocked(getReviewTaskStats)
|
||||
.mockRejectedValueOnce({ code: 500, message: '服务异常' })
|
||||
.mockResolvedValueOnce({ code: 200, data: tasks })
|
||||
const { wrapper } = await mountReview()
|
||||
|
||||
expect(wrapper.text()).toContain('复习数据加载失败,请稍后重试')
|
||||
|
||||
const retry = wrapper.findAll('button').find(b => b.text().includes('重新加载'))
|
||||
expect(retry).toBeTruthy()
|
||||
await retry!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(getReviewTaskStats).toHaveBeenCalledTimes(2)
|
||||
expect(wrapper.findAll('.task-card')).toHaveLength(2)
|
||||
expect(wrapper.text()).not.toContain('复习数据加载失败')
|
||||
})
|
||||
|
||||
it('无任务时展示空列表文案,不显示失败提示', async () => {
|
||||
vi.mocked(getReviewTaskStats).mockResolvedValue({ code: 200, data: [] })
|
||||
const { wrapper } = await mountReview()
|
||||
|
||||
expect(wrapper.text()).toContain('暂无复习任务')
|
||||
expect(wrapper.text()).not.toContain('复习数据加载失败')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus, { ElMessage } from 'element-plus'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import ReviewRecall from '@/components/ReviewRecall.vue'
|
||||
import {
|
||||
getStandardMindMap,
|
||||
listRecallRecords,
|
||||
recallCompare,
|
||||
} from '@/api/standardMindMap'
|
||||
|
||||
vi.mock('@/api/standardMindMap', () => ({
|
||||
findNode: vi.fn(),
|
||||
getStandardMindMap: vi.fn(),
|
||||
listRecallRecords: vi.fn(),
|
||||
recallCompare: vi.fn(),
|
||||
regenerateStandardMindMap: vi.fn(),
|
||||
updateStandardMindMap: vi.fn(),
|
||||
}))
|
||||
|
||||
const ok = (data: any = null) => ({ code: 200, message: '请求成功', data })
|
||||
|
||||
const standardMap = {
|
||||
id: 1,
|
||||
taskNum: 'T001',
|
||||
title: '测试任务',
|
||||
content: JSON.stringify({ title: '根主题', children: [{ title: '子节点' }] }),
|
||||
outline: '根主题\n- 子节点',
|
||||
summary: '',
|
||||
generator: 'AI',
|
||||
sourceReportCount: 1,
|
||||
}
|
||||
|
||||
/** MindMapViewer 依赖 mind-elixir(无法在 jsdom 运行),用可编程 stub 模拟导出的大纲 */
|
||||
const toOutline = vi.fn((): string => '根主题\n- 子节点')
|
||||
const MindMapViewerStub = {
|
||||
name: 'MindMapViewerStub',
|
||||
props: ['modelValue', 'nodeSelectable', 'colorByCompare', 'readonly'],
|
||||
template: '<div class="mindmap-stub" />',
|
||||
methods: { toOutline },
|
||||
}
|
||||
|
||||
/**
|
||||
* 交互式集成测试:真实挂载 ReviewRecall,
|
||||
* 点击“提交对比”模拟回忆对比流,断言 API 参数与对比结果渲染。
|
||||
*/
|
||||
describe('ReviewRecall 交互流程(集成)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
vi.mocked(getStandardMindMap).mockResolvedValue(ok(standardMap))
|
||||
vi.mocked(listRecallRecords).mockResolvedValue(
|
||||
ok([
|
||||
{
|
||||
id: 11,
|
||||
taskNum: 'T001',
|
||||
standardMapId: 1,
|
||||
recallContent: '根主题',
|
||||
compareResult: JSON.stringify({
|
||||
matchedTree: { title: '根主题', children: [] },
|
||||
recallRatio: 0.6,
|
||||
matchedCount: 3,
|
||||
missedCount: 2,
|
||||
extraCount: 0,
|
||||
}),
|
||||
recallRatio: 0.6,
|
||||
matchedCount: 3,
|
||||
missedCount: 2,
|
||||
extraCount: 0,
|
||||
createdTime: '2026-08-27 10:00:00',
|
||||
},
|
||||
]),
|
||||
)
|
||||
vi.mocked(recallCompare).mockResolvedValue(ok(standardMap))
|
||||
})
|
||||
|
||||
const mountPage = async () => {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [{ path: '/review/recall/:taskNum', component: ReviewRecall, meta: { wide: true } }],
|
||||
})
|
||||
await router.push('/review/recall/T001')
|
||||
await router.isReady()
|
||||
|
||||
const wrapper = mount(ReviewRecall, {
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
stubs: { ElTag: true, MindMapViewer: MindMapViewerStub },
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
return { wrapper }
|
||||
}
|
||||
|
||||
it('加载后展示标准导图标题,点击“提交对比”调用对比接口并渲染结果', async () => {
|
||||
const { wrapper } = await mountPage()
|
||||
// 默认折叠标准导图(防剧透),回忆面板可见
|
||||
expect(wrapper.text()).toContain('你的回忆')
|
||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '提交对比')!
|
||||
expect(submit).toBeTruthy()
|
||||
await submit.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(recallCompare).toHaveBeenCalledWith('T001', '根主题\n- 子节点', undefined)
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('回忆对比完成')
|
||||
// 对比完成后出现“清空重写”入口(v-if=hasCompared)
|
||||
expect(wrapper.findAll('button').some((b) => b.text().trim() === '清空重写')).toBe(true)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('回忆导图内容为单行时点击“提交对比”,提示先添加节点且不调接口', async () => {
|
||||
const { wrapper } = await mountPage()
|
||||
toOutline.mockReturnValue('只有一个根')
|
||||
|
||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '提交对比')!
|
||||
await submit.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const { ElMessage: Msg } = await import('element-plus')
|
||||
expect(Msg.warning).toHaveBeenCalledWith('请先在回忆导图中添加节点(选中节点后按 Tab 加子节点)')
|
||||
expect(recallCompare).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import StartTask from '@/components/StartTask.vue'
|
||||
import {
|
||||
continueSession,
|
||||
endSession,
|
||||
getActiveSession,
|
||||
getExpectation,
|
||||
getReportDraft,
|
||||
getSessionDetail,
|
||||
pauseSession,
|
||||
startOrContinueStudySession,
|
||||
} from '@/api/studySessions'
|
||||
import { getFragmentsBySession } from '@/api/reportFragments'
|
||||
|
||||
vi.mock('@/api/studySessions', () => ({
|
||||
abortSession: vi.fn(),
|
||||
continueSession: vi.fn(),
|
||||
endSession: 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(),
|
||||
}))
|
||||
|
||||
const sessionOngoing = {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
taskName: '测试任务',
|
||||
taskNum: 'T001',
|
||||
taskId: 1,
|
||||
startTime: '2026-08-27 10:00:00',
|
||||
endTime: '',
|
||||
lastStartTime: '2026-08-27 10:00:00',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1_500_000,
|
||||
systemMessage: '',
|
||||
}
|
||||
|
||||
const ok = (data: any = null) => ({ code: 200, message: '请求成功', data })
|
||||
|
||||
/**
|
||||
* 交互式集成测试:真实挂载 StartTask(不 shallow),
|
||||
* 通过 trigger('click') 模拟“暂停 → 开始”完整用户流,断言 DOM 状态与 API 调用序列。
|
||||
*/
|
||||
describe('StartTask 交互流程(集成)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
vi.mocked(getActiveSession).mockResolvedValue(ok(null))
|
||||
vi.mocked(startOrContinueStudySession).mockResolvedValue(ok(sessionOngoing))
|
||||
vi.mocked(getExpectation).mockResolvedValue(ok({ description: '本次学习预期' }))
|
||||
vi.mocked(getFragmentsBySession).mockResolvedValue(ok([]))
|
||||
vi.mocked(pauseSession).mockResolvedValue(ok())
|
||||
vi.mocked(continueSession).mockResolvedValue(ok())
|
||||
})
|
||||
|
||||
const mountPage = async () => {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/start-task/:taskNum', component: StartTask },
|
||||
{ path: '/study', component: { template: '<div />' } },
|
||||
],
|
||||
})
|
||||
await router.push('/start-task/T001')
|
||||
await router.isReady()
|
||||
|
||||
const wrapper = mount(StartTask, {
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
// el-tag 在 jsdom + VTU 下 vnode mounted 钩子崩溃(EP 2.8 已知问题),纯视觉组件,stub 掉
|
||||
stubs: { ElTag: true },
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
return { wrapper, router }
|
||||
}
|
||||
|
||||
const findButton = (wrapper: any, text: string) =>
|
||||
wrapper.findAll('button').find((b: any) => b.text().trim() === text)
|
||||
|
||||
it('进行中的会话:点击“暂停”同步后端状态,再点“开始”触发 continue 并恢复进行中', async () => {
|
||||
// 暂停后从详情接口同步回 PAUSED 状态
|
||||
vi.mocked(getSessionDetail).mockResolvedValue(
|
||||
ok({ ...sessionOngoing, sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20 }),
|
||||
)
|
||||
|
||||
const { wrapper } = await mountPage()
|
||||
expect(wrapper.find('.status-text').text()).toContain('进行中')
|
||||
|
||||
// 点击暂停:调用 pause API,页面状态变为已暂停
|
||||
const pauseBtn = findButton(wrapper, '暂停')
|
||||
expect(pauseBtn).toBeTruthy()
|
||||
await pauseBtn.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||
expect(wrapper.find('.status-text').text()).toContain('已暂停')
|
||||
|
||||
// 点击开始:会话为 PAUSED,应触发 continue API 并恢复进行中
|
||||
const startBtn = findButton(wrapper, '开始')
|
||||
expect(startBtn).toBeTruthy()
|
||||
await startBtn.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(continueSession).toHaveBeenCalledWith('SESSION_001')
|
||||
expect(wrapper.find('.status-text').text()).toContain('进行中')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('点击“结束会话”打开总结弹窗,无内容时确认结束被拦截', async () => {
|
||||
const { wrapper } = await mountPage()
|
||||
|
||||
const endBtn = findButton(wrapper, '结束会话')
|
||||
await endBtn.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
// 总结弹窗出现(无残片 → 不触发 AI 草稿等待)
|
||||
expect(wrapper.text()).toContain('结束会话总结')
|
||||
expect(getReportDraft).not.toHaveBeenCalled()
|
||||
|
||||
// 总结内容为空时点击确认结束:弹警示、不调接口
|
||||
const confirmEnd = findButton(wrapper, '确认结束')
|
||||
await confirmEnd.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const { ElMessage } = await import('element-plus')
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
|
||||
expect(endSession).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus, { ElMessage } from 'element-plus'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import TaskForm from '@/components/TaskForm.vue'
|
||||
import request from '@/utils/request'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn().mockResolvedValue({ code: 200, data: null }),
|
||||
post: vi.fn(),
|
||||
put: vi.fn().mockResolvedValue({ code: 200, data: null }),
|
||||
del: vi.fn().mockResolvedValue({ code: 200, data: null }),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockedPost = vi.mocked(request.post)
|
||||
|
||||
/**
|
||||
* 交互式集成测试:真实挂载 TaskForm(add 模式),
|
||||
* 填写任务名称 → 点击“添加”提交 → 断言请求载荷、成功提示与路由跳转。
|
||||
*/
|
||||
describe('TaskForm 交互流程(集成)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
})
|
||||
|
||||
const mountAddForm = async () => {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{
|
||||
path: '/add-task',
|
||||
name: 'add-task',
|
||||
component: TaskForm,
|
||||
meta: { requiresAuth: true, title: '创建学习任务', action: 'add', buttonText: '添加' },
|
||||
},
|
||||
{ path: '/study', name: 'study', component: { template: '<div />' } },
|
||||
],
|
||||
})
|
||||
await router.push('/add-task')
|
||||
await router.isReady()
|
||||
|
||||
const wrapper = mount(TaskForm, {
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
// el-tag 在 jsdom + VTU 下 vnode mounted 钩子崩溃(EP 2.8 已知问题),纯视觉组件,stub 掉
|
||||
stubs: { ElTag: true },
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
return { wrapper, router }
|
||||
}
|
||||
|
||||
it('填写任务名称后点击“添加”,提交 POST /tasks 并跳转学习任务页', async () => {
|
||||
mockedPost.mockResolvedValue({ code: 200, data: null } as any)
|
||||
const { wrapper, router } = await mountAddForm()
|
||||
|
||||
const nameInput = wrapper.find('input[placeholder="例如:Vue3 组件通信实践"]')
|
||||
expect(nameInput.exists()).toBe(true)
|
||||
await nameInput.setValue('集成测试任务')
|
||||
|
||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '添加')!
|
||||
expect(submit).toBeTruthy()
|
||||
await submit.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(mockedPost).toHaveBeenCalledWith(
|
||||
'/tasks',
|
||||
expect.objectContaining({
|
||||
taskName: '集成测试任务',
|
||||
taskDescription: '',
|
||||
materialUrl: '',
|
||||
}),
|
||||
)
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('创建任务成功')
|
||||
expect(router.currentRoute.value.path).toBe('/study')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('优先级维度区块展示取值范围与各维度含义说明', async () => {
|
||||
const { wrapper } = await mountAddForm()
|
||||
|
||||
const hint = wrapper.find('.priority-hint')
|
||||
expect(hint.exists()).toBe(true)
|
||||
expect(hint.text()).toContain('取值范围均为 0')
|
||||
expect(hint.text()).toContain('紧急性代表时间压力')
|
||||
expect(hint.text()).toContain('主观优先级是你的直觉判断')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('后端返回失败时提示错误、不跳转', async () => {
|
||||
mockedPost.mockResolvedValue({ code: 500, message: '任务名称重复' } as any)
|
||||
const { wrapper, router } = await mountAddForm()
|
||||
|
||||
await wrapper.find('input[placeholder="例如:Vue3 组件通信实践"]').setValue('重复任务')
|
||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '添加')!
|
||||
await submit.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('任务创建失败:任务名称重复')
|
||||
expect(router.currentRoute.value.path).toBe('/add-task')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
BASE_SPEED_PX_PER_SEC,
|
||||
MAX_REPEAT_COUNT,
|
||||
MAX_SPEED_PX_PER_SEC,
|
||||
MIN_REPEAT_COUNT,
|
||||
MIN_SPEED_PX_PER_SEC,
|
||||
NARROW_SPEED_FACTOR,
|
||||
clampAutoScrollTime,
|
||||
getRepeatCount,
|
||||
getScrollSpeedPxPerSec,
|
||||
measureAutoScroll,
|
||||
pxToTimeOffset,
|
||||
} from '@/utils/autoScroll'
|
||||
|
||||
const DESKTOP = 1440
|
||||
|
||||
describe('getScrollSpeedPxPerSec', () => {
|
||||
it('桌面端使用基准速度', () => {
|
||||
expect(getScrollSpeedPxPerSec(DESKTOP)).toBe(BASE_SPEED_PX_PER_SEC)
|
||||
})
|
||||
|
||||
it('正好 768px 属于手机端,769px 回到桌面速度', () => {
|
||||
expect(getScrollSpeedPxPerSec(768)).toBeCloseTo(BASE_SPEED_PX_PER_SEC * NARROW_SPEED_FACTOR)
|
||||
expect(getScrollSpeedPxPerSec(769)).toBe(BASE_SPEED_PX_PER_SEC)
|
||||
})
|
||||
|
||||
it('手机端是桌面速度的固定倍数', () => {
|
||||
const narrow = getScrollSpeedPxPerSec(375)
|
||||
expect(narrow).toBeCloseTo(BASE_SPEED_PX_PER_SEC * NARROW_SPEED_FACTOR)
|
||||
expect(narrow).toBeLessThan(getScrollSpeedPxPerSec(DESKTOP))
|
||||
})
|
||||
|
||||
it('桌面速度始终夹在上下限内', () => {
|
||||
;[0, 769, 1024, 1440, 2560].forEach(width => {
|
||||
const speed = getScrollSpeedPxPerSec(width)
|
||||
expect(speed).toBeGreaterThanOrEqual(MIN_SPEED_PX_PER_SEC)
|
||||
expect(speed).toBeLessThanOrEqual(MAX_SPEED_PX_PER_SEC)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('measureAutoScroll', () => {
|
||||
it('一轮距离为单份内容宽度,时长由恒速换算', () => {
|
||||
// 单份 2000px;60px/s → 33.3s
|
||||
const metrics = measureAutoScroll(2000, DESKTOP)
|
||||
expect(metrics).not.toBeNull()
|
||||
expect(metrics!.loopWidth).toBe(2000)
|
||||
expect(metrics!.speed).toBe(BASE_SPEED_PX_PER_SEC)
|
||||
expect(metrics!.duration).toBeCloseTo((2000 / BASE_SPEED_PX_PER_SEC) * 1000)
|
||||
})
|
||||
|
||||
it('速度恒定:内容量翻倍只改变时长,不改变速度', () => {
|
||||
const few = measureAutoScroll(2000, DESKTOP)!
|
||||
const many = measureAutoScroll(20000, DESKTOP)!
|
||||
expect(few.speed).toBe(many.speed)
|
||||
expect(many.duration / few.duration).toBeCloseTo(10)
|
||||
})
|
||||
|
||||
it('内容为空或宽度异常时返回 null', () => {
|
||||
expect(measureAutoScroll(0, DESKTOP)).toBeNull()
|
||||
expect(measureAutoScroll(-100, DESKTOP)).toBeNull()
|
||||
expect(measureAutoScroll(Number.NaN, DESKTOP)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRepeatCount', () => {
|
||||
it('内容再多也用最少两份', () => {
|
||||
expect(getRepeatCount(5000, 1000)).toBe(MIN_REPEAT_COUNT)
|
||||
})
|
||||
|
||||
it('内容比轨道窄时补足到能铺满并预留衔接份', () => {
|
||||
// 单份 300px、轨道 1000px:ceil(1000/300)+1 = 5
|
||||
expect(getRepeatCount(300, 1000)).toBe(5)
|
||||
// 刚好铺满也要多一份用于衔接
|
||||
expect(getRepeatCount(1000, 1000)).toBe(2)
|
||||
})
|
||||
|
||||
it('份数不超过上限', () => {
|
||||
expect(getRepeatCount(1, 100000)).toBe(MAX_REPEAT_COUNT)
|
||||
})
|
||||
|
||||
it('宽度非法时回退到最少份数', () => {
|
||||
expect(getRepeatCount(0, 1000)).toBe(MIN_REPEAT_COUNT)
|
||||
expect(getRepeatCount(Number.NaN, 1000)).toBe(MIN_REPEAT_COUNT)
|
||||
expect(getRepeatCount(300, 0)).toBe(MIN_REPEAT_COUNT)
|
||||
})
|
||||
|
||||
it('measureAutoScroll 会带上份数', () => {
|
||||
expect(measureAutoScroll(300, 1000)!.repeatCount).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pxToTimeOffset', () => {
|
||||
it('按速度把位移换算成时间', () => {
|
||||
expect(pxToTimeOffset(BASE_SPEED_PX_PER_SEC, BASE_SPEED_PX_PER_SEC)).toBe(1000)
|
||||
expect(pxToTimeOffset(30, 60)).toBe(500)
|
||||
})
|
||||
|
||||
it('速度为 0 或参数非法时返回 0', () => {
|
||||
expect(pxToTimeOffset(100, 0)).toBe(0)
|
||||
expect(pxToTimeOffset(Number.NaN, 60)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('clampAutoScrollTime', () => {
|
||||
it('夹在 0 与一轮时长之间', () => {
|
||||
expect(clampAutoScrollTime(-500, 1000)).toBe(0)
|
||||
expect(clampAutoScrollTime(1500, 1000)).toBe(1000)
|
||||
expect(clampAutoScrollTime(400, 1000)).toBe(400)
|
||||
})
|
||||
|
||||
it('参数非法时归零', () => {
|
||||
expect(clampAutoScrollTime(Number.NaN, 1000)).toBe(0)
|
||||
expect(clampAutoScrollTime(100, 0)).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatRatio } from '@/utils/format'
|
||||
|
||||
describe('formatRatio', () => {
|
||||
it('把 0~1 的比率格式化为一位小数的百分比', () => {
|
||||
expect(formatRatio(0.8)).toBe('80.0%')
|
||||
expect(formatRatio(0.8571)).toBe('85.7%')
|
||||
expect(formatRatio(1)).toBe('100.0%')
|
||||
expect(formatRatio(0)).toBe('0.0%')
|
||||
})
|
||||
|
||||
it('兼容后端返回字符串形式的比率', () => {
|
||||
expect(formatRatio('0.8')).toBe('80.0%')
|
||||
})
|
||||
|
||||
it('空值与非法值统一显示 "-"', () => {
|
||||
expect(formatRatio()).toBe('-')
|
||||
expect(formatRatio(null)).toBe('-')
|
||||
expect(formatRatio('')).toBe('-')
|
||||
expect(formatRatio('abc')).toBe('-')
|
||||
})
|
||||
})
|
||||
@@ -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('该功能暂不可用,请刷新后重试')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
// src/api/reportFragments.ts
|
||||
import request from "@/utils/request";
|
||||
|
||||
// 残片生成走 AI 聚合,耗时较长,放宽到 5 分钟(默认全局 30s)
|
||||
const AI_TIMEOUT = { timeout: 300_000 };
|
||||
|
||||
export const createFragments = (sessionNum: string, content: string) => {
|
||||
return request.post(`/report-fragments`, {sessionNum, content})
|
||||
return request.post(`/report-fragments`, { sessionNum, content }, AI_TIMEOUT)
|
||||
}
|
||||
|
||||
export const updateFragments = (id: number, content: string) => {
|
||||
return request.put(`/report-fragments/${id}`, {content})
|
||||
return request.put(`/report-fragments/${id}`, { content })
|
||||
}
|
||||
|
||||
export const getFragmentsBySession = (sessionNum: string) => {
|
||||
return request.get(`/report-fragments/session/${sessionNum}`)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -24,15 +24,15 @@ export interface ReviewTaskStats {
|
||||
}
|
||||
|
||||
export const getReviewFeed = (limit: number = 30, mode: "recent" | "random" | "smart" = "recent") => {
|
||||
return request.get("/review/feed", { limit, mode });
|
||||
return request.get<ReviewFeedItem[]>("/review/feed", { limit, mode });
|
||||
};
|
||||
|
||||
export const getReviewTaskStats = () => {
|
||||
return request.get("/review/tasks");
|
||||
return request.get<ReviewTaskStats[]>("/review/tasks");
|
||||
};
|
||||
|
||||
export const getReviewTaskStatsByTask = (taskNum: string) => {
|
||||
return request.get(`/review/tasks/${taskNum}`);
|
||||
return request.get<ReviewTaskStats>(`/review/tasks/${taskNum}`);
|
||||
};
|
||||
|
||||
export const getReportDetail = (id: number) => {
|
||||
|
||||
+14
-18
@@ -1,4 +1,5 @@
|
||||
import request from "@/utils/request";
|
||||
import type { ApiResponse } from "@/utils/request";
|
||||
|
||||
// ============ 标准思维导图 ============
|
||||
|
||||
@@ -12,7 +13,6 @@ export interface StandardMindMap {
|
||||
generator: "BUILTIN" | "AI" | "USER" | "USER_MERGE";
|
||||
generatorVersion?: string;
|
||||
sourceReportCount: number;
|
||||
sourceFragmentCount: number;
|
||||
generatedTime?: string;
|
||||
createdTime?: string;
|
||||
lastModifiedTime?: string;
|
||||
@@ -32,20 +32,17 @@ export interface RecallRecord {
|
||||
createdTime: string;
|
||||
}
|
||||
|
||||
export interface FindNodeResult {
|
||||
path: string;
|
||||
nodeTitle: string;
|
||||
score: number;
|
||||
}
|
||||
// AI 聚合类接口耗时较长,统一放宽到 5 分钟(默认全局 30s)
|
||||
const AI_TIMEOUT = { timeout: 300_000 };
|
||||
|
||||
/** 获取/自动生成标准思维导图 */
|
||||
/** 获取/自动生成标准思维导图(首次访问会触发 AI 生成) */
|
||||
export const getStandardMindMap = (taskNum: string) => {
|
||||
return request.get(`/review/standard-mind-map/${taskNum}`);
|
||||
return request.get<StandardMindMap>(`/review/standard-mind-map/${taskNum}`, {}, AI_TIMEOUT);
|
||||
};
|
||||
|
||||
/** 强制重新生成标准思维导图(全量或增量) */
|
||||
export const regenerateStandardMindMap = (taskNum: string, mode: "full" | "incremental" = "full") => {
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/regenerate?mode=${mode}`);
|
||||
return request.post<StandardMindMap>(`/review/standard-mind-map/${taskNum}/regenerate?mode=${mode}`, null, AI_TIMEOUT);
|
||||
};
|
||||
|
||||
/** 用户编辑标准思维导图(大纲文本) */
|
||||
@@ -54,23 +51,22 @@ export const updateStandardMindMap = (taskNum: string, outline: string) => {
|
||||
};
|
||||
|
||||
/** 用户提交回忆大纲,与标准导图对比(可选指定起始节点路径) */
|
||||
export const recallCompare = (taskNum: string, recallOutline: string, focusPath?: string) => {
|
||||
export const recallCompare = (
|
||||
taskNum: string,
|
||||
recallOutline: string,
|
||||
focusPath?: string,
|
||||
): Promise<ApiResponse<StandardMindMap>> => {
|
||||
const body: Record<string, any> = { recallOutline };
|
||||
if (focusPath) body.focusPath = focusPath;
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/recall`, body);
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/recall`, body, AI_TIMEOUT);
|
||||
};
|
||||
|
||||
/** 在标准导图中查找与内容最匹配的节点 */
|
||||
export const findNode = (taskNum: string, content: string) => {
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/find-node`, { content });
|
||||
return request.post<{ path: string }>(`/review/standard-mind-map/${taskNum}/find-node`, { content });
|
||||
};
|
||||
|
||||
/** 获取该任务的所有回忆对比记录 */
|
||||
export const listRecallRecords = (taskNum: string) => {
|
||||
return request.get(`/review/standard-mind-map/${taskNum}/recall-records`);
|
||||
};
|
||||
|
||||
/** 获取单条回忆对比记录 */
|
||||
export const getRecallRecord = (recordId: number) => {
|
||||
return request.get(`/review/standard-mind-map/recall-records/${recordId}`);
|
||||
return request.get<RecallRecord[]>(`/review/standard-mind-map/${taskNum}/recall-records`);
|
||||
};
|
||||
|
||||
+52
-12
@@ -1,6 +1,40 @@
|
||||
// src/api/studySession.ts
|
||||
// src/api/studySessions.ts
|
||||
import request from "@/utils/request";
|
||||
|
||||
/** 学习会话详情(start-or-continue / detail 接口返回的会话核心字段) */
|
||||
export interface SessionDetail {
|
||||
sessionNum: string;
|
||||
sessionState: "ONGOING" | "PAUSED" | "ENDED";
|
||||
taskNum: string;
|
||||
taskId: number;
|
||||
taskName?: string;
|
||||
materialUrl?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
lastStartTime?: string;
|
||||
actualTime?: number;
|
||||
effectiveTime?: number;
|
||||
effectivenessRatio?: number | string;
|
||||
pointerPosition?: number;
|
||||
systemMessage?: string;
|
||||
}
|
||||
|
||||
/** 当前活跃会话摘要(跨页面恢复用) */
|
||||
export interface ActiveSessionInfo {
|
||||
taskNum: string;
|
||||
sessionNum: string;
|
||||
taskName?: string;
|
||||
}
|
||||
|
||||
/** 后端 MyBatis-Plus 分页包装 */
|
||||
export interface PagedResult<T> {
|
||||
records: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// AI 聚合类接口耗时较长,统一放宽到 5 分钟(默认全局 30s)
|
||||
const AI_TIMEOUT = { timeout: 300_000 };
|
||||
|
||||
export const continueSession = (sessionNum: string) => {
|
||||
return request.post(`/study-sessions/${sessionNum}/study-sessions/continue`);
|
||||
};
|
||||
@@ -10,21 +44,27 @@ export const pauseSession = (sessionNum: string, endTime?: Date) => {
|
||||
return request.post(`/study-sessions/${sessionNum}/study-sessions/pause`, null, { params });
|
||||
};
|
||||
|
||||
/** 结束会话会触发后端报告生成,耗时较长 */
|
||||
export const endSession = (sessionNum: string, content: string = "任务结束") => {
|
||||
return request.post(`/study-sessions/${sessionNum}/study-sessions/ended`, { content });
|
||||
return request.post(`/study-sessions/${sessionNum}/study-sessions/ended`, { content }, AI_TIMEOUT);
|
||||
};
|
||||
|
||||
/** 误操作结束学习会话:需输入确认语,严格零数据关闭(删除会话与预期) */
|
||||
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`);
|
||||
return request.get<SessionDetail>(`/tasks/${taskNum}/study-sessions/start-or-continue`);
|
||||
};
|
||||
|
||||
export const getSessionDetail = (sessionNum: string) => {
|
||||
return request.get(`/study-sessions/${sessionNum}`);
|
||||
return request.get<SessionDetail>(`/study-sessions/${sessionNum}`);
|
||||
};
|
||||
|
||||
/** 获取会话的学习预期 */
|
||||
export const getExpectation = (sessionNum: string) => {
|
||||
return request.get(`/study-sessions/${sessionNum}/expectation`);
|
||||
return request.get<{ description: string } | null>(`/study-sessions/${sessionNum}/expectation`);
|
||||
};
|
||||
|
||||
/** 创建/更新会话的学习预期 */
|
||||
@@ -32,28 +72,28 @@ export const upsertExpectation = (sessionNum: string, description: string) => {
|
||||
return request.put(`/study-sessions/${sessionNum}/expectation`, { description });
|
||||
};
|
||||
|
||||
/** 获取报告草稿(AI 聚合残片,不可用时为拼接) */
|
||||
/** 获取报告草稿(AI 聚合残片,不可用时为拼接),生成失败不阻塞手写总结 */
|
||||
export const getReportDraft = (sessionNum: string) => {
|
||||
return request.get(`/study-sessions/${sessionNum}/report-draft`);
|
||||
return request.get<string>(`/study-sessions/${sessionNum}/report-draft`, {}, AI_TIMEOUT);
|
||||
};
|
||||
|
||||
/** 查询当前是否有活跃会话 */
|
||||
export const getActiveSession = (excludeTaskNum?: string) => {
|
||||
const params: Record<string, any> = {};
|
||||
if (excludeTaskNum) params.excludeTaskNum = excludeTaskNum;
|
||||
return request.get('/study-sessions/active', params);
|
||||
return request.get<ActiveSessionInfo | null>('/study-sessions/active', params);
|
||||
};
|
||||
|
||||
/** 分页查询任务的历史残片 */
|
||||
export const getTaskFragments = (taskNum: string, page: number, size: number, keyword?: string) => {
|
||||
export const getTaskFragments = <T = any>(taskNum: string, page: number, size: number, keyword?: string) => {
|
||||
const params: Record<string, any> = { page, size };
|
||||
if (keyword) params.keyword = keyword;
|
||||
return request.get(`/study-sessions/tasks/${taskNum}/fragments`, params);
|
||||
return request.get<PagedResult<T>>(`/study-sessions/tasks/${taskNum}/fragments`, params);
|
||||
};
|
||||
|
||||
/** 分页查询任务的历史报告 */
|
||||
export const getTaskReports = (taskNum: string, page: number, size: number, keyword?: string) => {
|
||||
export const getTaskReports = <T = any>(taskNum: string, page: number, size: number, keyword?: string) => {
|
||||
const params: Record<string, any> = { page, size };
|
||||
if (keyword) params.keyword = keyword;
|
||||
return request.get(`/study-sessions/tasks/${taskNum}/reports`, params);
|
||||
return request.get<PagedResult<T>>(`/study-sessions/tasks/${taskNum}/reports`, params);
|
||||
};
|
||||
|
||||
+5
-5
@@ -12,7 +12,7 @@ export interface TaskApplication {
|
||||
}
|
||||
|
||||
export const getTaskApplications = (taskNum: string) => {
|
||||
return request.get(`/tasks/${taskNum}/applications`);
|
||||
return request.get<TaskApplication[]>(`/tasks/${taskNum}/applications`);
|
||||
};
|
||||
|
||||
export const createTaskApplication = (
|
||||
@@ -24,7 +24,7 @@ export const createTaskApplication = (
|
||||
status?: TaskApplication["status"];
|
||||
},
|
||||
) => {
|
||||
return request.post(`/tasks/${taskNum}/applications`, payload);
|
||||
return request.post<TaskApplication>(`/tasks/${taskNum}/applications`, payload);
|
||||
};
|
||||
|
||||
export const updateTaskApplication = (
|
||||
@@ -36,7 +36,7 @@ export const updateTaskApplication = (
|
||||
status?: TaskApplication["status"];
|
||||
},
|
||||
) => {
|
||||
return request.put(`/tasks/applications/${id}`, payload);
|
||||
return request.put<TaskApplication>(`/tasks/applications/${id}`, payload);
|
||||
};
|
||||
|
||||
export const deleteTaskApplication = (id: number) => {
|
||||
@@ -54,10 +54,10 @@ export interface PriorityWeights {
|
||||
}
|
||||
|
||||
export const getPriorityWeights = () => {
|
||||
return request.get("/tasks/priority-weights");
|
||||
return request.get<PriorityWeights>("/tasks/priority-weights");
|
||||
};
|
||||
|
||||
/** 保存权重配置并触发全部任务优先级重算 */
|
||||
export const savePriorityWeights = (weights: PriorityWeights) => {
|
||||
return request.put("/tasks/priority-weights", weights);
|
||||
return request.put<PriorityWeights>("/tasks/priority-weights", weights);
|
||||
};
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
:root {
|
||||
--green-900: #123d2d;
|
||||
--green-800: #1a5a42;
|
||||
--green-700: #237556;
|
||||
--green-600: #2f8f68;
|
||||
--green-500: #43a879;
|
||||
--green-200: #d9f1e5;
|
||||
--green-100: #eef9f3;
|
||||
--surface: #f7fbf8;
|
||||
--surface-strong: #ffffff;
|
||||
--text-primary: #1b2a23;
|
||||
--text-secondary: #4b6156;
|
||||
--border-soft: #d6e6dc;
|
||||
--shadow-soft: 0 14px 30px rgba(19, 61, 45, 0.09);
|
||||
--shadow-strong: 0 20px 45px rgba(19, 61, 45, 0.16);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
background:
|
||||
radial-gradient(circle at 12% 18%, rgba(67, 168, 121, 0.2), transparent 32%),
|
||||
radial-gradient(circle at 85% 0%, rgba(35, 117, 86, 0.14), transparent 28%),
|
||||
linear-gradient(165deg, #eef9f3 0%, #f8fcfa 50%, #edf7f1 100%);
|
||||
font-family: "Source Han Sans SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>
|
||||
|
Before Width: | Height: | Size: 276 B |
+171
-1
@@ -1,4 +1,84 @@
|
||||
@import "./base.css";
|
||||
:root {
|
||||
--green-900: #123d2d;
|
||||
--green-800: #1a5a42;
|
||||
--green-700: #237556;
|
||||
--green-600: #2f8f68;
|
||||
--green-500: #43a879;
|
||||
--green-100: #eef9f3;
|
||||
--surface: #f7fbf8;
|
||||
--surface-strong: #ffffff;
|
||||
--text-primary: #1b2a23;
|
||||
--text-secondary: #4b6156;
|
||||
--border-soft: #d6e6dc;
|
||||
--shadow-soft: 0 14px 30px rgba(19, 61, 45, 0.09);
|
||||
--shadow-strong: 0 20px 45px rgba(19, 61, 45, 0.16);
|
||||
|
||||
/* 残片/提醒语义色(对应 EP warning 色系,避免各组件硬编码) */
|
||||
--accent-warning: #e6a23c;
|
||||
--accent-warning-soft: #fff8e1;
|
||||
--accent-warning-strong: #b8860b;
|
||||
/* 成功/命中语义的浅底与深字(统计卡片、标签共用) */
|
||||
--accent-success-soft: #e8f5e9;
|
||||
--accent-success-softer: #f1f8e9;
|
||||
--accent-success-strong: #2e7d32;
|
||||
--accent-success-text: #856404;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
background:
|
||||
radial-gradient(circle at 12% 18%, rgba(67, 168, 121, 0.2), transparent 32%),
|
||||
radial-gradient(circle at 85% 0%, rgba(35, 117, 86, 0.14), transparent 28%),
|
||||
linear-gradient(165deg, #eef9f3 0%, #f8fcfa 50%, #edf7f1 100%);
|
||||
font-family: "Source Han Sans SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* Element Plus 主题对齐
|
||||
*
|
||||
* EP 默认 success 是黄绿 #67c23a,与本站墨绿主题色相不一致,
|
||||
* 且白字压在其上对比度仅 2.24:1(低于 WCAG AA 4.5:1)。
|
||||
* 这里统一改写 EP 的 success / primary 色阶,使全站按钮、标签、
|
||||
* 开关等组件自动使用主题绿。
|
||||
*
|
||||
* 注意:本文件在 main.ts 中必须导入在 element-plus 样式之后,
|
||||
* 否则同特异度下会被 EP 默认值覆盖。
|
||||
* ------------------------------------------------------------------ */
|
||||
:root {
|
||||
/* primary 与 success 同源:本站正向语义统一走 success,primary 仅次级编辑 */
|
||||
--el-color-primary: var(--green-700);
|
||||
--el-color-primary-light-3: #4a8f74;
|
||||
--el-color-primary-light-5: #6ba98f;
|
||||
--el-color-primary-light-7: #9cc7b5;
|
||||
--el-color-primary-light-8: #bcd9cc;
|
||||
--el-color-primary-light-9: #eef9f3;
|
||||
--el-color-primary-dark-2: var(--green-800);
|
||||
|
||||
--el-color-success: var(--green-700);
|
||||
--el-color-success-light-3: #4a8f74;
|
||||
--el-color-success-light-5: #6ba98f;
|
||||
--el-color-success-light-7: #9cc7b5;
|
||||
--el-color-success-light-8: #bcd9cc;
|
||||
--el-color-success-light-9: #eef9f3;
|
||||
--el-color-success-dark-2: var(--green-800);
|
||||
}
|
||||
|
||||
#app {
|
||||
width: 100%;
|
||||
@@ -35,6 +115,96 @@ a:hover {
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* 按钮尺寸收敛
|
||||
*
|
||||
* EP 默认 large / default / small 三档实测高度为 32 / 32 / 24px:
|
||||
* large 与 default 在视觉上无法区分,行内 small 的 24px 又低于触屏
|
||||
* 舒适点击区。这里保持两个视觉层级:
|
||||
* 主操作 large → 40px 高
|
||||
* 常规/行内 default、small → 至少 28px 高(保留 small 的紧凑感)
|
||||
* 字号统一 13px 上限,避免行内按钮字号过小(原为 12px)。
|
||||
* ------------------------------------------------------------------ */
|
||||
.el-button--large {
|
||||
--el-button-size: 40px;
|
||||
padding: 0 20px;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.el-button--small {
|
||||
--el-button-size: 28px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.el-button--small.is-text,
|
||||
.el-button--small.is-link {
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
/* 按钮操作区统一规范:窄屏下操作按钮纵向全宽 */
|
||||
.action-row .el-button,
|
||||
.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,
|
||||
.task-actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-row .el-button,
|
||||
.edit-actions .el-button,
|
||||
.fragment-edit-actions .el-button,
|
||||
.task-actions .el-button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 移动端弹窗适配:覆盖 Element Plus 内联宽度并约束 footer */
|
||||
@media (max-width: 768px) {
|
||||
.el-dialog {
|
||||
--el-dialog-width: calc(100% - 24px) !important;
|
||||
--el-dialog-margin-top: 5vh;
|
||||
max-height: calc(100vh - 60px);
|
||||
}
|
||||
|
||||
.el-dialog__body {
|
||||
max-height: calc(100vh - 200px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.el-dialog__footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.el-dialog__footer .el-button {
|
||||
flex: 1;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.el-message-box {
|
||||
max-width: calc(100% - 24px);
|
||||
}
|
||||
|
||||
.el-message-box__btns {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.el-message-box__btns .el-button {
|
||||
flex: 1;
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.fade-up-enter-active,
|
||||
.fade-up-leave-active {
|
||||
transition: opacity 0.22s ease, transform 0.22s ease;
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
msg: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="greetings">
|
||||
<h1 class="green">{{ msg }}</h1>
|
||||
<h3>
|
||||
You’ve successfully created a project with
|
||||
<a href="https://vite.dev/" target="_blank" rel="noopener">Vite</a> +
|
||||
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
|
||||
</h3>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
h1 {
|
||||
font-weight: 500;
|
||||
font-size: 2.6rem;
|
||||
position: relative;
|
||||
top: -10px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.greetings h1,
|
||||
.greetings h3 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.greetings h1,
|
||||
.greetings h3 {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -50,6 +50,8 @@ const submitForm = async (formEl: FormInstance | undefined) => {
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
defineExpose({ registerData, loading, submitForm, isNotEmpty });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -82,7 +82,7 @@ const rendered = computed(() => {
|
||||
margin: 0.5em 0;
|
||||
padding: 0.5em 1em;
|
||||
border-left: 3px solid var(--green-600, #2f8f68);
|
||||
background: #f1f8e9;
|
||||
background: var(--accent-success-softer);
|
||||
color: #555;
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ const rendered = computed(() => {
|
||||
}
|
||||
|
||||
.markdown-body :deep(th) {
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,13 +27,9 @@ const props = defineProps<{
|
||||
height?: string;
|
||||
/** 节点可选择模式(点击节点触发 node-select 事件) */
|
||||
selectable?: boolean;
|
||||
/** 当前选中的节点路径(用于高亮,仅在 selectable 模式下生效) */
|
||||
selectedPath?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 编辑模式下结构变化时抛出最新大纲文本 */
|
||||
(e: "change", outline: string): void;
|
||||
/** 点击带溯源信息的节点 */
|
||||
(e: "node-click", node: { sourceType: string; sourceId: number }): void;
|
||||
/** 选择模式下点击节点,返回标题+路径 */
|
||||
@@ -61,6 +57,31 @@ const countAllDescendants = (node: MindMapTreeNode): number => {
|
||||
const COLOR_MATCHED = { background: "#c8e6c9", color: "#1b5e20" };
|
||||
const COLOR_MISSED = { background: "#ffcdd2", color: "#b71c1c" };
|
||||
|
||||
/**
|
||||
* 浅色主题:基于内置 Latte,画布/节点配色对齐全站薄荷绿主题(base.css 变量值)。
|
||||
* 注意:mind-elixir 主题只接受字面量,不能引用 CSS 变量,此处保留字面量。
|
||||
*/
|
||||
const LPT_LIGHT_THEME = {
|
||||
...MindElixir.THEME,
|
||||
name: "LPT Light",
|
||||
palette: ["#237556", "#2f8f68", "#43a879", "#1a5a42", "#5cb88a", "#7cc9a3"],
|
||||
cssVar: {
|
||||
...MindElixir.THEME.cssVar,
|
||||
"--bgcolor": "#f7fbf8",
|
||||
"--color": "#4b6156",
|
||||
"--root-bgcolor": "#237556",
|
||||
"--root-color": "#ffffff",
|
||||
"--main-color": "#1b2a23",
|
||||
"--main-bgcolor": "#ffffff",
|
||||
"--main-bgcolor-transparent": "rgba(255, 255, 255, 0.85)",
|
||||
"--selected": "#43a879",
|
||||
"--accent-color": "#237556",
|
||||
"--panel-color": "#1b2a23",
|
||||
"--panel-bgcolor": "#ffffff",
|
||||
"--panel-border-color": "#d6e6dc",
|
||||
},
|
||||
};
|
||||
|
||||
const compareStatus = (notes?: string): "MATCHED" | "MISSED" | null => {
|
||||
if (!notes) return null;
|
||||
if (notes.startsWith("MATCHED|")) return "MATCHED";
|
||||
@@ -153,15 +174,10 @@ const render = () => {
|
||||
contextMenu: !!props.editable,
|
||||
toolBar: true,
|
||||
keypress: !!props.editable,
|
||||
theme: LPT_LIGHT_THEME,
|
||||
});
|
||||
instance.init(toElixirData(props.tree));
|
||||
|
||||
if (props.editable) {
|
||||
instance.bus.addListener("operation", () => {
|
||||
emit("change", toOutline());
|
||||
});
|
||||
}
|
||||
|
||||
// mind-elixir v5: selectNode(el) is called on every node click, but the
|
||||
// selectNewNode event is never fired (it requires selectNode(el, true),
|
||||
// which the default click handler never passes). Monkey-patch selectNode
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
v-if="showBackButton"
|
||||
text
|
||||
class="back-btn"
|
||||
@click="router.push('/welcome')"
|
||||
@click="goBack"
|
||||
>
|
||||
← 返回首页
|
||||
← {{ backLabel }}
|
||||
</el-button>
|
||||
<template v-if="pageTitle">
|
||||
<h1 class="head-title">{{ pageTitle }}</h1>
|
||||
@@ -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,39 @@ 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);
|
||||
// 返回目标由路由 meta 声明,未声明时回首页
|
||||
const backTo = computed(() => (route.meta?.backTo as string | undefined) || "/welcome");
|
||||
const backLabel = computed(() => (route.meta?.backLabel as string | undefined) || "返回首页");
|
||||
// 有多个入口的页面(如复习详情)优先回到用户来路,无历史时回退到声明的上级
|
||||
const backUseHistory = computed(() => route.meta?.backUseHistory === true);
|
||||
const loggingOut = ref(false);
|
||||
|
||||
const goBack = () => {
|
||||
if (backUseHistory.value && window.history.state?.back) {
|
||||
router.back();
|
||||
return;
|
||||
}
|
||||
router.push(backTo.value);
|
||||
};
|
||||
|
||||
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, backTo, backLabel, loggingOut, goBack, handleLogout });
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
+122
-56
@@ -1,18 +1,15 @@
|
||||
<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 loadFailed = ref(false);
|
||||
const tasks = ref<ReviewTaskStats[]>([]);
|
||||
|
||||
const summary = computed(() => ({
|
||||
@@ -32,29 +29,21 @@ const formatEffectiveTime = (seconds: number | string): string => {
|
||||
|
||||
const loadTasks = async () => {
|
||||
loading.value = true;
|
||||
loadFailed.value = false;
|
||||
try {
|
||||
const res = await getReviewTaskStats();
|
||||
tasks.value = res?.data || [];
|
||||
} catch {
|
||||
// 请求层已提示具体错误,这里只保证不把失败当作空列表展示
|
||||
loadFailed.value = true;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
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(() => {
|
||||
@@ -64,9 +53,8 @@ onMounted(() => {
|
||||
|
||||
<template>
|
||||
<section class="review-page">
|
||||
<div class="table-toolbar">
|
||||
<span class="toolbar-placeholder"></span>
|
||||
<el-button type="success" plain size="small" :loading="loading" @click="loadTasks">刷新</el-button>
|
||||
<div class="page-toolbar">
|
||||
<el-button :loading="loading" @click="loadTasks">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="summary-grid">
|
||||
@@ -84,37 +72,49 @@ onMounted(() => {
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<article class="surface-card table-card">
|
||||
<el-table v-loading="loading" :data="tasks" stripe @row-click="openTaskReview">
|
||||
<el-table-column prop="taskName" label="任务名" min-width="180" />
|
||||
<el-table-column prop="effectiveTime" label="累计有效学习时长" min-width="150">
|
||||
<template #default="{ row }">
|
||||
{{ formatEffectiveTime(row.effectiveTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="reportCount" label="学习报告数" min-width="120" />
|
||||
<el-table-column prop="fragmentCount" label="学习残片数" min-width="120" />
|
||||
<el-table-column label="操作" width="200">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
text
|
||||
type="success"
|
||||
:loading="openingTaskNum === row.taskNum"
|
||||
@click.stop="openTaskReview(row)"
|
||||
>
|
||||
查看记录
|
||||
</el-button>
|
||||
<el-button
|
||||
text
|
||||
type="primary"
|
||||
@click.stop="router.push(`/review/recall/${row.taskNum}`)"
|
||||
>
|
||||
回忆复习
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</article>
|
||||
<div v-if="tasks.length > 0" v-loading="loading" class="task-list">
|
||||
<article
|
||||
v-for="row in tasks"
|
||||
:key="row.taskNum"
|
||||
class="surface-card task-card"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
:aria-label="`查看 ${row.taskName} 的学习记录`"
|
||||
@click="openTaskReview(row)"
|
||||
@keydown.enter.prevent="openTaskReview(row)"
|
||||
@keydown.space.prevent="openTaskReview(row)"
|
||||
>
|
||||
<div class="task-head">
|
||||
<strong>{{ row.taskName }}</strong>
|
||||
</div>
|
||||
<div class="task-meta">
|
||||
<span>累计有效学习时长:{{ formatEffectiveTime(row.effectiveTime) }}</span>
|
||||
</div>
|
||||
<div class="task-stats">
|
||||
<span>学习报告数量:{{ row.reportCount || 0 }}</span>
|
||||
<span>学习残片数量:{{ row.fragmentCount || 0 }}</span>
|
||||
</div>
|
||||
<!-- 卡片整体已可进详情,这里只保留「回忆复习」作为明确的主操作 -->
|
||||
<div class="task-actions">
|
||||
<span class="detail-hint">查看详情 →</span>
|
||||
<el-button
|
||||
class="recall-button"
|
||||
type="success"
|
||||
size="small"
|
||||
@click.stop="router.push(`/review/recall/${row.taskNum}`)"
|
||||
>
|
||||
回忆复习
|
||||
</el-button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<el-empty
|
||||
v-if="!loading && loadFailed"
|
||||
description="复习数据加载失败,请稍后重试"
|
||||
>
|
||||
<el-button type="success" plain @click="loadTasks">重新加载</el-button>
|
||||
</el-empty>
|
||||
<el-empty v-else-if="!loading && tasks.length === 0" description="暂无复习任务" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -125,7 +125,7 @@ onMounted(() => {
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.table-toolbar {
|
||||
.page-toolbar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
@@ -153,12 +153,66 @@ onMounted(() => {
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.table-card {
|
||||
padding: 10px;
|
||||
.task-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.table-card :deep(.el-table__row) {
|
||||
.task-card {
|
||||
padding: 14px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease;
|
||||
}
|
||||
|
||||
.task-card:hover {
|
||||
transform: translateY(-1px);
|
||||
border-color: var(--green-500, #43a879);
|
||||
box-shadow: var(--shadow-strong, var(--shadow-soft));
|
||||
}
|
||||
|
||||
.task-card:focus-visible {
|
||||
outline: 2px solid var(--green-700);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.detail-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
opacity: 0;
|
||||
transition: opacity 0.18s ease, color 0.18s ease;
|
||||
}
|
||||
|
||||
.task-card:hover .detail-hint,
|
||||
.task-card:focus-visible .detail-hint {
|
||||
opacity: 1;
|
||||
color: var(--green-600);
|
||||
}
|
||||
|
||||
.task-head strong {
|
||||
display: block;
|
||||
color: var(--green-900);
|
||||
font-size: 15px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.task-meta,
|
||||
.task-stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 14px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.task-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
@@ -166,4 +220,16 @@ onMounted(() => {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
/* 窄屏只保留一个主操作,不需要纵向堆叠与顺序调整 */
|
||||
.task-actions {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.task-actions .el-button {
|
||||
width: auto;
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -8,35 +8,32 @@ import {
|
||||
type ReviewFeedItem,
|
||||
} from "@/api/review";
|
||||
import { getSessionDetail } from "@/api/studySessions";
|
||||
import type { SessionDetail } from "@/api/studySessions";
|
||||
import { updateFragments } from "@/api/reportFragments";
|
||||
import { findNode } from "@/api/standardMindMap";
|
||||
import { formatRatio } from "@/utils/format";
|
||||
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("");
|
||||
@@ -47,14 +44,7 @@ const isEditing = ref(false);
|
||||
const editContent = ref("");
|
||||
const saving = ref(false);
|
||||
|
||||
const sessionInfo = ref<{
|
||||
taskName: string;
|
||||
sessionNum: string;
|
||||
actualTime?: number;
|
||||
effectiveTime?: number;
|
||||
effectivenessRatio?: number;
|
||||
startTime?: string;
|
||||
} | null>(null);
|
||||
const sessionInfo = ref<SessionDetail | null>(null);
|
||||
|
||||
const taskSessions = ref<{
|
||||
sessionNum: string;
|
||||
@@ -73,11 +63,6 @@ const formatDuration = (seconds?: number): string => {
|
||||
return `${s}秒`;
|
||||
};
|
||||
|
||||
const formatRatio = (ratio?: number): string => {
|
||||
if (ratio == null) return "-";
|
||||
return `${(ratio * 100).toFixed(1)}%`;
|
||||
};
|
||||
|
||||
const loadTaskHistory = async (tn: string) => {
|
||||
try {
|
||||
const res = await getTaskReview(tn);
|
||||
@@ -118,7 +103,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 +191,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 },
|
||||
@@ -252,8 +253,8 @@ watch(
|
||||
placeholder="请输入学习内容"
|
||||
/>
|
||||
<div class="edit-actions">
|
||||
<el-button @click="cancelEdit">取消</el-button>
|
||||
<el-button type="success" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
<el-button size="small" @click="cancelEdit">取消</el-button>
|
||||
<el-button type="success" size="small" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 只读模式 -->
|
||||
@@ -391,7 +392,7 @@ watch(
|
||||
}
|
||||
|
||||
.history-session.is-current {
|
||||
background: #f1f8e9;
|
||||
background: var(--accent-success-softer);
|
||||
margin: 0 -10px;
|
||||
padding: 14px 10px;
|
||||
border-radius: 8px;
|
||||
@@ -445,7 +446,7 @@ watch(
|
||||
}
|
||||
|
||||
.clickable-text.active {
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
border-left: 3px solid var(--green-600);
|
||||
}
|
||||
|
||||
@@ -460,13 +461,13 @@ watch(
|
||||
}
|
||||
|
||||
.report-tag {
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
color: var(--green-700);
|
||||
}
|
||||
|
||||
.fragment-tag {
|
||||
background: #fff8e1;
|
||||
color: #b8860b;
|
||||
background: var(--accent-warning-soft);
|
||||
color: var(--accent-warning-strong);
|
||||
}
|
||||
|
||||
.edit-area {
|
||||
@@ -480,11 +481,4 @@ watch(
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.form-row {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
@@ -2,17 +2,18 @@
|
||||
import { ref, onMounted, computed } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
findNode,
|
||||
getStandardMindMap,
|
||||
regenerateStandardMindMap,
|
||||
recallCompare,
|
||||
updateStandardMindMap,
|
||||
listRecallRecords,
|
||||
findNode,
|
||||
type StandardMindMap,
|
||||
type RecallRecord,
|
||||
} from "@/api/standardMindMap";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
|
||||
import { useElapsedSeconds } from "@/components/composables/useElapsedSeconds";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -21,17 +22,26 @@ const taskNum = computed(() => route.params.taskNum as string);
|
||||
const loading = ref(false);
|
||||
const standard = ref<StandardMindMap | null>(null);
|
||||
const comparing = ref(false);
|
||||
const comparingSeconds = ref(0);
|
||||
let comparingTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const {
|
||||
seconds: comparingSeconds,
|
||||
start: startComparingTimer,
|
||||
stop: stopComparingTimer,
|
||||
} = useElapsedSeconds();
|
||||
|
||||
// 重新生成标准导图
|
||||
const regenerating = ref(false);
|
||||
const regeneratingSeconds = ref(0);
|
||||
let regeneratingTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const {
|
||||
seconds: regeneratingSeconds,
|
||||
start: startRegeneratingTimer,
|
||||
stop: stopRegeneratingTimer,
|
||||
} = useElapsedSeconds();
|
||||
const lastResult = ref<any>(null);
|
||||
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);
|
||||
|
||||
@@ -51,6 +61,7 @@ const editViewer = ref<InstanceType<typeof MindMapViewer> | null>(null);
|
||||
// 回忆历史
|
||||
const historyRecords = ref<RecallRecord[]>([]);
|
||||
const showHistory = ref(false);
|
||||
const historyLoading = ref(false);
|
||||
|
||||
// 解析标准导图 JSON 为树节点
|
||||
const standardTree = computed<MindMapTreeNode | null>(() => {
|
||||
@@ -114,7 +125,18 @@ const loadData = async () => {
|
||||
try {
|
||||
const res = await getStandardMindMap(taskNum.value);
|
||||
standard.value = res?.data || null;
|
||||
} catch (e: any) {
|
||||
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 {
|
||||
standard.value = null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
@@ -188,8 +210,7 @@ const handleRegenerate = async () => {
|
||||
|
||||
// 开始生成
|
||||
regenerating.value = true;
|
||||
regeneratingSeconds.value = 0;
|
||||
regeneratingTimer = setInterval(() => { regeneratingSeconds.value++; }, 1000);
|
||||
startRegeneratingTimer();
|
||||
try {
|
||||
const res = await regenerateStandardMindMap(taskNum.value, mode);
|
||||
standard.value = res?.data || null;
|
||||
@@ -198,7 +219,7 @@ const handleRegenerate = async () => {
|
||||
ElMessage.error(e.message || "重新生成失败");
|
||||
} finally {
|
||||
regenerating.value = false;
|
||||
if (regeneratingTimer) { clearInterval(regeneratingTimer); regeneratingTimer = null; }
|
||||
stopRegeneratingTimer();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -210,8 +231,7 @@ const handleRecallCompare = async () => {
|
||||
return;
|
||||
}
|
||||
comparing.value = true;
|
||||
comparingSeconds.value = 0;
|
||||
comparingTimer = setInterval(() => { comparingSeconds.value++; }, 1000);
|
||||
startComparingTimer();
|
||||
try {
|
||||
const res = await recallCompare(taskNum.value, outline, focusPath.value || undefined);
|
||||
standard.value = res?.data || null;
|
||||
@@ -235,7 +255,7 @@ const handleRecallCompare = async () => {
|
||||
ElMessage.error(e.message || "对比失败");
|
||||
} finally {
|
||||
comparing.value = false;
|
||||
if (comparingTimer) { clearInterval(comparingTimer); comparingTimer = null; }
|
||||
stopComparingTimer();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -250,6 +270,8 @@ const resetComparison = () => {
|
||||
hasCompared.value = false;
|
||||
focusPath.value = "";
|
||||
recallTree.value = buildEmptyRecallTree();
|
||||
standardExpanded.value = true;
|
||||
editingStandard.value = false;
|
||||
};
|
||||
|
||||
// 编辑标准导图
|
||||
@@ -294,12 +316,19 @@ const cancelStandardEdit = () => {
|
||||
|
||||
// 查看回忆历史
|
||||
const loadHistory = async () => {
|
||||
if (showHistory.value) {
|
||||
showHistory.value = false;
|
||||
return;
|
||||
}
|
||||
historyLoading.value = true;
|
||||
try {
|
||||
const res = await listRecallRecords(taskNum.value);
|
||||
historyRecords.value = res?.data || [];
|
||||
showHistory.value = true;
|
||||
} catch {
|
||||
ElMessage.error("加载历史记录失败");
|
||||
} finally {
|
||||
historyLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -311,6 +340,8 @@ const selectHistoryRecord = (record: RecallRecord) => {
|
||||
const tree = parseOutlineToTree(record.recallContent);
|
||||
if (tree) recallTree.value = tree;
|
||||
hasCompared.value = true;
|
||||
focusPath.value = record.focusPath || "";
|
||||
standardExpanded.value = true;
|
||||
} catch {
|
||||
ElMessage.error("解析对比记录失败");
|
||||
}
|
||||
@@ -371,13 +402,12 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="recall-page">
|
||||
<!-- 顶部操作栏 -->
|
||||
<section class="recall-page" v-loading="loading">
|
||||
<!-- 顶部操作栏(页面标题由 MyHead 提供,这里只保留操作) -->
|
||||
<div class="page-header">
|
||||
<el-button size="small" @click="router.back()">← 返回</el-button>
|
||||
<h2>回忆复习</h2>
|
||||
<el-button size="small" @click="loadHistory" v-if="!showHistory">
|
||||
历史记录
|
||||
<span class="header-spacer"></span>
|
||||
<el-button :loading="historyLoading" @click="loadHistory">
|
||||
{{ showHistory ? "收起历史" : "历史记录" }}
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
@@ -385,12 +415,12 @@ onMounted(() => {
|
||||
<div class="review-scope surface-card" v-if="focusPath">
|
||||
<span class="scope-label">复习起点</span>
|
||||
<el-tag size="small" type="success" effect="light">{{ focusPath }}</el-tag>
|
||||
<el-button size="small" text @click="focusPath = ''">重选节点</el-button>
|
||||
<el-button size="small" text @click="resetComparison">重选节点</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 节点选择确认弹窗 -->
|
||||
<el-dialog v-model="focusConfirmVisible" title="确认复习起点" width="400px">
|
||||
<p v-if="selectedNodeInfo">
|
||||
<p v-if="selectedNodeInfo" class="focus-confirm-text">
|
||||
以 「<strong>{{ selectedNodeInfo.title }}</strong>」 为起点,
|
||||
复习该知识点下的 <strong>{{ selectedNodeInfo.childCount }}</strong> 个子知识点?
|
||||
</p>
|
||||
@@ -421,9 +451,9 @@ onMounted(() => {
|
||||
</div>
|
||||
|
||||
<!-- 回忆历史 -->
|
||||
<article class="surface-card" v-if="showHistory && historyRecords.length > 0">
|
||||
<article class="surface-card" v-if="showHistory">
|
||||
<h3>回忆历史</h3>
|
||||
<div class="history-list">
|
||||
<div v-if="historyRecords.length > 0" class="history-list">
|
||||
<div
|
||||
v-for="record in historyRecords"
|
||||
:key="record.id"
|
||||
@@ -437,6 +467,7 @@ onMounted(() => {
|
||||
<span class="history-detail">✅{{ record.matchedCount }} ❌{{ record.missedCount }} ➕{{ record.extraCount }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else description="暂无回忆记录" :image-size="48" />
|
||||
</article>
|
||||
|
||||
<!-- 折叠时引导:告知用户展开标准导图 -->
|
||||
@@ -478,19 +509,16 @@ onMounted(() => {
|
||||
<div class="panel-actions">
|
||||
<el-button
|
||||
v-if="hasCompared"
|
||||
size="small"
|
||||
type="success"
|
||||
@click="resetComparison"
|
||||
>
|
||||
返回完整导图
|
||||
</el-button>
|
||||
<el-button size="small" @click="standardExpanded = !standardExpanded">
|
||||
<el-button @click="standardExpanded = !standardExpanded">
|
||||
{{ standardExpanded ? "折叠" : "展开" }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="standardExpanded"
|
||||
size="small"
|
||||
type="warning"
|
||||
:loading="regenerating"
|
||||
@click="handleRegenerate"
|
||||
>
|
||||
@@ -498,7 +526,6 @@ onMounted(() => {
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="standardExpanded && !editingStandard"
|
||||
size="small"
|
||||
type="primary"
|
||||
@click="startEditStandard"
|
||||
>
|
||||
@@ -533,7 +560,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">
|
||||
点击导图节点即可选择复习起点,选好后凭记忆在上方补全知识点。
|
||||
@@ -603,18 +630,17 @@ onMounted(() => {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.page-header h2 {
|
||||
margin: 0;
|
||||
.header-spacer {
|
||||
flex: 1;
|
||||
color: var(--green-900);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.focus-confirm-text {
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
padding: 20px 22px;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-soft, #e0e0e0);
|
||||
}
|
||||
|
||||
.surface-card h3 {
|
||||
@@ -627,7 +653,7 @@ onMounted(() => {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
flex-wrap: wrap;
|
||||
background: linear-gradient(135deg, #f1f8e9 0%, #e8f5e9 100%);
|
||||
background: linear-gradient(135deg, var(--accent-success-softer) 0%, var(--accent-success-soft) 100%);
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
@@ -646,8 +672,8 @@ onMounted(() => {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.highlight { color: #2e7d32; }
|
||||
.matched { color: #2e7d32; }
|
||||
.highlight { color: var(--accent-success-strong); }
|
||||
.matched { color: var(--accent-success-strong); }
|
||||
.missed { color: #c62828; }
|
||||
.extra { color: #1565c0; }
|
||||
|
||||
@@ -680,7 +706,7 @@ onMounted(() => {
|
||||
|
||||
.ai-waiting {
|
||||
font-size: 13px;
|
||||
color: #e6a23c;
|
||||
color: var(--accent-warning);
|
||||
margin: 4px 0 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -692,7 +718,7 @@ onMounted(() => {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid #f3d19e;
|
||||
border-top-color: #e6a23c;
|
||||
border-top-color: var(--accent-warning);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
@@ -821,7 +847,7 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.history-item:hover {
|
||||
background: #f1f8e9;
|
||||
background: var(--accent-success-softer);
|
||||
}
|
||||
|
||||
.history-time {
|
||||
@@ -855,23 +881,18 @@ onMounted(() => {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.scope-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #999);
|
||||
}
|
||||
|
||||
.session-badge {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.start-guide {
|
||||
padding: 14px 22px;
|
||||
background: linear-gradient(135deg, #fff8e1 0%, #fff3cd 100%);
|
||||
background: linear-gradient(135deg, var(--accent-warning-soft) 0%, #fff3cd 100%);
|
||||
border-left: 4px solid #ffc107;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
color: #856404;
|
||||
color: var(--accent-success-text);
|
||||
}
|
||||
|
||||
.start-guide p {
|
||||
@@ -880,7 +901,7 @@ onMounted(() => {
|
||||
|
||||
.select-hint {
|
||||
font-size: 13px;
|
||||
color: #856404;
|
||||
color: var(--accent-success-text);
|
||||
margin: 0 0 8px;
|
||||
padding: 6px 12px;
|
||||
background: #fdf6ec;
|
||||
|
||||
+234
-238
@@ -5,17 +5,23 @@ 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,
|
||||
} from "@/api/studySessions";
|
||||
import { useStudyFragment } from "@/components/composables/fragment";
|
||||
import { getFragmentsBySession, updateFragments } from "@/api/reportFragments";
|
||||
import { getExpectation, getReportDraft, getTaskFragments, getTaskReports, upsertExpectation } from "@/api/studySessions";
|
||||
import router from "@/router";
|
||||
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { formatRatio } from "@/utils/format";
|
||||
import { useSessionHistory } from "@/components/composables/useSessionHistory";
|
||||
import { useSummaryReport } from "@/components/composables/useSummaryReport";
|
||||
import { useSessionExpectation } from "@/components/composables/useSessionExpectation";
|
||||
|
||||
const {
|
||||
fragmentsDialogVisible,
|
||||
@@ -23,20 +29,44 @@ const {
|
||||
openFragmentDialog,
|
||||
closeFragmentDialog,
|
||||
confirmGenerateFragment,
|
||||
creatingFragment,
|
||||
} = useStudyFragment();
|
||||
|
||||
const summaryDialogVisible = ref(false);
|
||||
const summaryContent = ref("");
|
||||
const summaryPreview = ref(false);
|
||||
const summaryLoading = ref(false);
|
||||
const summaryLoadingSeconds = ref(0);
|
||||
let summaryLoadingTimer: ReturnType<typeof setInterval> | null = null;
|
||||
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 expectationDialogVisible = ref(false);
|
||||
const expectationContent = ref("");
|
||||
const expectationSaved = ref("");
|
||||
const savingExpectation = ref(false);
|
||||
// 结束会话总结弹窗(有残片时先取 AI 草稿,等待期间展示已等待秒数)
|
||||
const {
|
||||
summaryDialogVisible,
|
||||
summaryContent,
|
||||
summaryPreview,
|
||||
summaryLoading,
|
||||
summaryLoadingSeconds,
|
||||
openSummaryDialog,
|
||||
closeSummaryDialog,
|
||||
} = useSummaryReport({
|
||||
getSessionNum: () => taskInfo.value.sessionNum,
|
||||
hasFragments: () => fragmentsList.value.length > 0,
|
||||
});
|
||||
|
||||
// 学习预期:会话必须有预期才能开始计时
|
||||
const {
|
||||
expectationDialogVisible,
|
||||
expectationContent,
|
||||
expectationSaved,
|
||||
savingExpectation,
|
||||
loadExpectation,
|
||||
saveExpectation,
|
||||
} = useSessionExpectation(() => taskInfo.value.sessionNum);
|
||||
|
||||
// 当前会话碎片列表
|
||||
interface FragmentItem {
|
||||
@@ -48,88 +78,27 @@ const editingFragmentId = ref<number | null>(null);
|
||||
const editFragmentContent = ref("");
|
||||
const savingFragment = ref(false);
|
||||
|
||||
// 历史学习记录
|
||||
const showHistory = ref(false);
|
||||
const historyTab = ref("fragments");
|
||||
const historyKeyword = ref("");
|
||||
let historyDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
const loadingHistory = ref(false);
|
||||
const historyFragments = ref<any[]>([]);
|
||||
const fragmentsTotal = ref(0);
|
||||
const fragmentsPage = ref(1);
|
||||
const historyReports = ref<any[]>([]);
|
||||
const reportsTotal = ref(0);
|
||||
const reportsPage = ref(1);
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
watch(showHistory, (val) => {
|
||||
if (val) {
|
||||
// 展开时立即加载当前 tab 的数据
|
||||
if (historyTab.value === "fragments") loadHistoryFragments();
|
||||
else loadHistoryReports();
|
||||
}
|
||||
});
|
||||
|
||||
const loadHistoryFragments = async () => {
|
||||
loadingHistory.value = true;
|
||||
try {
|
||||
const res = await getTaskFragments(taskNum, fragmentsPage.value, PAGE_SIZE, historyKeyword.value || undefined);
|
||||
const data = res?.data;
|
||||
historyFragments.value = data?.records || [];
|
||||
fragmentsTotal.value = data?.total || 0;
|
||||
} catch {
|
||||
historyFragments.value = [];
|
||||
fragmentsTotal.value = 0;
|
||||
} finally {
|
||||
loadingHistory.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadHistoryReports = async () => {
|
||||
loadingHistory.value = true;
|
||||
try {
|
||||
const res = await getTaskReports(taskNum, reportsPage.value, PAGE_SIZE, historyKeyword.value || undefined);
|
||||
const data = res?.data;
|
||||
historyReports.value = data?.records || [];
|
||||
reportsTotal.value = data?.total || 0;
|
||||
} catch {
|
||||
historyReports.value = [];
|
||||
reportsTotal.value = 0;
|
||||
} finally {
|
||||
loadingHistory.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const searchHistory = () => {
|
||||
if (historyDebounce) clearTimeout(historyDebounce);
|
||||
historyDebounce = setTimeout(() => {
|
||||
fragmentsPage.value = 1;
|
||||
reportsPage.value = 1;
|
||||
if (historyTab.value === "fragments") loadHistoryFragments();
|
||||
else loadHistoryReports();
|
||||
}, 300);
|
||||
};
|
||||
|
||||
const onHistoryTabChange = () => {
|
||||
fragmentsPage.value = 1;
|
||||
reportsPage.value = 1;
|
||||
if (historyTab.value === "fragments") loadHistoryFragments();
|
||||
else loadHistoryReports();
|
||||
};
|
||||
|
||||
const onFragmentsPageChange = (p: number) => {
|
||||
fragmentsPage.value = p;
|
||||
loadHistoryFragments();
|
||||
};
|
||||
|
||||
const onReportsPageChange = (p: number) => {
|
||||
reportsPage.value = p;
|
||||
loadHistoryReports();
|
||||
};
|
||||
|
||||
const route = useRoute();
|
||||
const taskNum = route.params.taskNum as string;
|
||||
|
||||
// 历史学习记录面板(分页查询、搜索防抖、tab 切换)
|
||||
const {
|
||||
showHistory,
|
||||
historyTab,
|
||||
historyKeyword,
|
||||
loadingHistory,
|
||||
historyFragments,
|
||||
fragmentsTotal,
|
||||
fragmentsPage,
|
||||
historyReports,
|
||||
reportsTotal,
|
||||
reportsPage,
|
||||
searchHistory,
|
||||
onHistoryTabChange,
|
||||
onFragmentsPageChange,
|
||||
onReportsPageChange,
|
||||
} = useSessionHistory(taskNum);
|
||||
|
||||
const taskInfo = ref({
|
||||
sessionNum: "",
|
||||
sessionState: "--",
|
||||
@@ -142,7 +111,7 @@ const taskInfo = ref({
|
||||
lastStartTime: "",
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: "--",
|
||||
effectivenessRatio: "-",
|
||||
pointerPosition: 0,
|
||||
systemMessage: "",
|
||||
});
|
||||
@@ -151,28 +120,7 @@ const taskInfo = ref({
|
||||
const editingMaterial = ref(false);
|
||||
const editMaterialContent = ref("");
|
||||
const savingMaterial = ref(false);
|
||||
const materialHtml = computed(() => {
|
||||
const raw = taskInfo.value.materialUrl || "";
|
||||
if (!raw.trim()) return "";
|
||||
let html = raw;
|
||||
const links: string[] = [];
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
|
||||
const tag = `<a href="${url.replace(/"/g, """)}" target="_blank" rel="noopener">${text}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!??)】」』\]]+$/, "");
|
||||
const tag = `<a href="${clean.replace(/"/g, """)}" target="_blank" rel="noopener">${clean}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/\n/g, "<br>");
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
html = html.replace(`__LINK_${i}__`, links[i]);
|
||||
}
|
||||
return html;
|
||||
});
|
||||
const materialHtml = computed(() => renderMarkdown(taskInfo.value.materialUrl || ""));
|
||||
|
||||
function startEditMaterial() {
|
||||
editMaterialContent.value = taskInfo.value.materialUrl;
|
||||
@@ -326,39 +274,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 = formatRatio(d.effectivenessRatio);
|
||||
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();
|
||||
@@ -384,6 +344,8 @@ const endTimer = async (content: string) => {
|
||||
// 用户取消结束会话,不做任何操作
|
||||
return;
|
||||
}
|
||||
if (endingSession.value) return;
|
||||
endingSession.value = true;
|
||||
|
||||
try {
|
||||
const res = await endSession(taskInfo.value.sessionNum, content);
|
||||
@@ -402,33 +364,45 @@ const endTimer = async (content: string) => {
|
||||
await router.push("/study");
|
||||
} catch {
|
||||
ElMessage.error("结束会话失败,请重试");
|
||||
} finally {
|
||||
endingSession.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openSummaryDialog = async () => {
|
||||
summaryDialogVisible.value = true;
|
||||
// 有残片且未填写过总结时,用 AI 聚合草稿作为编辑起点
|
||||
if (!summaryContent.value.trim() && fragmentsList.value.length > 0) {
|
||||
summaryLoading.value = true;
|
||||
summaryLoadingSeconds.value = 0;
|
||||
summaryLoadingTimer = setInterval(() => { summaryLoadingSeconds.value++; }, 1000);
|
||||
try {
|
||||
const res = await getReportDraft(taskInfo.value.sessionNum);
|
||||
if (res?.code === 200 && res.data) {
|
||||
summaryContent.value = res.data;
|
||||
}
|
||||
} catch {
|
||||
// 草稿失败不阻塞手写
|
||||
} finally {
|
||||
summaryLoading.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 closeSummaryDialog = () => {
|
||||
summaryDialogVisible.value = false;
|
||||
if (summaryLoadingTimer) { clearInterval(summaryLoadingTimer); summaryLoadingTimer = null; }
|
||||
};
|
||||
|
||||
const restTimer = async () => {
|
||||
@@ -454,6 +428,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();
|
||||
@@ -503,48 +498,17 @@ const loadTaskSession = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 学习预期:会话必须有预期才能开始计时
|
||||
const loadExpectation = async () => {
|
||||
if (!taskInfo.value.sessionNum) return;
|
||||
try {
|
||||
const res = await getExpectation(taskInfo.value.sessionNum);
|
||||
expectationSaved.value = res?.data?.description || "";
|
||||
} catch {
|
||||
expectationSaved.value = "";
|
||||
}
|
||||
if (!expectationSaved.value) {
|
||||
expectationDialogVisible.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const saveExpectation = async () => {
|
||||
if (!expectationContent.value.trim()) {
|
||||
ElMessage.warning("学习预期不可为空");
|
||||
return;
|
||||
}
|
||||
savingExpectation.value = true;
|
||||
try {
|
||||
const res = await upsertExpectation(taskInfo.value.sessionNum, expectationContent.value);
|
||||
if (res?.code === 200) {
|
||||
expectationSaved.value = expectationContent.value;
|
||||
expectationDialogVisible.value = false;
|
||||
} else {
|
||||
ElMessage.error(res?.message || "保存失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "请求失败");
|
||||
} finally {
|
||||
savingExpectation.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
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();
|
||||
};
|
||||
|
||||
// 碎片列表
|
||||
@@ -614,11 +578,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="已恢复上次的学习会话,继续学习吧"
|
||||
@@ -663,6 +641,7 @@ onUnmounted(() => {
|
||||
<el-button
|
||||
text
|
||||
size="small"
|
||||
type="primary"
|
||||
@click="expectationContent = expectationSaved; expectationDialogVisible = true"
|
||||
>
|
||||
修改
|
||||
@@ -721,12 +700,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>
|
||||
@@ -749,12 +729,12 @@ onUnmounted(() => {
|
||||
/>
|
||||
<div class="fragment-edit-actions">
|
||||
<el-button size="small" @click="cancelEditFragment">取消</el-button>
|
||||
<el-button size="small" type="primary" :loading="savingFragment" @click="saveEditFragment(fragment.id)">保存</el-button>
|
||||
<el-button size="small" type="success" :loading="savingFragment" @click="saveEditFragment(fragment.id)">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="fragment-content">{{ fragment.content }}</span>
|
||||
<el-button size="small" @click="startEditFragment(fragment)">编辑</el-button>
|
||||
<el-button text type="primary" size="small" @click="startEditFragment(fragment)">编辑</el-button>
|
||||
</template>
|
||||
</div>
|
||||
</article>
|
||||
@@ -807,7 +787,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>
|
||||
|
||||
@@ -827,6 +807,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>
|
||||
@@ -867,7 +848,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>
|
||||
@@ -898,7 +905,7 @@ onUnmounted(() => {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--green-700);
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
@@ -925,7 +932,7 @@ onUnmounted(() => {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--green-700);
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
@@ -962,7 +969,7 @@ onUnmounted(() => {
|
||||
|
||||
.ai-waiting {
|
||||
font-size: 13px;
|
||||
color: #e6a23c;
|
||||
color: var(--accent-warning);
|
||||
margin: 0 0 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -974,7 +981,7 @@ onUnmounted(() => {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid #f3d19e;
|
||||
border-top-color: #e6a23c;
|
||||
border-top-color: var(--accent-warning);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
@@ -1104,10 +1111,6 @@ onUnmounted(() => {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.action-row .el-button {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fragments-card {
|
||||
padding: 20px;
|
||||
}
|
||||
@@ -1165,20 +1168,12 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.top-head {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.info-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-row .el-button {
|
||||
width: 100%;
|
||||
.summary-toolbar .el-button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1244,7 +1239,7 @@ onUnmounted(() => {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
color: var(--green-700);
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
white-space: nowrap;
|
||||
@@ -1271,14 +1266,15 @@ onUnmounted(() => {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.history-content {
|
||||
flex: 1;
|
||||
.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;
|
||||
line-height: 1.6;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
text-align: center;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.report-item .history-content {
|
||||
margin: 0;
|
||||
}</style>
|
||||
</style>
|
||||
|
||||
+61
-75
@@ -4,7 +4,8 @@ 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";
|
||||
|
||||
import {
|
||||
getPriorityWeights,
|
||||
@@ -43,42 +44,14 @@ const pageSize = 20;
|
||||
const taskApplications = ref<TaskApplication[]>([]);
|
||||
const applicationsLoading = ref(false);
|
||||
const appUrlTitles = ref<Record<number, string>>({});
|
||||
|
||||
const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
|
||||
{ label: "待应用", value: "TODO" },
|
||||
{ label: "进行中", value: "DOING" },
|
||||
{ label: "已完成", value: "DONE" },
|
||||
];
|
||||
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
|
||||
);
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const escapeAttr = (s: string) => s.replace(/"/g, """).replace(/&/g, "&");
|
||||
|
||||
function renderMarkdown(raw: string): string {
|
||||
if (!raw.trim()) return "";
|
||||
let html = raw;
|
||||
const links: string[] = [];
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
|
||||
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!???)]」》]]+$/, "");
|
||||
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(clean)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/\n/g, "<br>");
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
html = html.replace(`__LINK_${i}__`, links[i]);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
const materialHtml = computed(() => renderMarkdown(selectedTask.value?.materialUrl || ""));
|
||||
|
||||
const formatEffectiveTime = (seconds: number): string => {
|
||||
@@ -134,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,
|
||||
@@ -147,6 +122,8 @@ const changeApplicationStatus = async (item: TaskApplication) => {
|
||||
if (selectedTask.value) {
|
||||
await loadTaskApplications(selectedTask.value.taskNum);
|
||||
}
|
||||
} finally {
|
||||
updatingApplicationId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -208,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 = () => {
|
||||
@@ -251,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}」?关联的学习会话、学习报告、应用场景等数据将被一并删除。`, "确认删除", {
|
||||
@@ -258,21 +219,23 @@ 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;
|
||||
}
|
||||
};
|
||||
|
||||
// ============ 优先级权重配置 ============
|
||||
const weightsDialogVisible = ref(false);
|
||||
const savingWeights = ref(false);
|
||||
const weightItems = ref([
|
||||
const weightItems = ref<{ key: keyof PriorityWeights; label: string; value: number }[]>([
|
||||
{ key: "urgencyWeight", label: "紧急性", value: 35 },
|
||||
{ key: "importanceWeight", label: "重要性", value: 25 },
|
||||
{ key: "contentDifficultyWeight", label: "内容难度", value: 20 },
|
||||
@@ -285,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;
|
||||
@@ -296,8 +261,10 @@ const openWeightsDialog = async () => {
|
||||
}
|
||||
} catch {
|
||||
// 读取失败时保持默认值
|
||||
} finally {
|
||||
weightsLoading.value = false;
|
||||
weightsDialogVisible.value = true;
|
||||
}
|
||||
weightsDialogVisible.value = true;
|
||||
};
|
||||
|
||||
const saveWeights = async () => {
|
||||
@@ -307,9 +274,11 @@ const saveWeights = async () => {
|
||||
}
|
||||
savingWeights.value = true;
|
||||
try {
|
||||
const payload = Object.fromEntries(
|
||||
weightItems.value.map((item) => [item.key, item.value / 100])
|
||||
) as unknown as PriorityWeights;
|
||||
// weightItems 的 key 已由 keyof PriorityWeights 约束,循环后必然覆盖全部维度
|
||||
const payload = {} as PriorityWeights;
|
||||
for (const item of weightItems.value) {
|
||||
payload[item.key] = item.value / 100;
|
||||
}
|
||||
const res = await savePriorityWeights(payload);
|
||||
if (res?.code === 200) {
|
||||
weightsDialogVisible.value = false;
|
||||
@@ -433,6 +402,8 @@ onMounted(() => {
|
||||
v-model="item.status"
|
||||
size="small"
|
||||
class="application-status"
|
||||
:loading="updatingApplicationId === item.id"
|
||||
:disabled="updatingApplicationId !== null"
|
||||
@change="changeApplicationStatus(item)"
|
||||
>
|
||||
<el-option
|
||||
@@ -457,12 +428,12 @@ onMounted(() => {
|
||||
|
||||
<aside class="surface-card action-card">
|
||||
<div class="block-title">常用操作</div>
|
||||
<el-button size="large" @click="fetchTasks" :loading="loading">刷新列表</el-button>
|
||||
<el-button @click="fetchTasks" :loading="loading">刷新列表</el-button>
|
||||
<el-button type="success" size="large" @click="startTask">开始任务</el-button>
|
||||
<el-button size="large" @click="addTask">添加任务</el-button>
|
||||
<el-button size="large" @click="changeTask">更新任务</el-button>
|
||||
<el-button size="large" @click="openWeightsDialog">权重配置</el-button>
|
||||
<el-button type="danger" size="large" @click="removeTask">删除任务</el-button>
|
||||
<el-button @click="addTask">添加任务</el-button>
|
||||
<el-button @click="changeTask">更新任务</el-button>
|
||||
<el-button :loading="weightsLoading" @click="openWeightsDialog">权重配置</el-button>
|
||||
<el-button type="danger" :loading="removingTask" @click="removeTask">删除任务</el-button>
|
||||
</aside>
|
||||
</main>
|
||||
</div>
|
||||
@@ -693,7 +664,7 @@ onMounted(() => {
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
@@ -701,17 +672,27 @@ onMounted(() => {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 10px 12px;
|
||||
background: var(--accent-success-softer);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 13px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 15px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.stats-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.application-list {
|
||||
@@ -791,8 +772,13 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.page-head {
|
||||
flex-direction: column;
|
||||
.weight-row {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.weight-label {
|
||||
width: 64px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.action-card {
|
||||
|
||||
+130
-115
@@ -11,6 +11,8 @@ import {
|
||||
type TaskApplication,
|
||||
} from "@/api/tasks";
|
||||
import { getUrlTitle } from "@/utils/fetchTitle";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { applicationStatusOptions } from "@/utils/taskApplication";
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
@@ -32,18 +34,17 @@ const priority = ref({
|
||||
});
|
||||
|
||||
const priorityOptions = [0, 1, 2, 3, 4, 5];
|
||||
const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
|
||||
{ label: "待应用", value: "TODO" },
|
||||
{ label: "进行中", value: "DOING" },
|
||||
{ label: "已完成", value: "DONE" },
|
||||
];
|
||||
|
||||
const applications = ref<TaskApplication[]>([]);
|
||||
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;
|
||||
@@ -138,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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -171,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 = () => {
|
||||
@@ -243,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("该功能暂不可用,请刷新后重试");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -276,44 +293,17 @@ const isMobile = computed(() => screenWidth.value <= 900);
|
||||
// 学习材料 Markdown 预览
|
||||
const showPreview = ref(false);
|
||||
const materialPreview = ref("");
|
||||
const previewLoading = ref(false);
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const escapeAttr = (s: string) => s.replace(/"/g, """).replace(/&/g, "&");
|
||||
|
||||
function renderMarkdown(raw: string, urlTitles: Record<string, string> = {}): string {
|
||||
if (!raw.trim()) return "";
|
||||
let html = raw;
|
||||
// 1) [text](url) → <a> 占位,防止后续裸 URL 匹配进属性里
|
||||
const links: string[] = [];
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
|
||||
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
// 2) 裸 URL → <a> 占位
|
||||
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!??)】」』\]]+$/, "");
|
||||
const label = urlTitles[clean] || url;
|
||||
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(label)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
// 3) 换行
|
||||
html = html.replace(/\n/g, "<br>");
|
||||
// 4) 还原占位
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
html = html.replace(`__LINK_${i}__`, links[i]);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
async function previewMaterial() {
|
||||
showPreview.value = true;
|
||||
const raw = materialUrl.value || "";
|
||||
if (!raw.trim()) { materialPreview.value = ""; return; }
|
||||
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) => {
|
||||
@@ -323,14 +313,30 @@ async function previewMaterial() {
|
||||
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>
|
||||
@@ -349,6 +355,7 @@ async function previewMaterial() {
|
||||
text
|
||||
size="small"
|
||||
type="primary"
|
||||
:loading="previewLoading"
|
||||
@click="previewMaterial()"
|
||||
>预览</el-button>
|
||||
<el-button
|
||||
@@ -375,7 +382,7 @@ async function previewMaterial() {
|
||||
<div class="group">
|
||||
<h3>优先级维度</h3>
|
||||
<div class="priority-grid" :class="{ mobile: isMobile }">
|
||||
<el-form-item label="急迫性">
|
||||
<el-form-item label="紧急性">
|
||||
<el-select v-model="priority.urgency">
|
||||
<el-option v-for="item in priorityOptions" :key="'u' + item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
@@ -405,12 +412,15 @@ async function previewMaterial() {
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<p class="priority-hint">
|
||||
五个维度取值范围均为 0–5,数值越大表示程度越高,0 表示不适用或未评估。紧急性代表时间压力,重要性代表对当前目标的权重,内容难度代表学习该内容的困难程度,未来价值代表对长期目标的价值,主观优先级是你的直觉判断。系统综合这些维度排序,更倾向「重要但不紧急」的任务,紧急性作为兜底。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="group" v-if="isUpdateMode" v-loading="applicationLoading">
|
||||
<div class="application-header">
|
||||
<h3>应用场景</h3>
|
||||
<el-button type="primary" @click="openApplicationDialog()">添加应用场景</el-button>
|
||||
<el-button type="success" @click="openApplicationDialog()">添加应用场景</el-button>
|
||||
</div>
|
||||
<div class="application-list" v-if="applications.length > 0">
|
||||
<div class="application-item" v-for="item in applications" :key="item.id">
|
||||
@@ -426,7 +436,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>
|
||||
@@ -459,7 +476,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>
|
||||
@@ -539,6 +556,13 @@ async function previewMaterial() {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.priority-hint {
|
||||
margin: 10px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.application-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -608,15 +632,6 @@ async function previewMaterial() {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-row .el-button {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.application-main {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
|
||||
+313
-153
@@ -1,65 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import router from "@/router";
|
||||
import { getReviewFeed, type ReviewFeedItem } from "@/api/review";
|
||||
import { getReviewFeed, getTaskReview, type ReviewFeedItem } from "@/api/review";
|
||||
import {
|
||||
clampAutoScrollTime,
|
||||
measureAutoScroll,
|
||||
pxToTimeOffset,
|
||||
type AutoScrollMetrics,
|
||||
} from "@/utils/autoScroll";
|
||||
|
||||
const reviewItems = ref<ReviewFeedItem[]>([]);
|
||||
const isHovering = ref(false);
|
||||
const contentRef = ref<HTMLElement | null>(null);
|
||||
const trackRef = ref<HTMLElement | null>(null);
|
||||
let autoScroll: Animation | null = null;
|
||||
let autoScrollMetrics: AutoScrollMetrics | null = null;
|
||||
/** 当前渲染的内容份数:内容比轨道窄时要多铺几份,否则循环时会露白 */
|
||||
const repeatCount = ref(2);
|
||||
|
||||
interface SessionGroup {
|
||||
interface FragmentChip {
|
||||
id: number;
|
||||
sessionNum: string;
|
||||
taskName: string;
|
||||
taskNum: string;
|
||||
content: string;
|
||||
hasReport: boolean;
|
||||
fragmentCount: number;
|
||||
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");
|
||||
// 滚动条只展示学习残片,每条残片单独作为 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 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,
|
||||
fragmentCount: fragments.length,
|
||||
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;
|
||||
});
|
||||
|
||||
// 复制一份实现无缝循环
|
||||
const duplicatedGroups = computed(() => [...sessionGroups.value, ...sessionGroups.value]);
|
||||
// 复制多份实现无缝循环,份数按轨道宽度动态补足
|
||||
const duplicatedChips = computed(() =>
|
||||
Array.from({ length: repeatCount.value }, () => fragmentChips.value).flat(),
|
||||
);
|
||||
|
||||
const loadReviewFeed = async () => {
|
||||
try {
|
||||
@@ -67,55 +52,79 @@ const loadReviewFeed = async () => {
|
||||
reviewItems.value = res?.data || [];
|
||||
} catch {
|
||||
// feed 加载失败不影响页面主体功能
|
||||
} finally {
|
||||
// 残片宽度依赖真实内容,必须等 DOM 更新后再按实际宽度重建动画
|
||||
await nextTick();
|
||||
startAutoScroll();
|
||||
}
|
||||
};
|
||||
|
||||
// 回忆卡片:点击滚动内容先尝试回忆,再看原文
|
||||
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");
|
||||
@@ -130,8 +139,137 @@ const startReview = () => {
|
||||
router.push("/review");
|
||||
};
|
||||
|
||||
/** 按当前内容宽度与轨道宽度(重新)建立动画 */
|
||||
const startAutoScroll = () => {
|
||||
const content = contentRef.value;
|
||||
const track = trackRef.value;
|
||||
if (!content || !track) return;
|
||||
|
||||
// 保留手动滚动后的位置:重建动画前把当前进度换成比例
|
||||
const elapsed = autoScroll && typeof autoScroll.currentTime === "number"
|
||||
? autoScroll.currentTime
|
||||
: 0;
|
||||
const prevDuration = autoScrollMetrics?.duration ?? 0;
|
||||
const progress = prevDuration > 0 ? elapsed / prevDuration : 0;
|
||||
autoScroll?.cancel();
|
||||
autoScroll = null;
|
||||
autoScrollMetrics = null;
|
||||
|
||||
// 渲染总宽 / 当前份数 = 单份内容的实际宽度
|
||||
const singleCopyWidth = content.scrollWidth / Math.max(repeatCount.value, 1);
|
||||
const metrics = measureAutoScroll(singleCopyWidth, track.clientWidth);
|
||||
if (!metrics) return;
|
||||
|
||||
// 份数不足时先补足再重新测量,下一轮才是准确的循环宽度
|
||||
if (metrics.repeatCount !== repeatCount.value) {
|
||||
repeatCount.value = metrics.repeatCount;
|
||||
nextTick(() => startAutoScroll());
|
||||
return;
|
||||
}
|
||||
|
||||
autoScrollMetrics = metrics;
|
||||
const anim = content.animate(
|
||||
[
|
||||
{ transform: "translateX(0)" },
|
||||
{ transform: `translateX(-${100 / repeatCount.value}%)` },
|
||||
],
|
||||
{ duration: metrics.duration, iterations: Infinity, easing: "linear" },
|
||||
);
|
||||
anim.currentTime = progress * metrics.duration;
|
||||
autoScroll = anim;
|
||||
};
|
||||
|
||||
/** 滚轮与手指拖动共用的手动位移 */
|
||||
const scrollByPixels = (deltaPx: number) => {
|
||||
const anim = autoScroll;
|
||||
const metrics = autoScrollMetrics;
|
||||
if (!anim || !metrics) return;
|
||||
const current = anim.currentTime;
|
||||
if (typeof current !== "number") return;
|
||||
anim.currentTime = clampAutoScrollTime(
|
||||
current + pxToTimeOffset(deltaPx, metrics.speed),
|
||||
metrics.duration,
|
||||
);
|
||||
};
|
||||
|
||||
const handleTrackWheel = (event: WheelEvent) => {
|
||||
if (!autoScrollMetrics) return;
|
||||
autoScroll?.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;
|
||||
scrollByPixels(delta);
|
||||
};
|
||||
|
||||
let touchLastX = 0;
|
||||
let touchMovedDistance = 0;
|
||||
const TOUCH_TAP_THRESHOLD = 6;
|
||||
|
||||
const handleTouchStart = (event: TouchEvent) => {
|
||||
if (!autoScrollMetrics) return;
|
||||
const touch = event.touches[0];
|
||||
if (!touch) return;
|
||||
touchLastX = touch.clientX;
|
||||
touchMovedDistance = 0;
|
||||
autoScroll?.pause();
|
||||
};
|
||||
|
||||
const handleTouchMove = (event: TouchEvent) => {
|
||||
if (!autoScrollMetrics) return;
|
||||
const touch = event.touches[0];
|
||||
if (!touch) return;
|
||||
const deltaX = touch.clientX - touchLastX;
|
||||
touchLastX = touch.clientX;
|
||||
touchMovedDistance += Math.abs(deltaX);
|
||||
if (!deltaX) return;
|
||||
scrollByPixels(deltaX);
|
||||
};
|
||||
|
||||
const handleTouchEnd = () => {
|
||||
autoScroll?.play();
|
||||
};
|
||||
|
||||
/** 拖动过就吞掉这次 click,避免误触打开回忆卡片 */
|
||||
const handleChipClick = (fragment: FragmentChip, event: MouseEvent) => {
|
||||
if (touchMovedDistance > TOUCH_TAP_THRESHOLD) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
touchMovedDistance = 0;
|
||||
return;
|
||||
}
|
||||
touchMovedDistance = 0;
|
||||
openRecallCard(fragment);
|
||||
};
|
||||
|
||||
/** 视口跨过断点时速度会变,需重新测量时长并保持当前进度 */
|
||||
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const handleViewportResize = () => {
|
||||
if (resizeTimer) clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(() => {
|
||||
resizeTimer = null;
|
||||
startAutoScroll();
|
||||
}, 150);
|
||||
};
|
||||
|
||||
const pauseAutoScroll = () => {
|
||||
autoScroll?.pause();
|
||||
};
|
||||
|
||||
const resumeAutoScroll = () => {
|
||||
autoScroll?.play();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadReviewFeed();
|
||||
window.addEventListener("resize", handleViewportResize);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
autoScroll?.cancel();
|
||||
autoScroll = null;
|
||||
window.removeEventListener("resize", handleViewportResize);
|
||||
if (resizeTimer) clearTimeout(resizeTimer);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -140,27 +278,40 @@ onMounted(() => {
|
||||
<section class="welcome-page">
|
||||
<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>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="left"
|
||||
:show-after="200"
|
||||
content="学习残片(知识碎片)是学习过程中随手记下的不完整内容,不要求是完整总结,只记录刚学到、想到或需要记住的内容。它是学习记录的主要单元,后续由你或 AI 汇总为学习报告与思维导图。"
|
||||
>
|
||||
<span class="color-legend" tabindex="0">
|
||||
<span class="dot dot-fragment"></span> 学习残片
|
||||
</span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
<div class="review-scroll-track">
|
||||
<div
|
||||
ref="trackRef"
|
||||
class="review-scroll-track"
|
||||
@mouseenter="pauseAutoScroll"
|
||||
@mouseleave="resumeAutoScroll"
|
||||
@wheel.prevent="handleTrackWheel"
|
||||
@touchstart.passive="handleTouchStart"
|
||||
@touchmove.passive="handleTouchMove"
|
||||
@touchend="handleTouchEnd"
|
||||
@touchcancel="handleTouchEnd"
|
||||
>
|
||||
<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="handleChipClick(chip, $event)"
|
||||
>
|
||||
<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>
|
||||
@@ -193,35 +344,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" @click="revealRecallContent">
|
||||
回忆好了,展开对照
|
||||
<el-button
|
||||
v-if="!recallCard.revealed"
|
||||
type="success"
|
||||
plain
|
||||
:loading="recallCard.loadingSession"
|
||||
@click="revealRecallContent"
|
||||
>
|
||||
展开对照
|
||||
</el-button>
|
||||
<el-button v-else type="success" @click="openRecallDetail">进入详情页</el-button>
|
||||
<el-button type="success" plain @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>
|
||||
@@ -288,6 +457,8 @@ onMounted(() => {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
cursor: help;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.dot {
|
||||
@@ -298,16 +469,14 @@ onMounted(() => {
|
||||
margin-right: 3px;
|
||||
}
|
||||
|
||||
.dot-report {
|
||||
background: var(--green-600);
|
||||
}
|
||||
|
||||
.dot-fragment {
|
||||
background: #e6a23c;
|
||||
background: var(--accent-warning);
|
||||
}
|
||||
|
||||
.review-scroll-track {
|
||||
overflow: hidden;
|
||||
/* 限制横向手势交给脚本处理,避免拖动时页面跟着晃 */
|
||||
touch-action: pan-y;
|
||||
mask-image: linear-gradient(to right, transparent, black 3%, black 97%, transparent);
|
||||
-webkit-mask-image: linear-gradient(to right, transparent, black 3%, black 97%, transparent);
|
||||
}
|
||||
@@ -316,20 +485,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 {
|
||||
@@ -339,7 +494,6 @@ onMounted(() => {
|
||||
padding: 8px 16px;
|
||||
background: var(--surface-strong);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-left: 3px solid transparent;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, box-shadow 0.2s;
|
||||
@@ -347,24 +501,9 @@ 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;
|
||||
background: var(--accent-success-softer);
|
||||
}
|
||||
|
||||
.chip-task {
|
||||
@@ -393,7 +532,7 @@ onMounted(() => {
|
||||
margin: 0 0 14px;
|
||||
padding: 12px 16px;
|
||||
border-left: 3px solid var(--green-600);
|
||||
background: #f1f8e9;
|
||||
background: var(--accent-success-softer);
|
||||
border-radius: 0 6px 6px 0;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
@@ -402,6 +541,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;
|
||||
@@ -420,6 +565,11 @@ onMounted(() => {
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.recall-full-item.is-clicked {
|
||||
background: var(--accent-warning-soft);
|
||||
border-color: var(--accent-warning);
|
||||
}
|
||||
|
||||
.recall-item-tag {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
@@ -429,13 +579,13 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
.tag-report {
|
||||
background: #e8f5e9;
|
||||
background: var(--accent-success-soft);
|
||||
color: var(--green-700);
|
||||
}
|
||||
|
||||
.tag-fragment {
|
||||
background: #fff8e1;
|
||||
color: #b8860b;
|
||||
background: var(--accent-warning-soft);
|
||||
color: var(--accent-warning-strong);
|
||||
}
|
||||
|
||||
.recall-item-content {
|
||||
@@ -456,4 +606,14 @@ onMounted(() => {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.recall-card-dialog :deep(.el-dialog__footer) {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.recall-card-dialog :deep(.el-dialog__footer .el-button) {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// src/components/composables/useElapsedSeconds.ts
|
||||
import { getCurrentInstance, onUnmounted, ref } from 'vue';
|
||||
|
||||
/**
|
||||
* 统一的秒表计时:记录异步操作已耗时秒数,用于“已等待 N 秒”等界面提示。
|
||||
* - start():归零并开始每秒递增(重复调用会先停止上一次计时)
|
||||
* - stop():停止计时,保留当前秒数
|
||||
* - reset():停止并归零
|
||||
* 组件卸载时自动清理定时器;在组件外部调用仅作纯状态机使用。
|
||||
*/
|
||||
export function useElapsedSeconds() {
|
||||
const seconds = ref(0);
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const stop = () => {
|
||||
if (timer) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
stop();
|
||||
seconds.value = 0;
|
||||
timer = setInterval(() => {
|
||||
seconds.value++;
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
stop();
|
||||
seconds.value = 0;
|
||||
};
|
||||
|
||||
if (getCurrentInstance()) {
|
||||
onUnmounted(stop);
|
||||
}
|
||||
|
||||
return { seconds, start, stop, reset };
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ref } from 'vue';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { getExpectation, upsertExpectation } from '@/api/studySessions';
|
||||
|
||||
/**
|
||||
* 学习会话的学习预期:会话必须有预期才能开始计时。
|
||||
* - loadExpectation:读取已保存预期,无预期时自动弹出填写弹窗
|
||||
* - saveExpectation:保存预期并关闭弹窗
|
||||
*/
|
||||
export function useSessionExpectation(getSessionNum: () => string) {
|
||||
const expectationDialogVisible = ref(false);
|
||||
const expectationContent = ref("");
|
||||
const expectationSaved = ref("");
|
||||
const savingExpectation = ref(false);
|
||||
|
||||
const loadExpectation = async () => {
|
||||
if (!getSessionNum()) return;
|
||||
try {
|
||||
const res = await getExpectation(getSessionNum());
|
||||
expectationSaved.value = res?.data?.description || "";
|
||||
} catch {
|
||||
expectationSaved.value = "";
|
||||
}
|
||||
if (!expectationSaved.value) {
|
||||
expectationDialogVisible.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const saveExpectation = async () => {
|
||||
if (!expectationContent.value.trim()) {
|
||||
ElMessage.warning("学习预期不可为空");
|
||||
return;
|
||||
}
|
||||
savingExpectation.value = true;
|
||||
try {
|
||||
const res = await upsertExpectation(getSessionNum(), expectationContent.value);
|
||||
if (res?.code === 200) {
|
||||
expectationSaved.value = expectationContent.value;
|
||||
expectationDialogVisible.value = false;
|
||||
} else {
|
||||
ElMessage.error(res?.message || "保存失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "请求失败");
|
||||
} finally {
|
||||
savingExpectation.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
expectationDialogVisible,
|
||||
expectationContent,
|
||||
expectationSaved,
|
||||
savingExpectation,
|
||||
loadExpectation,
|
||||
saveExpectation,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { ref, watch } from 'vue';
|
||||
import { getTaskFragments, getTaskReports } from '@/api/studySessions';
|
||||
|
||||
/** 历史残片 / 历史报告共用的列表项形状(模板只消费这些字段) */
|
||||
export interface SessionHistoryRecord {
|
||||
id: number;
|
||||
sessionNum: string;
|
||||
content: string;
|
||||
sessionExpectation?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 学习会话页的“历史学习记录”面板:按任务分页查询历史残片与报告,
|
||||
* 支持关键字搜索(300ms 防抖)与 tab 切换。
|
||||
*/
|
||||
export function useSessionHistory(taskNum: string) {
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
const showHistory = ref(false);
|
||||
const historyTab = ref("fragments");
|
||||
const historyKeyword = ref("");
|
||||
let historyDebounce: ReturnType<typeof setTimeout> | null = null;
|
||||
const loadingHistory = ref(false);
|
||||
const historyFragments = ref<SessionHistoryRecord[]>([]);
|
||||
const fragmentsTotal = ref(0);
|
||||
const fragmentsPage = ref(1);
|
||||
const historyReports = ref<SessionHistoryRecord[]>([]);
|
||||
const reportsTotal = ref(0);
|
||||
const reportsPage = ref(1);
|
||||
|
||||
watch(showHistory, (val) => {
|
||||
if (val) {
|
||||
// 展开时立即加载当前 tab 的数据
|
||||
if (historyTab.value === "fragments") loadHistoryFragments();
|
||||
else loadHistoryReports();
|
||||
}
|
||||
});
|
||||
|
||||
const loadHistoryFragments = async () => {
|
||||
loadingHistory.value = true;
|
||||
try {
|
||||
const res = await getTaskFragments(taskNum, fragmentsPage.value, PAGE_SIZE, historyKeyword.value || undefined);
|
||||
const data = res?.data;
|
||||
historyFragments.value = data?.records || [];
|
||||
fragmentsTotal.value = data?.total || 0;
|
||||
} catch {
|
||||
historyFragments.value = [];
|
||||
fragmentsTotal.value = 0;
|
||||
} finally {
|
||||
loadingHistory.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadHistoryReports = async () => {
|
||||
loadingHistory.value = true;
|
||||
try {
|
||||
const res = await getTaskReports(taskNum, reportsPage.value, PAGE_SIZE, historyKeyword.value || undefined);
|
||||
const data = res?.data;
|
||||
historyReports.value = data?.records || [];
|
||||
reportsTotal.value = data?.total || 0;
|
||||
} catch {
|
||||
historyReports.value = [];
|
||||
reportsTotal.value = 0;
|
||||
} finally {
|
||||
loadingHistory.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const searchHistory = () => {
|
||||
if (historyDebounce) clearTimeout(historyDebounce);
|
||||
historyDebounce = setTimeout(() => {
|
||||
fragmentsPage.value = 1;
|
||||
reportsPage.value = 1;
|
||||
if (historyTab.value === "fragments") loadHistoryFragments();
|
||||
else loadHistoryReports();
|
||||
}, 300);
|
||||
};
|
||||
|
||||
const onHistoryTabChange = () => {
|
||||
fragmentsPage.value = 1;
|
||||
reportsPage.value = 1;
|
||||
if (historyTab.value === "fragments") loadHistoryFragments();
|
||||
else loadHistoryReports();
|
||||
};
|
||||
|
||||
const onFragmentsPageChange = (p: number) => {
|
||||
fragmentsPage.value = p;
|
||||
loadHistoryFragments();
|
||||
};
|
||||
|
||||
const onReportsPageChange = (p: number) => {
|
||||
reportsPage.value = p;
|
||||
loadHistoryReports();
|
||||
};
|
||||
|
||||
return {
|
||||
PAGE_SIZE,
|
||||
showHistory,
|
||||
historyTab,
|
||||
historyKeyword,
|
||||
loadingHistory,
|
||||
historyFragments,
|
||||
fragmentsTotal,
|
||||
fragmentsPage,
|
||||
historyReports,
|
||||
reportsTotal,
|
||||
reportsPage,
|
||||
searchHistory,
|
||||
onHistoryTabChange,
|
||||
onFragmentsPageChange,
|
||||
onReportsPageChange,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ref } from 'vue';
|
||||
import { getReportDraft } from '@/api/studySessions';
|
||||
import { useElapsedSeconds } from './useElapsedSeconds';
|
||||
|
||||
/**
|
||||
* “结束会话总结”弹窗:编辑/预览总结内容。
|
||||
* 有学习残片且尚未填写内容时,先取 AI 聚合草稿作为编辑起点(失败不阻塞手写),
|
||||
* 等待期间展示“已等待 N 秒”提示。
|
||||
*/
|
||||
export function useSummaryReport(options: {
|
||||
getSessionNum: () => string;
|
||||
hasFragments: () => boolean;
|
||||
}) {
|
||||
const summaryDialogVisible = ref(false);
|
||||
const summaryContent = ref("");
|
||||
const summaryPreview = ref(false);
|
||||
const summaryLoading = ref(false);
|
||||
const { seconds: summaryLoadingSeconds, start: startLoadingTimer, stop: stopLoadingTimer } = useElapsedSeconds();
|
||||
|
||||
const openSummaryDialog = async () => {
|
||||
summaryDialogVisible.value = true;
|
||||
// 有残片且未填写过总结时,用 AI 聚合草稿作为编辑起点
|
||||
if (!summaryContent.value.trim() && options.hasFragments()) {
|
||||
summaryLoading.value = true;
|
||||
startLoadingTimer();
|
||||
try {
|
||||
const res = await getReportDraft(options.getSessionNum());
|
||||
if (res?.code === 200 && res.data) {
|
||||
summaryContent.value = res.data;
|
||||
}
|
||||
} catch {
|
||||
// 草稿失败不阻塞手写
|
||||
} finally {
|
||||
summaryLoading.value = false;
|
||||
stopLoadingTimer();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const closeSummaryDialog = () => {
|
||||
summaryDialogVisible.value = false;
|
||||
stopLoadingTimer();
|
||||
};
|
||||
|
||||
return {
|
||||
summaryDialogVisible,
|
||||
summaryContent,
|
||||
summaryPreview,
|
||||
summaryLoading,
|
||||
summaryLoadingSeconds,
|
||||
openSummaryDialog,
|
||||
closeSummaryDialog,
|
||||
};
|
||||
}
|
||||
@@ -8,7 +8,6 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
const remainingTime = ref(25 * 60 * 1000);
|
||||
const timerRunning = ref(false);
|
||||
const timerIsOver = ref(false);
|
||||
const audioActivated = ref(false);
|
||||
|
||||
let timerInterval: number;
|
||||
const audio = new Audio(audioUrl);
|
||||
@@ -65,10 +64,8 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
await audio.play();
|
||||
audio.pause();
|
||||
audio.currentTime = 0;
|
||||
audioActivated.value = true;
|
||||
return true;
|
||||
} catch {
|
||||
audioActivated.value = false;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -82,7 +79,6 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
await audio.play();
|
||||
audio.pause();
|
||||
audio.currentTime = 0;
|
||||
audioActivated.value = true;
|
||||
resolve(true);
|
||||
} catch {
|
||||
resolve(false);
|
||||
@@ -95,7 +91,6 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
return {
|
||||
timerMinutes,
|
||||
timerSeconds,
|
||||
remainingTime,
|
||||
timerRunning,
|
||||
timerIsOver,
|
||||
runCountdown,
|
||||
@@ -103,6 +98,5 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
clear,
|
||||
checkAudioPermission,
|
||||
requestAudioPermission,
|
||||
audioActivated,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -1,7 +0,0 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
|
||||
<path
|
||||
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -1,7 +0,0 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -1,7 +0,0 @@
|
||||
<template>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
|
||||
<path
|
||||
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -1,19 +0,0 @@
|
||||
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
|
||||
<template>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
aria-hidden="true"
|
||||
role="img"
|
||||
class="iconify iconify--mdi"
|
||||
width="24"
|
||||
height="24"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
|
||||
fill="currentColor"
|
||||
></path>
|
||||
</svg>
|
||||
</template>
|
||||
+5
-4
@@ -1,13 +1,14 @@
|
||||
import './assets/main.css'
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import 'normalize.css'
|
||||
// 必须在 EP 样式之后:同特异度下靠加载顺序覆盖 EP 主题变量
|
||||
import './assets/main.css'
|
||||
|
||||
import App from './App.vue'
|
||||
import router from "@/router"
|
||||
import 'normalize.css'
|
||||
|
||||
var app = createApp(App)
|
||||
const app = createApp(App)
|
||||
app.use(ElementPlus)
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
|
||||
+15
-2
@@ -27,10 +27,21 @@ 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: "复习详情", backTo: "/review", backLabel: "返回总览" },
|
||||
},
|
||||
{
|
||||
path: "/review/detail/:type/:id",
|
||||
component: () => import("@/components/ReviewDetail.vue"),
|
||||
meta: { requiresAuth: true, title: "复习详情" },
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
title: "复习详情",
|
||||
backTo: "/review",
|
||||
backLabel: "返回上一页",
|
||||
backUseHistory: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "/review/recall/:taskNum",
|
||||
@@ -98,7 +109,9 @@ router.beforeEach((to) => {
|
||||
if (taskNum) {
|
||||
return `/start-task/${encodeURIComponent(taskNum)}?resume=true`;
|
||||
}
|
||||
} catch {}
|
||||
} catch {
|
||||
// activeSession 内容异常时不恢复会话
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 无缝横向跑马灯的恒速换算。
|
||||
*
|
||||
* 滚动内容复制多份,动画从 translateX(0) 走到 translateX(-100%/份数),
|
||||
* 因此一"轮"的距离就是单份内容的宽度。
|
||||
*
|
||||
* 速度恒定(与内容量无关):同样的 px/s 在任何数据量、任何环境下观感一致;
|
||||
* 上下限只作为安全边界,避免以后有人把基准值改坏导致完全不可用。
|
||||
*
|
||||
* 说明:内容不足一屏时仍然滚动——轨道右侧有渐变遮罩,不滚动就看不到后面的内容。
|
||||
*/
|
||||
|
||||
/** 桌面基准速度:60px/s,一屏 1000px 内容约 17 秒走完 */
|
||||
export const BASE_SPEED_PX_PER_SEC = 60;
|
||||
|
||||
/** 桌面基准速度的安全上限:内容再怪也不超过这个速度 */
|
||||
export const MAX_SPEED_PX_PER_SEC = 85;
|
||||
|
||||
/** 桌面基准速度的安全下限:再慢也不会显得像卡住了 */
|
||||
export const MIN_SPEED_PX_PER_SEC = 45;
|
||||
|
||||
/** 窄屏(手机)相对桌面的速度系数:视口窄,同 px/s 的视觉速度更快 */
|
||||
export const NARROW_SPEED_FACTOR = 0.6;
|
||||
|
||||
/** 移动端断点,与仓库样式约定保持一致 */
|
||||
export const NARROW_MAX_WIDTH = 768;
|
||||
|
||||
/** 最少复制份数:一份用于展示,一份用于无缝衔接 */
|
||||
export const MIN_REPEAT_COUNT = 2;
|
||||
|
||||
/** 复制份数上限,避免内容异常时渲染过多节点 */
|
||||
export const MAX_REPEAT_COUNT = 24;
|
||||
|
||||
export interface AutoScrollMetrics {
|
||||
/** 一轮滚动距离(px),即单份内容的宽度 */
|
||||
loopWidth: number;
|
||||
/** 轨道可视宽度(px) */
|
||||
viewportWidth: number;
|
||||
/** 实际使用速度(px/s) */
|
||||
speed: number;
|
||||
/** 一轮动画时长(ms) */
|
||||
duration: number;
|
||||
/** 需要渲染的内容份数 */
|
||||
repeatCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按视口宽度取速度(px/s)。
|
||||
* 上下限只约束桌面基准速度(防止基准值被改坏),移动端系数在其后生效,
|
||||
* 这样手机端才是真正的桌面 0.6 倍。
|
||||
*/
|
||||
export function getScrollSpeedPxPerSec(viewportWidth: number): number {
|
||||
const baseSpeed = Math.min(Math.max(BASE_SPEED_PX_PER_SEC, MIN_SPEED_PX_PER_SEC), MAX_SPEED_PX_PER_SEC);
|
||||
const isNarrow = viewportWidth > 0 && viewportWidth <= NARROW_MAX_WIDTH;
|
||||
return baseSpeed * (isNarrow ? NARROW_SPEED_FACTOR : 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 需要渲染多少份内容。
|
||||
* 动画把内容向前推一份的宽度,若总宽不够,循环后半段轨道右侧会露白,
|
||||
* 所以至少要能铺满「可视宽度 + 无缝衔接的那一份」。
|
||||
*/
|
||||
export function getRepeatCount(singleCopyWidth: number, viewportWidth: number): number {
|
||||
if (!Number.isFinite(singleCopyWidth) || singleCopyWidth <= 0) return MIN_REPEAT_COUNT;
|
||||
if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) return MIN_REPEAT_COUNT;
|
||||
const needed = Math.ceil(viewportWidth / singleCopyWidth) + 1;
|
||||
return Math.min(Math.max(needed, MIN_REPEAT_COUNT), MAX_REPEAT_COUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算一轮滚动的距离、速度与时长。
|
||||
* `singleCopyWidth` 是单份内容宽度(调用方按实际用量总宽折算)。
|
||||
* 无法计算时返回 null,调用方据此不启动动画。
|
||||
*/
|
||||
export function measureAutoScroll(
|
||||
singleCopyWidth: number,
|
||||
viewportWidth: number,
|
||||
): AutoScrollMetrics | null {
|
||||
const speed = getScrollSpeedPxPerSec(viewportWidth);
|
||||
if (!Number.isFinite(singleCopyWidth) || singleCopyWidth <= 0) return null;
|
||||
if (!Number.isFinite(speed) || speed <= 0) return null;
|
||||
return {
|
||||
loopWidth: singleCopyWidth,
|
||||
viewportWidth,
|
||||
speed,
|
||||
duration: (singleCopyWidth / speed) * 1000,
|
||||
repeatCount: getRepeatCount(singleCopyWidth, viewportWidth),
|
||||
};
|
||||
}
|
||||
|
||||
/** 把位移(px)换算成动画时间(ms),滚轮与手指拖动共用同一套换算 */
|
||||
export function pxToTimeOffset(deltaPx: number, speed: number): number {
|
||||
if (!Number.isFinite(deltaPx) || !Number.isFinite(speed) || speed <= 0) return 0;
|
||||
return (deltaPx / speed) * 1000;
|
||||
}
|
||||
|
||||
/** 把动画时间夹在 [0, duration] 内,配合 iterations: Infinity 保持循环连续 */
|
||||
export function clampAutoScrollTime(time: number, duration: number): number {
|
||||
if (!Number.isFinite(time)) return 0;
|
||||
if (!Number.isFinite(duration) || duration <= 0) return 0;
|
||||
return Math.min(Math.max(time, 0), duration);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 把 0~1 的比率格式化为百分比文案。
|
||||
* 后端可能返回数字或字符串,空值与非法值统一显示 "-"。
|
||||
*/
|
||||
export const formatRatio = (ratio?: number | string | null): string => {
|
||||
if (ratio == null || ratio === "") return "-";
|
||||
const value = Number(ratio);
|
||||
if (Number.isNaN(value)) return "-";
|
||||
return `${(value * 100).toFixed(1)}%`;
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
export const escapeHtml = (s: string) =>
|
||||
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
export const escapeAttr = (s: string) => s.replace(/"/g, """).replace(/&/g, "&");
|
||||
|
||||
export function renderMarkdown(raw: string, urlTitles: Record<string, string> = {}): string {
|
||||
if (!raw.trim()) return "";
|
||||
let html = raw;
|
||||
const links: string[] = [];
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
|
||||
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!??)】」』\]]+$/, "");
|
||||
const label = urlTitles[clean] || clean;
|
||||
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(label)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/\n/g, "<br>");
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
html = html.replace(`__LINK_${i}__`, links[i]);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
+49
-39
@@ -2,11 +2,21 @@ import axios from 'axios';
|
||||
import { ElMessage } from "element-plus";
|
||||
import router from "@/router";
|
||||
|
||||
const basic_url = import.meta.env.VITE_BASE_URL;
|
||||
/** 后端统一响应包装:code === 200 表示业务成功 */
|
||||
export interface ApiResponse<T = any> {
|
||||
code: number;
|
||||
message?: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
const baseURL = import.meta.env.VITE_BASE_URL;
|
||||
|
||||
// 默认 30s:普通 CRUD 足够;AI 聚合等长耗时接口需在 api 层显式覆写 timeout
|
||||
const DEFAULT_TIMEOUT = 30_000;
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: basic_url,
|
||||
timeout: 600000,
|
||||
baseURL,
|
||||
timeout: DEFAULT_TIMEOUT,
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
@@ -32,14 +42,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) => {
|
||||
@@ -51,45 +61,45 @@ const validateResponse = (res: any) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
function get(url: string, params: Record<string, any>): Promise<any>;
|
||||
function get(url: string): Promise<any>;
|
||||
|
||||
function get(url: string, params: Record<string, any> = {}) {
|
||||
return axiosInstance.get(url, { params })
|
||||
const get = <T = any>(
|
||||
url: string,
|
||||
params: Record<string, any> = {},
|
||||
config: Record<string, any> = {},
|
||||
): Promise<ApiResponse<T>> =>
|
||||
axiosInstance.get(url, { params, ...config })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
}
|
||||
|
||||
const post = (url: string, data: any = null, config: any = {}) => {
|
||||
|
||||
if (config.params) {
|
||||
// 如果传入 config.params,则作为 URL 参数
|
||||
return axiosInstance.post(url, data, { params: config.params, ...config })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
} else {
|
||||
// 默认 POST JSON
|
||||
return axiosInstance.post(url, data, config)
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
}
|
||||
};
|
||||
|
||||
const put = (url: string, data: any, config: any = {}) => {
|
||||
return axiosInstance.put(url, data, config)
|
||||
const post = <T = any>(
|
||||
url: string,
|
||||
data: any = null,
|
||||
config: Record<string, any> = {},
|
||||
): Promise<ApiResponse<T>> =>
|
||||
axiosInstance.post(url, data, config)
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
};
|
||||
|
||||
const del = (url: string, params: Record<string, any> = {}, config: any = {}) => {
|
||||
return axiosInstance.delete(url, { params, ...config })
|
||||
const put = <T = any>(
|
||||
url: string,
|
||||
data: any,
|
||||
config: Record<string, any> = {},
|
||||
): Promise<ApiResponse<T>> =>
|
||||
axiosInstance.put(url, data, config)
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
};
|
||||
|
||||
const requestNotImplemented = (method: string) => {
|
||||
ElMessage.error(`请求方法 ${method} 未实现`);
|
||||
throw new Error(`请求方法 ${method} 未实现`);
|
||||
const del = <T = any>(
|
||||
url: string,
|
||||
params: Record<string, any> = {},
|
||||
config: Record<string, any> = {},
|
||||
): Promise<ApiResponse<T>> =>
|
||||
axiosInstance.delete(url, { params, ...config })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
|
||||
const requestNotImplemented = () => {
|
||||
ElMessage.error("该功能暂不可用,请刷新后重试");
|
||||
throw new Error("该功能暂不可用,请刷新后重试");
|
||||
};
|
||||
|
||||
const request = (method: string, url: string, paramsOrData: any) => {
|
||||
@@ -98,7 +108,7 @@ const request = (method: string, url: string, paramsOrData: any) => {
|
||||
case 'post': return post(url, paramsOrData);
|
||||
case 'put': return put(url, paramsOrData);
|
||||
case 'delete': return del(url, paramsOrData);
|
||||
default: return requestNotImplemented(method);
|
||||
default: return requestNotImplemented();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { TaskApplication } from "@/api/tasks";
|
||||
|
||||
export const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
|
||||
{ label: "待应用", value: "TODO" },
|
||||
{ label: "进行中", value: "DOING" },
|
||||
{ label: "已完成", value: "DONE" },
|
||||
];
|
||||
@@ -29,5 +29,19 @@ export default defineConfig({
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./src/__tests__/setup.ts'],
|
||||
include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'html'],
|
||||
reportsDirectory: 'coverage',
|
||||
include: ['src/**'],
|
||||
exclude: ['src/__tests__/**', 'src/main.ts', 'src/env.d.ts'],
|
||||
thresholds: {
|
||||
// 棘轮基线(2026-08 首次接入实测:lines 62.4 / funcs 47.7 / stmts 62.4 / branches 73.5),只升不降
|
||||
lines: 60,
|
||||
functions: 45,
|
||||
statements: 60,
|
||||
branches: 72,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user