Compare commits
132
Commits
task-1
..
fe45ec0f76
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
a87fdba4cc | ||
|
|
a43267db73 | ||
|
|
9af479d833 | ||
|
|
a00e576516 | ||
|
|
02ce825c53 | ||
|
|
68082afc78 | ||
|
|
e446cde225 | ||
|
|
d1210db1a7 | ||
|
|
68d5ca119a | ||
|
|
4bda9d6ba2 | ||
|
|
0a82bac723 | ||
|
|
1efc7581e6 | ||
|
|
29b879b274 | ||
|
|
ec05269806 | ||
|
|
ff8d4fefe2 | ||
|
|
835ebafc21 | ||
|
|
02cccbd94b | ||
|
|
bc5880ec31 | ||
|
|
38ab924b91 | ||
|
|
021cb81125 | ||
|
|
ec157b06dc | ||
|
|
bc707179ce | ||
|
|
e1faacf7a7 | ||
|
|
2a24c16244 | ||
|
|
9c49e21575 | ||
|
|
f712fa9e85 | ||
|
|
88747cbd48 | ||
|
|
131e25c154 | ||
|
|
e44301e1d5 | ||
|
|
c08c247271 | ||
|
|
2315c0d08f | ||
|
|
032317da7b | ||
|
|
9c3c1f0d26 | ||
|
|
6accec1b2a | ||
|
|
73d0572dfc | ||
|
|
a81f83f27c | ||
|
|
39bf6b7426 | ||
|
|
a67d092805 | ||
|
|
52b59019d0 | ||
|
|
59dea6f84c | ||
|
|
e65b800e01 | ||
|
|
1ea15db504 | ||
|
|
e66bdb79dc | ||
|
|
ebbbeb4c85 | ||
|
|
84fe452e80 | ||
|
|
5a5a294f06 | ||
|
|
e5adb4095b | ||
|
|
62e12686e3 | ||
|
|
c41aa09b4a | ||
|
|
ea9b7ec569 | ||
|
|
85bee1d311 | ||
|
|
88a3521f27 | ||
|
|
b7387e02c4 | ||
|
|
5986b3996b | ||
|
|
a63942d105 | ||
|
|
5f7a5a55a4 | ||
|
|
f0a6b16185 | ||
|
|
9c2c1b7614 | ||
|
|
89d186c82e | ||
|
|
a485d33933 | ||
|
|
4e1c71e4d5 | ||
|
|
a259e0ac1a | ||
|
|
fa3ecd50ed | ||
|
|
ae796308a6 | ||
|
|
cd68811dfb | ||
|
|
3adbeb183c | ||
|
|
104ae78a2b | ||
|
|
8e75a7d2e4 | ||
|
|
d9e5d1ef3a | ||
|
|
7fef9e2bb2 | ||
|
|
5616399108 | ||
|
|
6346120805 | ||
|
|
b24483b03b | ||
|
|
dc7469ec3f | ||
|
|
8ed1d45ae1 | ||
|
|
45ac0a98d1 | ||
|
|
1827093a9f | ||
|
|
7878242596 | ||
|
|
000b1aa9f4 | ||
|
|
0be2b1c26e | ||
|
|
7a55063174 | ||
|
|
15eea25598 | ||
|
|
0a71a42056 | ||
|
|
1f44da3c6c | ||
|
|
97981d5401 | ||
|
|
887756f4ff | ||
|
|
a82c25b45c | ||
|
|
0f1a2d8bba | ||
|
|
439a530978 | ||
|
|
a6ac089e15 | ||
|
|
52dbc51749 | ||
|
|
c1f00378f2 | ||
|
|
29db5a4c30 | ||
|
|
43d3dbde2c | ||
|
|
2da736aaf3 | ||
|
|
e0f5055740 | ||
|
|
b8a4f1e981 | ||
|
|
aa5e5a654f | ||
|
|
88ec132579 | ||
|
|
13846a0b61 | ||
|
|
f35f73dca0 | ||
|
|
6e74256d66 | ||
|
|
801c8a670c |
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
.DS_Store
|
||||
coverage
|
||||
.nyc_output
|
||||
playwright-report
|
||||
test-results
|
||||
@@ -0,0 +1,172 @@
|
||||
name: lpt-fe Build & Deploy
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
environment:
|
||||
description: '部署环境(dev 仅允许 dev 分支;prod 仅允许 master/main)'
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- dev
|
||||
- prod
|
||||
|
||||
env:
|
||||
REGISTRY: 192.168.123.199:5000
|
||||
APP: lpt-fe
|
||||
REPO_URL: http://git.cat-shark.xyz/cat-shark/lpt-fe.git
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Validate branch ↔ environment
|
||||
run: |
|
||||
set -euo pipefail
|
||||
REF="${{ gitea.ref }}"
|
||||
BRANCH="${REF#refs/heads/}"
|
||||
# tag 触发时拒绝
|
||||
if [[ "$REF" == refs/tags/* ]]; then
|
||||
echo "ERROR: 请从分支触发部署,不要用 tag。当前 ref=$REF"
|
||||
exit 1
|
||||
fi
|
||||
ENV="${{ inputs.environment }}"
|
||||
echo "branch=$BRANCH environment=$ENV sha=${{ gitea.sha }}"
|
||||
case "$ENV" in
|
||||
prod)
|
||||
case "$BRANCH" in
|
||||
master|main) echo "OK: prod 允许从 $BRANCH 部署" ;;
|
||||
*)
|
||||
echo "ERROR: prod 只能从 master/main 部署,当前分支是 '$BRANCH'"
|
||||
echo "请切换到 master 后再 Run workflow,并选择 environment=prod"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
dev)
|
||||
case "$BRANCH" in
|
||||
dev) echo "OK: dev 允许从 $BRANCH 部署" ;;
|
||||
*)
|
||||
echo "ERROR: dev 只能从 dev 分支部署,当前分支是 '$BRANCH'"
|
||||
echo "请切换到 dev 后再 Run workflow,并选择 environment=dev"
|
||||
echo "(禁止用 master 代码部署到 lpt-dev,避免环境错配)"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
echo "ERROR: 未知 environment=$ENV"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Checkout code
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git clone "$REPO_URL" .
|
||||
git checkout "${{ gitea.sha }}"
|
||||
|
||||
- name: Login to Docker Registry
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
|
||||
- name: Build & Push Docker image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ENV="${{ inputs.environment }}"
|
||||
if [ "$ENV" = "prod" ]; then
|
||||
BUILD_MODE=production
|
||||
else
|
||||
BUILD_MODE=development
|
||||
fi
|
||||
TAG="${{ gitea.sha }}-$(date +%s)"
|
||||
echo "Building $REGISTRY/$APP:$TAG (BUILD_MODE=$BUILD_MODE, env tag=$ENV)"
|
||||
docker build \
|
||||
--build-arg "BUILD_MODE=$BUILD_MODE" \
|
||||
-t "$REGISTRY/$APP:$TAG" \
|
||||
-t "$REGISTRY/$APP:$ENV" .
|
||||
docker push "$REGISTRY/$APP:$TAG"
|
||||
docker push "$REGISTRY/$APP:$ENV"
|
||||
# 持久化 TAG:兼容 Gitea / GitHub Actions;文件兜底避免 env 文件不支持
|
||||
if [ -n "${GITHUB_ENV:-}" ]; then
|
||||
echo "IMAGE_TAG=$TAG" >> "$GITHUB_ENV"
|
||||
fi
|
||||
if [ -n "${GITEA_ENV:-}" ]; then
|
||||
echo "IMAGE_TAG=$TAG" >> "$GITEA_ENV"
|
||||
fi
|
||||
echo "$TAG" > image_tag.txt
|
||||
if [ -n "${{ runner.temp }}" ]; then
|
||||
echo "$TAG" > "${{ runner.temp }}/image_tag.txt" || true
|
||||
fi
|
||||
echo "IMAGE_TAG=$TAG"
|
||||
|
||||
- name: Setup kubectl
|
||||
run: |
|
||||
set -euo pipefail
|
||||
curl -sLO "https://dl.k8s.io/release/v1.30.0/bin/linux/amd64/kubectl"
|
||||
chmod +x kubectl
|
||||
mv kubectl /usr/local/bin/
|
||||
echo "${{ secrets.KUBECONFIG_B64 }}" | base64 -d > /tmp/kubeconfig
|
||||
|
||||
- name: Create/Update imagePullSecret
|
||||
run: |
|
||||
set -euo pipefail
|
||||
kubectl --kubeconfig=/tmp/kubeconfig create secret docker-registry regcred \
|
||||
--docker-server="$REGISTRY" \
|
||||
--docker-username="${{ secrets.REGISTRY_USERNAME }}" \
|
||||
--docker-password="${{ secrets.REGISTRY_PASSWORD }}" \
|
||||
-n "lpt-${{ inputs.environment }}" \
|
||||
--dry-run=client -o yaml | kubectl --kubeconfig=/tmp/kubeconfig apply -f -
|
||||
|
||||
- name: Deploy to K8s
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ENV="${{ inputs.environment }}"
|
||||
IMAGE_TAG="${IMAGE_TAG:-}"
|
||||
if [ -z "$IMAGE_TAG" ] && [ -f image_tag.txt ]; then
|
||||
IMAGE_TAG="$(cat image_tag.txt)"
|
||||
fi
|
||||
if [ -z "$IMAGE_TAG" ] && [ -f "${{ runner.temp }}/image_tag.txt" ]; then
|
||||
IMAGE_TAG="$(cat "${{ runner.temp }}/image_tag.txt")"
|
||||
fi
|
||||
if [ -z "$IMAGE_TAG" ]; then
|
||||
echo "ERROR: IMAGE_TAG 为空,无法部署"
|
||||
exit 1
|
||||
fi
|
||||
echo "Deploying $REGISTRY/$APP:$IMAGE_TAG -> namespace lpt-$ENV"
|
||||
kubectl --kubeconfig=/tmp/kubeconfig set image "deployment/$APP" \
|
||||
"$APP=$REGISTRY/$APP:$IMAGE_TAG" \
|
||||
-n "lpt-$ENV" --record
|
||||
kubectl --kubeconfig=/tmp/kubeconfig rollout status "deployment/$APP" \
|
||||
-n "lpt-$ENV" --timeout=5m
|
||||
|
||||
- name: Debug on failure
|
||||
if: failure()
|
||||
run: |
|
||||
ENV="${{ inputs.environment }}"
|
||||
echo "=== Deployment Status ==="
|
||||
kubectl --kubeconfig=/tmp/kubeconfig get deployment "$APP" -n "lpt-$ENV" || true
|
||||
echo ""
|
||||
echo "=== Pod Status ==="
|
||||
kubectl --kubeconfig=/tmp/kubeconfig get pods -n "lpt-$ENV" -l "app=$APP" || true
|
||||
echo ""
|
||||
echo "=== Recent Events ==="
|
||||
kubectl --kubeconfig=/tmp/kubeconfig get events -n "lpt-$ENV" --sort-by='.lastTimestamp' | tail -20 || true
|
||||
echo ""
|
||||
echo "=== Pod Describe (latest) ==="
|
||||
POD=$(kubectl --kubeconfig=/tmp/kubeconfig get pods -n "lpt-$ENV" -l "app=$APP" --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1].metadata.name}' 2>/dev/null || true)
|
||||
if [ -n "${POD:-}" ]; then
|
||||
kubectl --kubeconfig=/tmp/kubeconfig describe pod "$POD" -n "lpt-$ENV" || true
|
||||
echo ""
|
||||
echo "=== Pod Logs (latest) ==="
|
||||
kubectl --kubeconfig=/tmp/kubeconfig logs "$POD" -n "lpt-$ENV" --tail=50 || true
|
||||
fi
|
||||
|
||||
- name: Rollback on failure
|
||||
if: failure()
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ENV="${{ inputs.environment }}"
|
||||
kubectl --kubeconfig=/tmp/kubeconfig rollout undo "deployment/$APP" -n "lpt-$ENV" || true
|
||||
kubectl --kubeconfig=/tmp/kubeconfig rollout status "deployment/$APP" -n "lpt-$ENV" || true
|
||||
@@ -28,3 +28,7 @@ coverage
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
# Test artifacts
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# LPT 前端应用(lpt-fe)
|
||||
|
||||
> Vue 3 + TypeScript + Vite 单页应用。
|
||||
|
||||
## Git 提交规范
|
||||
|
||||
- 提交信息必须简短且使用中文,不要使用英文长句。
|
||||
- 格式:`类型: 简述`,例如 `feat: 新增学习会话页面`、`fix: 修复路由守卫401跳转`、`docs: 补充组件说明`。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- 框架:Vue 3 + TypeScript + Vite 5
|
||||
- UI 库:Element Plus 2.8
|
||||
- HTTP:Axios(`withCredentials: true`,自动携带 Cookie `satoken`)
|
||||
- 思维导图:mind-elixir 5.13
|
||||
- Markdown:marked 18.0
|
||||
- 测试:Vitest + Playwright
|
||||
|
||||
## 项目结构
|
||||
|
||||
```text
|
||||
lpt-fe/src/
|
||||
├── api/ → API 接口层
|
||||
├── components/ → 页面组件
|
||||
├── components/composables/ → 组合式函数
|
||||
├── router/ → 路由配置
|
||||
├── utils/ → 工具函数
|
||||
├── assets/ → 全局样式与资源
|
||||
└── __tests__/ → 单元测试
|
||||
```
|
||||
|
||||
核心组件:`Login.vue`、`Welcome.vue`、`Study.vue`、`StartTask.vue`、`Review.vue`、`ReviewDetail.vue`、`ReviewRecall.vue`、`TaskForm.vue`、`MindMapViewer.vue`、`MarkdownRenderer.vue`。
|
||||
|
||||
## 路由表
|
||||
|
||||
| 路径 | 组件 | 说明 |
|
||||
|------|------|------|
|
||||
| `/login` | Login.vue | 登录页(无需认证) |
|
||||
| `/welcome` | Welcome.vue | 首页 |
|
||||
| `/study` | Study.vue | 学习任务列表 |
|
||||
| `/start-task/:taskNum` | StartTask.vue | 学习会话 |
|
||||
| `/add-task` | TaskForm.vue | 创建任务 |
|
||||
| `/update-task/:taskId` | TaskForm.vue | 更新任务 |
|
||||
| `/review` | Review.vue | 复习总览 |
|
||||
| `/review/detail/:type/:id` | ReviewDetail.vue | 复习详情 |
|
||||
| `/review/recall/:taskNum` | ReviewRecall.vue | 回忆复习 |
|
||||
|
||||
## 认证与请求
|
||||
|
||||
- Axios `withCredentials: true`,Cookie `satoken` 自动携带。
|
||||
- 401 处理:HTTP 层和业务层双重检测,清理 `localStorage.isLoggedIn` 后跳转 `/login`。
|
||||
- `validateResponse`:`code !== 200` 时 reject。
|
||||
- Vite 代理:`/api` → `http://localhost:5157`,自动重写去掉 `/api` 前缀。
|
||||
|
||||
## Markdown 学习材料
|
||||
|
||||
- 编辑:textarea 输入,支持 `[文字](url)` 和裸 URL。
|
||||
- 预览:`renderMarkdown(raw)` 同步函数,使用 `__LINK_N__` 占位符防止嵌套 HTML。
|
||||
- 保存:`convertMaterialUrls()` 异步拉取标题,替换裸 URL 为 `[标题](url)`。
|
||||
- `getUrlTitle(url)`:调用 `/utils/fetch-title`,带内存缓存和请求去重。
|
||||
|
||||
## 应用场景
|
||||
|
||||
- TaskForm 编辑页使用 `el-dialog` 弹窗管理应用场景。
|
||||
- Study 详情页使用 `getUrlTitle` 展示应用场景链接标题。
|
||||
|
||||
## 样式与交互约定
|
||||
|
||||
- 链接使用绿色系 `var(--green-600)`,虚线下划线,hover 变实线。
|
||||
- 区块分隔使用 `.detail-block`:`border-top` + `padding-top`,首个除外。
|
||||
- 小字提示使用 12px `var(--text-secondary)`。
|
||||
- `Study.vue` 任务清单每页 20 条。
|
||||
- `StartTask.vue` 编辑任务时先 GET 详情,合并后再 PUT,避免覆盖其他字段。
|
||||
- `MindMapViewer.vue` 支持只读、编辑、selectable、colorByCompare 模式;selectable 模式下点击节点 emit `node-select`。
|
||||
- ReviewRecall 中 `standardExpanded` 展开后节点可点击,用于选择复习起点。
|
||||
|
||||
## 前端代码标准
|
||||
|
||||
### 交互防抖与加载原则
|
||||
|
||||
- 点击后需要跳转到其他页面时,应立刻执行跳转,不要在跳转前等待接口返回;目标页面在数据未加载完成时必须展示页面级 loading。
|
||||
- 点击后不跳转页面时,触发接口的按钮必须自身展示 loading 或在请求期间禁用,防止网络慢时被多次触发。
|
||||
- 登录、创建/更新、结束会话等必须确认后端成功的操作属于例外:按钮先进入 loading,成功后再跳转。
|
||||
- 同一异步动作执行期间必须通过 loading 或 disabled 阻止重复触发,不能只依赖路由跳转后的页面卸载。
|
||||
|
||||
### 按钮规范
|
||||
|
||||
- 页面主操作 / 卡片 CTA:`size="large"`,如 Study 开始任务、TaskForm 保存、Welcome 快速入口。
|
||||
- 区块工具栏 / 页内操作:默认尺寸,如 Review 刷新、ReviewRecall 面板操作、历史记录。
|
||||
- 表格/列表行内操作:`size="small"`,主操作实底 `type="success"`,次操作 `text`;如 Review 卡片中「回忆复习」为主、「查看记录」为次。
|
||||
- 弹窗 footer:默认尺寸;确认按钮 `type="success"`,取消按钮默认;危险操作统一 `type="danger"`。
|
||||
- 正向/保存语义统一 `success`,次级编辑语义可用 `primary`,不要在同一功能上混用。
|
||||
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css` 的 `.action-row / .edit-actions / .fragment-edit-actions / .task-actions`;`.task-actions` 中主操作在上、次操作在下(如 Review 的回忆复习/查看记录)。
|
||||
|
||||
### 移动端适配
|
||||
|
||||
- 断点约定:按钮/弹窗使用 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)不进入业务代码。
|
||||
|
||||
### 测试规范
|
||||
|
||||
- 单元测试必须直接测试真实代码:直接调用 composable、挂载真实组件、使用真实路由;禁止把组件或 composable 的逻辑复制到测试里再自测。
|
||||
- 测试中可以 mock 外部依赖(API、Element Plus 服务、Audio 等),但被测逻辑本身必须来自生产模块。
|
||||
- `script setup` 内部状态需要测试访问时,通过 `defineExpose` 暴露,而不是在测试里重写一份相同逻辑。
|
||||
|
||||
### 提交前检查
|
||||
|
||||
- 运行 `npx vue-tsc --noEmit`、`npm run test`、`npm run build`。
|
||||
- 提交信息按 Git 提交规范使用中文短句;样式类改动用 `style:`,清理类用 `refactor:` / `chore:`。
|
||||
|
||||
## 开发配置
|
||||
|
||||
- 开发端口:5158
|
||||
- 代理:`/api` → `http://localhost:5157`
|
||||
- 环境变量:`.env.development` / `.env.production` / `.env.uat`
|
||||
|
||||
## 启动命令
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
npm run build
|
||||
npm run test
|
||||
npm run test:e2e
|
||||
npx vue-tsc --noEmit
|
||||
```
|
||||
|
||||
编译检查也可以使用:
|
||||
|
||||
```bash
|
||||
npx vite build
|
||||
npx vue-tsc --noEmit
|
||||
```
|
||||
|
||||
## Docker
|
||||
|
||||
- 多阶段构建:`node:20-alpine` 编译 → `nginx:alpine` 运行。
|
||||
- 暴露端口:80。
|
||||
- 构建参数:`BUILD_MODE`,默认 production。
|
||||
|
||||
## 关联项目
|
||||
|
||||
| 项目 | 路径 | 端口 | 说明 |
|
||||
|------|------|------|------|
|
||||
| lpt-be | `../lpt-be/` | 5157 | Spring Boot 后端,前端通过 `/api` 代理调用 |
|
||||
| lpt-ai | `../lpt-ai/` | 5199 | AI 服务,前端不直接调用 |
|
||||
|
||||
## 调用关系
|
||||
|
||||
```text
|
||||
浏览器 → lpt-fe (5158) ──/api──→ lpt-be (5157) ──HTTP──→ lpt-ai (5199)
|
||||
│
|
||||
└── MySQL (8109)
|
||||
```
|
||||
+16
-5
@@ -1,10 +1,21 @@
|
||||
# --- 构建阶段 ---
|
||||
FROM node:20-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
ARG BUILD_MODE=production
|
||||
|
||||
# 先复制依赖描述文件,利用层缓存
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm install
|
||||
|
||||
# 再复制源码,构建
|
||||
COPY . .
|
||||
RUN npm run type-check && npm run build:${BUILD_MODE}
|
||||
|
||||
# --- 生产阶段 ---
|
||||
FROM nginx:alpine
|
||||
|
||||
# 安装 curl 用于健康检查
|
||||
RUN apk add --no-cache curl
|
||||
|
||||
COPY dist/ /usr/share/nginx/html/
|
||||
COPY --from=builder /app/dist/ /usr/share/nginx/html/
|
||||
RUN chmod -R 755 /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
Vendored
+12
-61
@@ -1,51 +1,18 @@
|
||||
pipeline {
|
||||
agent none // 全局不指定,局部单独声明
|
||||
agent none
|
||||
environment {
|
||||
IMAGE_NAME = 'lpt-fe:0.0'
|
||||
IMAGE_NAME = "lpt-fe:${env.GIT_COMMIT?.take(8) ?: '0.0'}"
|
||||
CONTAINER_NAME = 'LPT_FE'
|
||||
CONTAINER_PORT = '80'
|
||||
}
|
||||
stages {
|
||||
stage('Install Dependencies') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
stage('构建 Docker 镜像') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
npm config set cache /.npm
|
||||
npm install
|
||||
'''
|
||||
sh 'docker build --build-arg BUILD_MODE=production -t $IMAGE_NAME .'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Type Check & Build') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
steps {
|
||||
sh '''
|
||||
npm run type-check
|
||||
npm run build
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build Docker Image') {
|
||||
agent any // Jenkins默认节点,有Docker命令
|
||||
steps {
|
||||
sh '''
|
||||
docker build -t $IMAGE_NAME .
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Run Docker Container') {
|
||||
stage('部署容器') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
@@ -60,36 +27,20 @@ pipeline {
|
||||
--label "traefik.http.routers.lpt-fe.tls.certresolver=le" \\
|
||||
--label "traefik.http.routers.lpt-fe.service=lpt-fe" \\
|
||||
--label "traefik.http.services.lpt-fe.loadbalancer.server.port=$CONTAINER_PORT" \\
|
||||
--health-cmd="curl -f http://localhost:80 || exit 1" \\
|
||||
--health-interval=5s \\
|
||||
--health-retries=3 \\
|
||||
--restart=always \\
|
||||
$IMAGE_NAME
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Check Docker Status') {
|
||||
stage('健康检查') {
|
||||
agent any
|
||||
steps {
|
||||
script {
|
||||
def lastStatus = ''
|
||||
timeout(time: 60, unit: 'SECONDS') {
|
||||
waitUntil {
|
||||
def status = sh(
|
||||
script: "docker inspect -f '{{.State.Health.Status}}' $CONTAINER_NAME || echo 'unhealthy'",
|
||||
returnStdout: true
|
||||
).trim()
|
||||
|
||||
if (status != lastStatus) {
|
||||
echo "Container health: ${status}"
|
||||
lastStatus = status
|
||||
}
|
||||
|
||||
return (status == 'healthy')
|
||||
}
|
||||
sh 'sleep 15 && docker exec $CONTAINER_NAME curl -f http://localhost:$CONTAINER_PORT/ || (docker logs $CONTAINER_NAME && exit 1)'
|
||||
}
|
||||
}
|
||||
stage('清理旧镜像') {
|
||||
agent any
|
||||
steps {
|
||||
sh 'docker image prune -af --filter "until=168h" || true'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-62
@@ -1,51 +1,18 @@
|
||||
pipeline {
|
||||
agent none // 全局不指定,局部单独声明
|
||||
agent none
|
||||
environment {
|
||||
IMAGE_NAME = 'lpt-fe-dev:0.0'
|
||||
CONTAINER_NAME = 'LPT_FE-dev'
|
||||
CONTAINER_PORT = '80'
|
||||
}
|
||||
stages {
|
||||
stage('Install Dependencies') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
stage('构建 Docker 镜像') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
npm config set cache /.npm
|
||||
npm install
|
||||
'''
|
||||
sh 'docker build --build-arg BUILD_MODE=dev -t $IMAGE_NAME .'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Type Check & Build') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
steps {
|
||||
sh '''
|
||||
npm run type-check
|
||||
npm run build:dev
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build Docker Image') {
|
||||
agent any // Jenkins默认节点,有Docker命令
|
||||
steps {
|
||||
sh '''
|
||||
docker build -t $IMAGE_NAME .
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Run Docker Container') {
|
||||
stage('部署容器') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
@@ -60,36 +27,14 @@ pipeline {
|
||||
--label "traefik.http.routers.lpt-fe-dev.tls.certresolver=le" \\
|
||||
--label "traefik.http.routers.lpt-fe-dev.service=lpt-fe-dev" \\
|
||||
--label "traefik.http.services.lpt-fe-dev.loadbalancer.server.port=$CONTAINER_PORT" \\
|
||||
--health-cmd="curl -f http://localhost:80 || exit 1" \\
|
||||
--health-interval=5s \\
|
||||
--health-retries=3 \\
|
||||
--restart=always \\
|
||||
$IMAGE_NAME
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Check Docker Status') {
|
||||
stage('健康检查') {
|
||||
agent any
|
||||
steps {
|
||||
script {
|
||||
def lastStatus = ''
|
||||
timeout(time: 60, unit: 'SECONDS') {
|
||||
waitUntil {
|
||||
def status = sh(
|
||||
script: "docker inspect -f '{{.State.Health.Status}}' $CONTAINER_NAME || echo 'unhealthy'",
|
||||
returnStdout: true
|
||||
).trim()
|
||||
|
||||
if (status != lastStatus) {
|
||||
echo "Container health: ${status}"
|
||||
lastStatus = status
|
||||
}
|
||||
|
||||
return (status == 'healthy')
|
||||
}
|
||||
}
|
||||
}
|
||||
sh 'sleep 5 && docker exec $CONTAINER_NAME curl -f http://localhost:$CONTAINER_PORT/ || (docker logs $CONTAINER_NAME && exit 1)'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Auth guard', () => {
|
||||
test('redirects to /login when not authenticated', async ({ page }) => {
|
||||
// Ensure no auth state
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.removeItem('isLoggedIn'));
|
||||
await page.goto('/welcome');
|
||||
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
await expect(page.locator('.login-page')).toBeVisible();
|
||||
});
|
||||
|
||||
test('redirects / to /login when not authenticated', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.removeItem('isLoggedIn'));
|
||||
await page.goto('/');
|
||||
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
});
|
||||
|
||||
test('allows access to /welcome when authenticated', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
|
||||
await expect(page).toHaveURL(/\/welcome/);
|
||||
await expect(page.locator('.welcome-page')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockLoginSuccess = { code: 200, message: '登录成功' };
|
||||
const mockLoginFailure = { code: 401, message: '账号或密码错误' };
|
||||
const mockTasks = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
test.describe('Login page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForSelector('.login-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('renders the login form with title and inputs', async ({ page }) => {
|
||||
await expect(page.locator('h2')).toContainText('账号登录');
|
||||
await expect(page.locator('.login-form')).toBeVisible();
|
||||
// Element Plus inputs
|
||||
const inputs = page.locator('.el-input');
|
||||
await expect(inputs).toHaveCount(2);
|
||||
await expect(page.locator('.submit-btn')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows validation errors when fields are empty', async ({ page }) => {
|
||||
await page.locator('.submit-btn').click();
|
||||
// Element Plus validation shows error messages
|
||||
await expect(page.locator('.el-form-item__error').first()).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test('shows error on invalid credentials', async ({ page }) => {
|
||||
await page.route('**/api/login**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockLoginFailure),
|
||||
}),
|
||||
);
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockTasks) }),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
// 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');
|
||||
await usernameInput.fill('wronguser');
|
||||
await passwordInput.fill('wrongpass');
|
||||
await page.locator('.submit-btn').click();
|
||||
|
||||
// Element Plus error message appears in a popup
|
||||
await expect(page.locator('.el-message--error')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test('successful login navigates to /welcome', async ({ page }) => {
|
||||
await page.route('**/api/login**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockLoginSuccess),
|
||||
}),
|
||||
);
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockTasks) }),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
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');
|
||||
await usernameInput.fill('admin');
|
||||
await passwordInput.fill('password123');
|
||||
await page.locator('.submit-btn').click();
|
||||
|
||||
await expect(page).toHaveURL(/\/welcome/, { timeout: 10_000 });
|
||||
const isLoggedIn = await page.evaluate(() => localStorage.getItem('isLoggedIn'));
|
||||
expect(isLoggedIn).toBe('true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockTasks = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
test.describe('Header navigation', () => {
|
||||
test('shows brand title on login page', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await expect(page.locator('.login-page')).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.locator('.login-panel h1')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows logout button on authenticated pages', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.head .logout-btn')).toBeVisible();
|
||||
});
|
||||
|
||||
test('logout clears auth and redirects to /login', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
await page.locator('.head .logout-btn').click();
|
||||
await expect(page).toHaveURL(/\/login/, { timeout: 5000 });
|
||||
const isLoggedIn = await page.evaluate(() => localStorage.getItem('isLoggedIn'));
|
||||
expect(isLoggedIn).toBeNull();
|
||||
});
|
||||
|
||||
test('back button shows on sub-pages and navigates to /welcome', async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) => {
|
||||
if (route.request().url().includes('/src/')) return route.continue();
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockTasks) });
|
||||
});
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/study');
|
||||
await page.waitForSelector('.study-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.head .back-btn')).toBeVisible();
|
||||
await page.locator('.head .back-btn').click();
|
||||
await expect(page).toHaveURL(/\/welcome/);
|
||||
});
|
||||
|
||||
test('no back button on welcome page', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.head .back-btn')).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockTasksData = {
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
taskNum: 'T001',
|
||||
taskName: '学习 Vue3',
|
||||
reportCount: 3,
|
||||
fragmentCount: 5,
|
||||
effectiveTime: 9000,
|
||||
},
|
||||
{
|
||||
taskNum: 'T002',
|
||||
taskName: '学习 TypeScript',
|
||||
reportCount: 1,
|
||||
fragmentCount: 2,
|
||||
effectiveTime: 4500,
|
||||
},
|
||||
],
|
||||
};
|
||||
const mockTasksEmpty = { code: 200, data: [] };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
test.describe('Review page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/review/tasks**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasksData),
|
||||
}),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/review');
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('displays summary metrics and task table', 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);
|
||||
});
|
||||
|
||||
test('shows empty state when no tasks', async ({ page }) => {
|
||||
await page.route('**/api/review/tasks**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasksEmpty),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/review');
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.metric-card').first().locator('strong')).toContainText('0');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockSessionOngoing = {
|
||||
code: 200,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
taskName: '学习 Vue3',
|
||||
taskNum: 'T001',
|
||||
startTime: '2026-05-30T10:00:00',
|
||||
endTime: null,
|
||||
lastStartTime: '2026-05-30T10:00:00',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1500000,
|
||||
systemMessage: '',
|
||||
},
|
||||
};
|
||||
|
||||
const mockSessionPaused = {
|
||||
code: 200,
|
||||
data: {
|
||||
...mockSessionOngoing.data,
|
||||
sessionState: 'PAUSED',
|
||||
lastStartTime: '2026-05-30T10:05:00',
|
||||
actualTime: 300,
|
||||
effectiveTime: 300,
|
||||
},
|
||||
};
|
||||
|
||||
const mockApiResponse = (code = 200, data: any = null, message = '请求成功') => ({
|
||||
code,
|
||||
message,
|
||||
data,
|
||||
});
|
||||
|
||||
test.describe('StartTask - 暂停后继续', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// mock 音频权限(阻止 audio.play() 弹窗阻塞会话加载)
|
||||
await page.addInitScript(() => {
|
||||
HTMLAudioElement.prototype.play = () => Promise.resolve();
|
||||
});
|
||||
|
||||
// 模拟登录
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
|
||||
// mock startOrContinue API(初始加载返回 ONGOING 状态)
|
||||
await page.route('**/api/tasks/*/study-sessions/start-or-continue', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockSessionOngoing),
|
||||
}),
|
||||
);
|
||||
|
||||
// mock fragments API
|
||||
await page.route('**/api/study-sessions/*/all-fragments', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse(200, [])),
|
||||
}),
|
||||
);
|
||||
|
||||
// mock 学习预期(已存在,避免强制弹窗阻塞流程)
|
||||
await page.route('**/api/study-sessions/*/expectation', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse(200, { sessionNum: 'SESSION_001', description: '测试预期' })),
|
||||
}),
|
||||
);
|
||||
|
||||
// mock 报告草稿
|
||||
await page.route('**/api/study-sessions/*/report-draft', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse(200, '')),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('暂停后点击开始,应触发 continue API', async ({ page }) => {
|
||||
// 记录 API 调用
|
||||
const apiCalls: string[] = [];
|
||||
|
||||
// mock pause API
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/pause', (route) => {
|
||||
apiCalls.push('pause');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
// mock continue API
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/continue', (route) => {
|
||||
apiCalls.push('continue');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
// 进入 start-task 页面
|
||||
await page.goto('/start-task/T001');
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
|
||||
// 等待计时器启动
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
|
||||
// 点击暂停按钮
|
||||
await page.locator('button', { hasText: '暂停' }).click();
|
||||
|
||||
// 验证暂停 API 被调用
|
||||
expect(apiCalls).toContain('pause');
|
||||
|
||||
// 验证状态变为已暂停
|
||||
await expect(page.locator('.status-text')).toContainText('已暂停');
|
||||
|
||||
// 点击开始按钮
|
||||
await page.locator('button', { hasText: '开始' }).click();
|
||||
|
||||
// 验证 continue API 被调用
|
||||
expect(apiCalls).toContain('continue');
|
||||
|
||||
// 验证状态恢复为进行中
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
});
|
||||
|
||||
test('暂停后点击开始,不暂停时开始不应触发 continue API', async ({ page }) => {
|
||||
const apiCalls: string[] = [];
|
||||
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/pause', (route) => {
|
||||
apiCalls.push('pause');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/continue', (route) => {
|
||||
apiCalls.push('continue');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto('/start-task/T001');
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
|
||||
// ONGOING 状态下,开始按钮是 disabled 的,不应触发 continue
|
||||
const startBtn = page.locator('button', { hasText: '开始' });
|
||||
await expect(startBtn).toBeDisabled();
|
||||
|
||||
// continue API 不应被调用
|
||||
expect(apiCalls).not.toContain('continue');
|
||||
});
|
||||
|
||||
test('暂停后结束会话,应正确调用 ended API 并展示提示', async ({ page }) => {
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/pause', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/ended', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse(200, null, '本次有效学习时间不足10分钟,不计入总学习时间')),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/start-task/T001');
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
|
||||
// 暂停
|
||||
await page.locator('button', { hasText: '暂停' }).click();
|
||||
await expect(page.locator('.status-text')).toContainText('已暂停');
|
||||
|
||||
// 结束会话
|
||||
await page.locator('button', { hasText: '结束会话' }).click();
|
||||
|
||||
// 在弹窗中输入总结内容
|
||||
await page.locator('.el-dialog textarea').fill('测试总结');
|
||||
await page.locator('.el-dialog button', { hasText: '确认结束' }).click();
|
||||
|
||||
// 确认第二个弹窗("确定要结束本次学习会话吗?")
|
||||
const confirmBtn = page.locator('.el-message-box__btns button', { hasText: '确定' });
|
||||
await confirmBtn.waitFor({ timeout: 5000 });
|
||||
await confirmBtn.click();
|
||||
|
||||
// 应看到 warning 提示(有效时间不足)
|
||||
await expect(page.locator('.el-message--warning')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockTasks = {
|
||||
code: 200,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
taskNum: 'T001',
|
||||
taskName: '学习 Vue3 组合式 API',
|
||||
taskDescription: '掌握 Composition API 的核心概念',
|
||||
taskPriority: 5,
|
||||
materialUrl: 'https://vuejs.org/guide',
|
||||
lastLearningStatus: '进行中',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
taskNum: 'T002',
|
||||
taskName: 'TypeScript 类型体操',
|
||||
taskDescription: '练习 TypeScript 高级类型',
|
||||
taskPriority: 3,
|
||||
materialUrl: '',
|
||||
lastLearningStatus: '未开始',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const mockTasksEmpty = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
const authAndNavigate = async (page: any) => {
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
};
|
||||
|
||||
test.describe('Study page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) => {
|
||||
const url = route.request().url();
|
||||
// 排除 Vite 模块加载请求(.ts 文件),只拦截真正的 API 请求
|
||||
// Vite 模块请求都走 /src/ 路径,跳过它们只拦截真正的 API 请求
|
||||
if (url.includes('/src/')) return route.continue();
|
||||
if (url.includes('/tasks') && !url.includes('/tasks/')) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasks),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: {} }),
|
||||
});
|
||||
});
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
await authAndNavigate(page);
|
||||
await page.goto('/study');
|
||||
await page.waitForSelector('.study-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('displays task list with names and priorities', async ({ page }) => {
|
||||
const taskItems = page.locator('.task-list-item');
|
||||
await expect(taskItems).toHaveCount(2);
|
||||
await expect(taskItems.first().locator('.task-name')).toContainText('学习 Vue3 组合式 API');
|
||||
await expect(taskItems.nth(1).locator('.task-name')).toContainText('TypeScript 类型体操');
|
||||
});
|
||||
|
||||
test('selecting a task shows its details', async ({ page }) => {
|
||||
const taskItems = page.locator('.task-list-item');
|
||||
await taskItems.nth(1).click();
|
||||
await expect(page.locator('.detail-head h3')).toContainText('TypeScript 类型体操');
|
||||
});
|
||||
|
||||
test('clicking add navigates to add-task form', async ({ page }) => {
|
||||
await page.locator('.action-card').locator('button', { hasText: '添加任务' }).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 expect(page).toHaveURL(/\/update-task/);
|
||||
});
|
||||
|
||||
test('delete task removes it from the list', async ({ page }) => {
|
||||
await page.route('**/api/tasks/1', (route) => {
|
||||
const url = route.request().url();
|
||||
// Vite 模块请求都走 /src/ 路径,跳过它们只拦截真正的 API 请求
|
||||
if (url.includes('/src/')) return route.continue();
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, message: '删除成功' }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.locator('.action-card').locator('button', { hasText: '删除任务' }).click();
|
||||
// 处理确认弹窗
|
||||
const confirmBtn = page.locator('.el-message-box__btns button:has-text("确定删除")');
|
||||
await confirmBtn.waitFor({ timeout: 3000 });
|
||||
await confirmBtn.click();
|
||||
await expect(page.locator('.task-list-item')).toHaveCount(1, { timeout: 5000 });
|
||||
});
|
||||
|
||||
test('shows empty state when no tasks', async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) => {
|
||||
const url = route.request().url();
|
||||
// Vite 模块请求都走 /src/ 路径,跳过它们只拦截真正的 API 请求
|
||||
if (url.includes('/src/')) return route.continue();
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasksEmpty),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto('/study');
|
||||
await page.waitForSelector('.study-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.el-empty')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
const loginAndGo = async (page: any, url: string) => {
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto(url);
|
||||
await page.waitForSelector('.task-form-page', { timeout: 10_000 });
|
||||
};
|
||||
|
||||
test.describe('Task form', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
});
|
||||
|
||||
test('add-task form renders empty fields and "添加" button', async ({ page }) => {
|
||||
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('添加');
|
||||
});
|
||||
|
||||
test('submitting add-task sends POST and navigates to /study', async ({ page }) => {
|
||||
await page.route('**/api/tasks', (route) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, message: '创建成功' }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ code: 200, data: { records: [] } }) });
|
||||
});
|
||||
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 expect(page).toHaveURL(/\/study/, { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('update-task loads existing data and submits PUT', async ({ page }) => {
|
||||
const mockTask = {
|
||||
code: 200,
|
||||
data: {
|
||||
id: 1,
|
||||
taskName: '已有任务',
|
||||
taskDescription: '已有描述',
|
||||
materialURL: 'https://example.com',
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 1,
|
||||
},
|
||||
};
|
||||
|
||||
await page.route('**/api/tasks/1', (route) => {
|
||||
if (route.request().method() === 'PUT') {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, message: '更新成功' }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTask),
|
||||
});
|
||||
});
|
||||
|
||||
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 page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input').fill('更新后的任务');
|
||||
await page.locator('.action-row button').first().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 expect(page).toHaveURL(/\/study/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Welcome page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('shows welcome banner and quick action cards', async ({ page }) => {
|
||||
await expect(page.locator('.page-title')).toContainText('欢迎回来');
|
||||
await expect(page.locator('.page-subtitle')).toBeVisible();
|
||||
await expect(page.locator('.quick-card')).toHaveCount(2);
|
||||
});
|
||||
|
||||
test('clicking start study navigates to /study', async ({ page }) => {
|
||||
await page.locator('.quick-card').first().locator('button').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 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);
|
||||
});
|
||||
});
|
||||
Generated
+2652
-1510
File diff suppressed because it is too large
Load Diff
+15
-5
@@ -6,30 +6,40 @@
|
||||
"scripts": {
|
||||
"dev": "vite --mode development",
|
||||
"build:dev": "vite build --mode development",
|
||||
"build:development": "vite build --mode development",
|
||||
"build:production": "vite build --mode production",
|
||||
"build": "vite build --mode production",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build --force"
|
||||
"type-check": "vue-tsc --build --force",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"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",
|
||||
"normalize": "^0.3.1",
|
||||
"marked": "^18.0.5",
|
||||
"mind-elixir": "^5.13.0",
|
||||
"normalize.css": "^8.0.1",
|
||||
"style-loader": "^4.0.0",
|
||||
"vue": "^3.5.12",
|
||||
"vue-router": "^4.4.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@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",
|
||||
"@vue/test-utils": "^2.4.10",
|
||||
"@vue/tsconfig": "^0.5.1",
|
||||
"npm-run-all2": "^7.0.1",
|
||||
"jsdom": "^24.1.3",
|
||||
"tsx": "^4.23.0",
|
||||
"typescript": "~5.6.0",
|
||||
"vite": "^5.4.10",
|
||||
"vitest": "^2.1.9",
|
||||
"vue-tsc": "^2.1.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: false,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: 1,
|
||||
reporter: 'list',
|
||||
use: {
|
||||
baseURL: 'http://localhost:5158',
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
channel: 'chrome',
|
||||
},
|
||||
},
|
||||
],
|
||||
webServer: {
|
||||
command: 'npm run dev',
|
||||
url: 'http://localhost:5158',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
Generated
+2715
File diff suppressed because it is too large
Load Diff
+9
-6
@@ -14,10 +14,12 @@ const route = useRoute();
|
||||
<el-header class="shell-header">
|
||||
<MyHead />
|
||||
</el-header>
|
||||
<el-main class="shell-main">
|
||||
<el-main class="shell-main" :class="{ wide: route.meta.wide }">
|
||||
<RouterView v-slot="{ Component }">
|
||||
<Transition name="fade-up" mode="out-in">
|
||||
<RouterView :key="route.fullPath" />
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</Transition>
|
||||
</RouterView>
|
||||
</el-main>
|
||||
<el-footer class="shell-footer">
|
||||
<MyFooter />
|
||||
@@ -45,16 +47,17 @@ const route = useRoute();
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.shell-main {
|
||||
}.shell-main {
|
||||
max-width: 1240px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 18px 20px 24px;
|
||||
}
|
||||
|
||||
.shell-main.wide {
|
||||
max-width: 1720px;
|
||||
}
|
||||
|
||||
.shell-footer {
|
||||
height: auto;
|
||||
padding: 0 20px 18px;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import { login, logout } from '@/api/login'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('login API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('login sends POST to /login with credentials', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, message: 'OK' })
|
||||
const result = await login('admin', '123456')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/login', { username: 'admin', password: '123456' })
|
||||
expect(result).toEqual({ code: 200, message: 'OK' })
|
||||
})
|
||||
|
||||
it('logout sends POST to /logout', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, message: '已退出' })
|
||||
const result = await logout()
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/logout')
|
||||
expect(result).toEqual({ code: 200, message: '已退出' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('reportFragments API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
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(result).toEqual({ code: 200, data: { id: 1 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
del: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import {
|
||||
getFragmentDetail,
|
||||
getReportDetail,
|
||||
getReviewFeed,
|
||||
getReviewTaskStats,
|
||||
getReviewTaskStatsByTask,
|
||||
getTaskReview,
|
||||
} from '@/api/review'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('review API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('getReviewFeed calls GET /review/feed with limit', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
const result = await getReviewFeed(10)
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/feed', { limit: 10, mode: 'recent' })
|
||||
expect(result).toEqual({ code: 200, data: [] })
|
||||
})
|
||||
|
||||
it('getReviewFeed uses default limit of 30 and recent mode', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
await getReviewFeed()
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/feed', { limit: 30, mode: 'recent' })
|
||||
})
|
||||
|
||||
it('getReviewFeed accepts random mode', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
await getReviewFeed(50, 'random')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/feed', { limit: 50, mode: 'random' })
|
||||
})
|
||||
|
||||
it('getReviewTaskStats calls GET /review/tasks', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
await getReviewTaskStats()
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/tasks')
|
||||
})
|
||||
|
||||
it('getReviewTaskStatsByTask calls GET /review/tasks/:taskNum', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
|
||||
await getReviewTaskStatsByTask('T001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/tasks/T001')
|
||||
})
|
||||
|
||||
it('getReportDetail calls GET /review/report/:id', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
const result = await getReportDetail(1)
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/report/1')
|
||||
expect(result).toEqual({ code: 200, data: { id: 1 } })
|
||||
})
|
||||
|
||||
it('getFragmentDetail calls GET /review/fragment/:id', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { id: 5 } })
|
||||
await getFragmentDetail(5)
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/fragment/5')
|
||||
})
|
||||
|
||||
it('getTaskReview calls GET /review/task/:taskNum', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
|
||||
await getTaskReview('T001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/task/T001')
|
||||
})
|
||||
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import {
|
||||
continueSession,
|
||||
pauseSession,
|
||||
endSession,
|
||||
startOrContinueStudySession,
|
||||
getSessionDetail,
|
||||
} from '@/api/studySessions'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('studySessions API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('continueSession sends POST to correct endpoint', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await continueSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/study-sessions/S001/study-sessions/continue')
|
||||
})
|
||||
|
||||
it('pauseSession sends POST with endTime param when provided', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
const endTime = new Date('2024-01-15T10:30:00Z')
|
||||
await pauseSession('S001', endTime)
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/pause',
|
||||
null,
|
||||
{ params: { endTime: endTime.toISOString() } }
|
||||
)
|
||||
})
|
||||
|
||||
it('pauseSession sends POST with null params when endTime not provided', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await pauseSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/pause',
|
||||
null,
|
||||
{ params: null }
|
||||
)
|
||||
})
|
||||
|
||||
it('endSession sends POST with default content', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await endSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/ended',
|
||||
{ content: '任务结束' }
|
||||
)
|
||||
})
|
||||
|
||||
it('endSession sends POST with custom content', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await endSession('S001', '自定义结束')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/ended',
|
||||
{ content: '自定义结束' }
|
||||
)
|
||||
})
|
||||
|
||||
it('startOrContinueStudySession sends GET to correct endpoint', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { sessionNum: 'S002' } })
|
||||
const result = await startOrContinueStudySession('T001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/tasks/T001/study-sessions/start-or-continue')
|
||||
expect(result).toEqual({ code: 200, data: { sessionNum: 'S002' } })
|
||||
})
|
||||
|
||||
it('getSessionDetail sends GET to correct endpoint', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
await getSessionDetail('S001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/study-sessions/S001')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
del: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import {
|
||||
createTaskApplication,
|
||||
deleteTaskApplication,
|
||||
getTaskApplications,
|
||||
updateTaskApplication,
|
||||
} from '@/api/tasks'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('tasks API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('task applications API calls expected endpoints', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
mockedRequest.put.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
mockedRequest.del.mockResolvedValue({ code: 200 })
|
||||
|
||||
await getTaskApplications('T001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/tasks/T001/applications')
|
||||
|
||||
await createTaskApplication('T001', { title: 'Demo', status: 'TODO' })
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/tasks/T001/applications', {
|
||||
title: 'Demo',
|
||||
status: 'TODO',
|
||||
})
|
||||
|
||||
await updateTaskApplication(1, { title: 'Demo 2', status: 'DOING' })
|
||||
expect(mockedRequest.put).toHaveBeenCalledWith('/tasks/applications/1', {
|
||||
title: 'Demo 2',
|
||||
status: 'DOING',
|
||||
})
|
||||
|
||||
await deleteTaskApplication(1)
|
||||
expect(mockedRequest.del).toHaveBeenCalledWith('/tasks/applications/1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
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'
|
||||
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}))
|
||||
|
||||
function mountLogin() {
|
||||
return mount(Login, {
|
||||
shallow: true,
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
it('isNotEmpty validator reports empty value and accepts filled value', () => {
|
||||
const wrapper = mountLogin()
|
||||
const callback = vi.fn()
|
||||
|
||||
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, '', callback)
|
||||
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
||||
|
||||
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, 'admin', callback)
|
||||
expect(callback).toHaveBeenCalledWith()
|
||||
})
|
||||
|
||||
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'
|
||||
|
||||
await wrapper.vm.submitForm(createForm(true))
|
||||
|
||||
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'
|
||||
|
||||
await wrapper.vm.submitForm(createForm(true))
|
||||
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
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()
|
||||
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
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(),
|
||||
}))
|
||||
|
||||
async function mountAt(path: string) {
|
||||
await router.push(path)
|
||||
await router.isReady()
|
||||
return mount(MyHead, {
|
||||
shallow: true,
|
||||
global: {
|
||||
plugins: [ElementPlus, router],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('MyHead.vue', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
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 {
|
||||
continueSession,
|
||||
endSession,
|
||||
getActiveSession,
|
||||
getExpectation,
|
||||
getSessionDetail,
|
||||
pauseSession,
|
||||
startOrContinueStudySession,
|
||||
} from '@/api/studySessions'
|
||||
import { getFragmentsBySession } from '@/api/reportFragments'
|
||||
|
||||
vi.mock('@/api/studySessions', () => ({
|
||||
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 defaultSessionData = {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'PAUSED',
|
||||
taskName: '测试任务',
|
||||
taskNum: 'T001',
|
||||
taskId: 1,
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
lastStartTime: '',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1_500_000,
|
||||
systemMessage: '',
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
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 wrapper.vm.stopTimer()
|
||||
|
||||
expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(wrapper.vm.taskInfo.actualTime).toBe(10)
|
||||
expect(wrapper.vm.taskInfo.effectiveTime).toBe(20)
|
||||
expect(wrapper.vm.timerRunning).toBe(false)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
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()
|
||||
|
||||
// 挂载时后端返回 PAUSED;手动改为 PAUSED 后,startTimer 应触发 continue
|
||||
wrapper.vm.taskInfo.sessionState = 'PAUSED'
|
||||
await wrapper.vm.startTimer()
|
||||
|
||||
expect(continueSession).toHaveBeenCalledWith('SESSION_001')
|
||||
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
|
||||
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(wrapper.vm.timerRunning).toBe(true)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('startTimer does not call continue API when session is already ongoing', async () => {
|
||||
const wrapper = await mountTask()
|
||||
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||
|
||||
await wrapper.vm.startTimer()
|
||||
|
||||
expect(continueSession).not.toHaveBeenCalled()
|
||||
expect(wrapper.vm.timerRunning).toBe(true)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
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()
|
||||
|
||||
expect(startOrContinueStudySession).not.toHaveBeenCalled()
|
||||
expect(router.currentRoute.value.path).toBe('/start-task/T002')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('endTimer refuses empty content without calling API', async () => {
|
||||
const wrapper = await mountTask()
|
||||
|
||||
await wrapper.vm.endTimer('')
|
||||
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
|
||||
expect(endSession).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('endTimer ends session and navigates to study page', async () => {
|
||||
vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const wrapper = await mountTask()
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
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('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/tasks', () => ({
|
||||
getTaskApplications: vi.fn(),
|
||||
createTaskApplication: vi.fn(),
|
||||
updateTaskApplication: vi.fn(),
|
||||
deleteTaskApplication: vi.fn(),
|
||||
}))
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
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,
|
||||
})
|
||||
})
|
||||
|
||||
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
|
||||
|
||||
wrapper.vm.createTask()
|
||||
await flushPromises()
|
||||
|
||||
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'))
|
||||
})
|
||||
|
||||
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',
|
||||
urgency: 4,
|
||||
importance: 5,
|
||||
contentDifficulty: 3,
|
||||
futureValue: 4,
|
||||
subjectivePriority: 2,
|
||||
},
|
||||
})
|
||||
|
||||
const wrapper = await mountAt('/update-task/42')
|
||||
await flushPromises()
|
||||
|
||||
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,
|
||||
})
|
||||
})
|
||||
|
||||
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,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
import { useStudyFragment } from '@/components/composables/fragment'
|
||||
|
||||
vi.mock('@/api/reportFragments', () => ({
|
||||
createFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('useStudyFragment', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
|
||||
})
|
||||
|
||||
it('openFragmentDialog resets content and shows dialog', () => {
|
||||
const { fragmentsDialogVisible, fragmentContent, openFragmentDialog } = useStudyFragment()
|
||||
fragmentContent.value = 'old content'
|
||||
|
||||
openFragmentDialog()
|
||||
|
||||
expect(fragmentContent.value).toBe('')
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('closeFragmentDialog hides dialog after confirm', async () => {
|
||||
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
|
||||
fragmentsDialogVisible.value = true
|
||||
|
||||
await closeFragmentDialog()
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
expect(ElMessage.info).toHaveBeenCalledWith('已取消生成')
|
||||
})
|
||||
|
||||
it('closeFragmentDialog keeps dialog open when user cancels', async () => {
|
||||
vi.mocked(ElMessageBox.confirm).mockRejectedValue('cancel')
|
||||
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
|
||||
fragmentsDialogVisible.value = true
|
||||
|
||||
await closeFragmentDialog()
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment warns when content is empty', async () => {
|
||||
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = ' '
|
||||
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
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, fragmentsDialogVisible, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习了递归算法'
|
||||
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('学习残片生成成功!')
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles business failure', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
|
||||
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习内容'
|
||||
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
expect(result).toBe(false)
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('生成失败')
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles network error', async () => {
|
||||
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
|
||||
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||
fragmentContent.value = '学习内容'
|
||||
|
||||
const result = await confirmGenerateFragment('S001')
|
||||
|
||||
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,56 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
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()
|
||||
})
|
||||
|
||||
it('syncDisplay writes formatted remaining time', () => {
|
||||
const { timerMinutes, timerSeconds, timerIsOver, syncDisplay } = useTimer()
|
||||
|
||||
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('runCountdown decreases remaining time and stops at zero', () => {
|
||||
const { timerMinutes, timerSeconds, timerRunning, timerIsOver, runCountdown, clear } = useTimer()
|
||||
|
||||
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('notifies when countdown completes', () => {
|
||||
const { runCountdown, clear } = useTimer()
|
||||
|
||||
runCountdown(1000)
|
||||
vi.advanceTimersByTime(1000)
|
||||
|
||||
expect(ElMessageBox.alert).toHaveBeenCalled()
|
||||
clear()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import router from '@/router'
|
||||
|
||||
describe('route guards', () => {
|
||||
beforeEach(async () => {
|
||||
localStorage.clear()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
})
|
||||
|
||||
it('redirects unauthenticated user from protected route to /login', async () => {
|
||||
await router.push('/welcome')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('allows authenticated user to access protected route', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
await router.push('/welcome')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('allows unauthenticated access to /login', async () => {
|
||||
await router.push('/login')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('root path redirects to /login', async () => {
|
||||
await router.push('/')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
// 只 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,122 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { mockGet, mockPost, mockPut, mockDel } = vi.hoisted(() => ({
|
||||
mockGet: vi.fn(),
|
||||
mockPost: vi.fn(),
|
||||
mockPut: vi.fn(),
|
||||
mockDel: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('axios', () => ({
|
||||
default: {
|
||||
create: vi.fn(() => ({
|
||||
get: mockGet,
|
||||
post: mockPost,
|
||||
put: mockPut,
|
||||
delete: mockDel,
|
||||
interceptors: {
|
||||
request: { use: vi.fn() },
|
||||
response: { use: vi.fn() },
|
||||
},
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
|
||||
describe('request utility', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('get', () => {
|
||||
it('should call axios.get with url and params wrapped', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 200, data: 'test' } })
|
||||
const result = await request.get('/test', { id: 1 })
|
||||
expect(mockGet).toHaveBeenCalledWith('/test', { params: { id: 1 } })
|
||||
expect(result).toEqual({ code: 200, data: 'test' })
|
||||
})
|
||||
|
||||
it('should default to empty params object', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 200, data: 'test' } })
|
||||
await request.get('/test')
|
||||
expect(mockGet).toHaveBeenCalledWith('/test', { params: {} })
|
||||
})
|
||||
|
||||
it('should reject when response code is not 200', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 400, message: 'Bad request' } })
|
||||
await expect(request.get('/test')).rejects.toEqual({ code: 400, message: 'Bad request' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('post', () => {
|
||||
it('should call axios.post with url, data, and empty config', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 200, data: 'created' } })
|
||||
const result = await request.post('/test', { name: 'foo' })
|
||||
expect(mockPost).toHaveBeenCalledWith('/test', { name: 'foo' }, {})
|
||||
expect(result).toEqual({ code: 200, data: 'created' })
|
||||
})
|
||||
|
||||
it('should pass config when provided', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
await request.post('/test', null, { params: { id: 1 } })
|
||||
expect(mockPost).toHaveBeenCalledWith('/test', null, { params: { id: 1 } })
|
||||
})
|
||||
|
||||
it('should reject when response code is not 200', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 500, message: 'Server error' } })
|
||||
await expect(request.post('/test')).rejects.toEqual({ code: 500, message: 'Server error' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('put', () => {
|
||||
it('should call axios.put with url, data, and empty config', async () => {
|
||||
mockPut.mockResolvedValue({ data: { code: 200, data: 'updated' } })
|
||||
const result = await request.put('/test/1', { name: 'bar' })
|
||||
expect(mockPut).toHaveBeenCalledWith('/test/1', { name: 'bar' }, {})
|
||||
expect(result).toEqual({ code: 200, data: 'updated' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('del', () => {
|
||||
it('should call axios.delete with url and params wrapped', async () => {
|
||||
mockDel.mockResolvedValue({ data: { code: 200, data: 'deleted' } })
|
||||
const result = await request.del('/test/1')
|
||||
expect(mockDel).toHaveBeenCalledWith('/test/1', { params: {} })
|
||||
expect(result).toEqual({ code: 200, data: 'deleted' })
|
||||
})
|
||||
|
||||
it('should merge params into config spread for axios.delete', async () => {
|
||||
mockDel.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
// del(url, params={reason:'test'}, config={timeout:1000})
|
||||
// => axios.delete(url, { params: { reason:'test' }, timeout: 1000 })
|
||||
await request.del('/test/1', { reason: 'test' }, { timeout: 1000 })
|
||||
expect(mockDel).toHaveBeenCalledWith('/test/1', { params: { reason: 'test' }, timeout: 1000 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('generic request', () => {
|
||||
it('should dispatch GET with params', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
const result = await request.request('get', '/test', { id: 1 })
|
||||
expect(mockGet).toHaveBeenCalledWith('/test', { params: { id: 1 } })
|
||||
expect(result).toEqual({ code: 200, data: 'ok' })
|
||||
})
|
||||
|
||||
it('should dispatch POST with data', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
await request.request('post', '/test', { name: 'foo' })
|
||||
expect(mockPost).toHaveBeenCalledWith('/test', { name: 'foo' }, {})
|
||||
})
|
||||
|
||||
it('should dispatch DELETE with params', async () => {
|
||||
mockDel.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
await request.request('delete', '/test/1', null)
|
||||
expect(mockDel).toHaveBeenCalledWith('/test/1', { params: null })
|
||||
})
|
||||
|
||||
it('should throw for unsupported method', () => {
|
||||
expect(() => request.request('patch', '/test', null)).toThrow('该功能暂不可用,请刷新后重试')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,3 +4,11 @@ import request from "@/utils/request";
|
||||
export const createFragments = (sessionNum: string, content: string) => {
|
||||
return request.post(`/report-fragments`, {sessionNum, content})
|
||||
}
|
||||
|
||||
export const updateFragments = (id: number, content: string) => {
|
||||
return request.put(`/report-fragments/${id}`, {content})
|
||||
}
|
||||
|
||||
export const getFragmentsBySession = (sessionNum: string) => {
|
||||
return request.get(`/report-fragments/session/${sessionNum}`)
|
||||
}
|
||||
+23
-2
@@ -10,8 +10,29 @@ export interface ReviewFeedItem {
|
||||
createdTime: string;
|
||||
}
|
||||
|
||||
export const getReviewFeed = (limit: number = 30) => {
|
||||
return request.get("/review/feed", { limit });
|
||||
export interface ReviewTaskStats {
|
||||
taskNum: string;
|
||||
taskName: string;
|
||||
reportCount: number;
|
||||
fragmentCount: number;
|
||||
effectiveTime: number;
|
||||
sessionCount: number;
|
||||
todayEffectiveTime: number;
|
||||
weekEffectiveTime: number;
|
||||
avgEffectiveTime: number;
|
||||
avgEffectivenessRatio: number;
|
||||
}
|
||||
|
||||
export const getReviewFeed = (limit: number = 30, mode: "recent" | "random" | "smart" = "recent") => {
|
||||
return request.get("/review/feed", { limit, mode });
|
||||
};
|
||||
|
||||
export const getReviewTaskStats = () => {
|
||||
return request.get("/review/tasks");
|
||||
};
|
||||
|
||||
export const getReviewTaskStatsByTask = (taskNum: string) => {
|
||||
return request.get(`/review/tasks/${taskNum}`);
|
||||
};
|
||||
|
||||
export const getReportDetail = (id: number) => {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import request from "@/utils/request";
|
||||
|
||||
// ============ 标准思维导图 ============
|
||||
|
||||
export interface StandardMindMap {
|
||||
id: number;
|
||||
taskNum: string;
|
||||
title: string;
|
||||
content: string;
|
||||
outline: string;
|
||||
summary: string;
|
||||
generator: "BUILTIN" | "AI" | "USER" | "USER_MERGE";
|
||||
generatorVersion?: string;
|
||||
sourceReportCount: number;
|
||||
generatedTime?: string;
|
||||
createdTime?: string;
|
||||
lastModifiedTime?: string;
|
||||
}
|
||||
|
||||
export interface RecallRecord {
|
||||
id: number;
|
||||
taskNum: string;
|
||||
standardMapId: number;
|
||||
focusPath?: string;
|
||||
recallContent: string;
|
||||
compareResult: string;
|
||||
recallRatio: number;
|
||||
matchedCount: number;
|
||||
missedCount: number;
|
||||
extraCount: number;
|
||||
createdTime: string;
|
||||
}
|
||||
|
||||
/** 获取/自动生成标准思维导图 */
|
||||
export const getStandardMindMap = (taskNum: string) => {
|
||||
return request.get(`/review/standard-mind-map/${taskNum}`);
|
||||
};
|
||||
|
||||
/** 强制重新生成标准思维导图(全量或增量) */
|
||||
export const regenerateStandardMindMap = (taskNum: string, mode: "full" | "incremental" = "full") => {
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/regenerate?mode=${mode}`);
|
||||
};
|
||||
|
||||
/** 用户编辑标准思维导图(大纲文本) */
|
||||
export const updateStandardMindMap = (taskNum: string, outline: string) => {
|
||||
return request.put(`/review/standard-mind-map/${taskNum}`, { outline });
|
||||
};
|
||||
|
||||
/** 用户提交回忆大纲,与标准导图对比(可选指定起始节点路径) */
|
||||
export const recallCompare = (taskNum: string, recallOutline: string, focusPath?: string) => {
|
||||
const body: Record<string, any> = { recallOutline };
|
||||
if (focusPath) body.focusPath = focusPath;
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/recall`, body);
|
||||
};
|
||||
|
||||
/** 在标准导图中查找与内容最匹配的节点 */
|
||||
export const findNode = (taskNum: string, content: string) => {
|
||||
return request.post(`/review/standard-mind-map/${taskNum}/find-node`, { content });
|
||||
};
|
||||
|
||||
/** 获取该任务的所有回忆对比记录 */
|
||||
export const listRecallRecords = (taskNum: string) => {
|
||||
return request.get(`/review/standard-mind-map/${taskNum}/recall-records`);
|
||||
};
|
||||
@@ -21,3 +21,39 @@ export const startOrContinueStudySession = (taskNum: string) => {
|
||||
export const getSessionDetail = (sessionNum: string) => {
|
||||
return request.get(`/study-sessions/${sessionNum}`);
|
||||
};
|
||||
|
||||
/** 获取会话的学习预期 */
|
||||
export const getExpectation = (sessionNum: string) => {
|
||||
return request.get(`/study-sessions/${sessionNum}/expectation`);
|
||||
};
|
||||
|
||||
/** 创建/更新会话的学习预期 */
|
||||
export const upsertExpectation = (sessionNum: string, description: string) => {
|
||||
return request.put(`/study-sessions/${sessionNum}/expectation`, { description });
|
||||
};
|
||||
|
||||
/** 获取报告草稿(AI 聚合残片,不可用时为拼接) */
|
||||
export const getReportDraft = (sessionNum: string) => {
|
||||
return request.get(`/study-sessions/${sessionNum}/report-draft`);
|
||||
};
|
||||
|
||||
/** 查询当前是否有活跃会话 */
|
||||
export const getActiveSession = (excludeTaskNum?: string) => {
|
||||
const params: Record<string, any> = {};
|
||||
if (excludeTaskNum) params.excludeTaskNum = excludeTaskNum;
|
||||
return request.get('/study-sessions/active', params);
|
||||
};
|
||||
|
||||
/** 分页查询任务的历史残片 */
|
||||
export const getTaskFragments = (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);
|
||||
};
|
||||
|
||||
/** 分页查询任务的历史报告 */
|
||||
export const getTaskReports = (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);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import request from "@/utils/request";
|
||||
|
||||
export interface TaskApplication {
|
||||
id: number;
|
||||
taskNum: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
resourceUrl?: string;
|
||||
status: "TODO" | "DOING" | "DONE";
|
||||
createdTime?: string;
|
||||
lastModifiedTime?: string;
|
||||
}
|
||||
|
||||
export const getTaskApplications = (taskNum: string) => {
|
||||
return request.get(`/tasks/${taskNum}/applications`);
|
||||
};
|
||||
|
||||
export const createTaskApplication = (
|
||||
taskNum: string,
|
||||
payload: {
|
||||
title: string;
|
||||
description?: string;
|
||||
resourceUrl?: string;
|
||||
status?: TaskApplication["status"];
|
||||
},
|
||||
) => {
|
||||
return request.post(`/tasks/${taskNum}/applications`, payload);
|
||||
};
|
||||
|
||||
export const updateTaskApplication = (
|
||||
id: number,
|
||||
payload: {
|
||||
title: string;
|
||||
description?: string;
|
||||
resourceUrl?: string;
|
||||
status?: TaskApplication["status"];
|
||||
},
|
||||
) => {
|
||||
return request.put(`/tasks/applications/${id}`, payload);
|
||||
};
|
||||
|
||||
export const deleteTaskApplication = (id: number) => {
|
||||
return request.del(`/tasks/applications/${id}`);
|
||||
};
|
||||
|
||||
// ============ 优先级权重配置 ============
|
||||
|
||||
export interface PriorityWeights {
|
||||
urgencyWeight: number;
|
||||
importanceWeight: number;
|
||||
contentDifficultyWeight: number;
|
||||
futureValueWeight: number;
|
||||
subjectivePriorityWeight: number;
|
||||
}
|
||||
|
||||
export const getPriorityWeights = () => {
|
||||
return request.get("/tasks/priority-weights");
|
||||
};
|
||||
|
||||
/** 保存权重配置并触发全部任务优先级重算 */
|
||||
export const savePriorityWeights = (weights: PriorityWeights) => {
|
||||
return request.put("/tasks/priority-weights", weights);
|
||||
};
|
||||
@@ -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 |
+67
-1
@@ -27,12 +27,78 @@ a:hover {
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
background: var(--surface-strong);
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
/* 按钮操作区统一规范:窄屏下操作按钮纵向全宽 */
|
||||
.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>
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { marked } from "marked";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
content: string;
|
||||
}>(), {
|
||||
content: "",
|
||||
});
|
||||
|
||||
const rendered = computed(() => {
|
||||
if (!props.content) return "";
|
||||
return marked.parse(props.content, { breaks: true, gfm: true });
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="markdown-body" v-html="rendered"></div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.markdown-body {
|
||||
line-height: 1.8;
|
||||
color: #333;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.markdown-body :deep(h1),
|
||||
.markdown-body :deep(h2),
|
||||
.markdown-body :deep(h3),
|
||||
.markdown-body :deep(h4) {
|
||||
margin: 0.75em 0 0.5em;
|
||||
color: var(--green-900, #1b5e20);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.markdown-body :deep(h1) { font-size: 1.4em; }
|
||||
.markdown-body :deep(h2) { font-size: 1.25em; }
|
||||
.markdown-body :deep(h3) { font-size: 1.1em; }
|
||||
|
||||
.markdown-body :deep(p) {
|
||||
margin: 0.4em 0;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.markdown-body :deep(ul),
|
||||
.markdown-body :deep(ol) {
|
||||
margin: 0.4em 0;
|
||||
padding-left: 1.5em;
|
||||
}
|
||||
|
||||
.markdown-body :deep(li) {
|
||||
margin: 0.2em 0;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.markdown-body :deep(code) {
|
||||
background: #f0f4f0;
|
||||
padding: 0.15em 0.4em;
|
||||
border-radius: 3px;
|
||||
font-size: 0.9em;
|
||||
color: #c62828;
|
||||
}
|
||||
|
||||
.markdown-body :deep(pre) {
|
||||
background: #f5f7f5;
|
||||
padding: 12px 16px;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #e0e8e0;
|
||||
margin: 0.6em 0;
|
||||
}
|
||||
|
||||
.markdown-body :deep(pre code) {
|
||||
background: none;
|
||||
padding: 0;
|
||||
color: #333;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.markdown-body :deep(blockquote) {
|
||||
margin: 0.5em 0;
|
||||
padding: 0.5em 1em;
|
||||
border-left: 3px solid var(--green-600, #2f8f68);
|
||||
background: #f1f8e9;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.markdown-body :deep(a) {
|
||||
color: var(--green-600, #2f8f68);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.markdown-body :deep(a:hover) {
|
||||
color: var(--green-900, #1b5e20);
|
||||
}
|
||||
|
||||
.markdown-body :deep(strong) {
|
||||
font-weight: 600;
|
||||
color: #222;
|
||||
}
|
||||
|
||||
.markdown-body :deep(hr) {
|
||||
border: none;
|
||||
border-top: 1px solid #e0e8e0;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.markdown-body :deep(table) {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin: 0.6em 0;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.markdown-body :deep(th),
|
||||
.markdown-body :deep(td) {
|
||||
border: 1px solid #d0d8d0;
|
||||
padding: 6px 10px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.markdown-body :deep(th) {
|
||||
background: #e8f5e9;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.markdown-body :deep(img) {
|
||||
max-width: 100%;
|
||||
border-radius: 4px;
|
||||
margin: 0.5em 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,210 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import MindElixir, { type MindElixirData, type MindElixirInstance } from "mind-elixir";
|
||||
import "mind-elixir/style.css";
|
||||
|
||||
/**
|
||||
* mind-elixir 封装:展示/编辑思维导图。
|
||||
* 节点着色约定(对比模式):绿=回忆命中,红=遗漏,蓝=额外。
|
||||
*/
|
||||
|
||||
export interface MindMapTreeNode {
|
||||
title: string;
|
||||
notes?: string;
|
||||
sourceType?: string;
|
||||
sourceId?: number;
|
||||
children?: MindMapTreeNode[];
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
/** 树数据(根节点) */
|
||||
tree: MindMapTreeNode | null;
|
||||
/** 是否可编辑 */
|
||||
editable?: boolean;
|
||||
/** 是否按 MATCHED/MISSED 标记着色 */
|
||||
colorByCompare?: boolean;
|
||||
/** 画布高度,如 "520px"、"60vh",默认 480px */
|
||||
height?: string;
|
||||
/** 节点可选择模式(点击节点触发 node-select 事件) */
|
||||
selectable?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 点击带溯源信息的节点 */
|
||||
(e: "node-click", node: { sourceType: string; sourceId: number }): void;
|
||||
/** 选择模式下点击节点,返回标题+路径 */
|
||||
(e: "node-select", node: { title: string; path: string; childCount: number }): void;
|
||||
}>();
|
||||
|
||||
const container = ref<HTMLElement | null>(null);
|
||||
let instance: MindElixirInstance | null = null;
|
||||
let nodeCounter = 0;
|
||||
/** 节点路径映射:elixir node id → { title, path, childCount } */
|
||||
let nodePathMap: Record<string, { title: string; path: string; childCount: number }> = {};
|
||||
|
||||
/** 递归构建节点路径映射 */
|
||||
const buildPathMap = (node: MindMapTreeNode, ancestors: string[]): { title: string; path: string; childCount: number } => {
|
||||
const title = node.title || "(未命名)";
|
||||
const path = [...ancestors, title].join(" / ");
|
||||
const childCount = (node.children || []).reduce((sum, c) => sum + 1 + countAllDescendants(c), 0);
|
||||
return { title, path, childCount };
|
||||
};
|
||||
|
||||
const countAllDescendants = (node: MindMapTreeNode): number => {
|
||||
return (node.children || []).reduce((sum, c) => sum + 1 + countAllDescendants(c), 0);
|
||||
};
|
||||
|
||||
const COLOR_MATCHED = { background: "#c8e6c9", color: "#1b5e20" };
|
||||
const COLOR_MISSED = { background: "#ffcdd2", color: "#b71c1c" };
|
||||
|
||||
const compareStatus = (notes?: string): "MATCHED" | "MISSED" | null => {
|
||||
if (!notes) return null;
|
||||
if (notes.startsWith("MATCHED|")) return "MATCHED";
|
||||
if (notes.startsWith("MISSED|")) return "MISSED";
|
||||
return null;
|
||||
};
|
||||
|
||||
const toElixirNode = (node: MindMapTreeNode, ancestors: string[] = []): any => {
|
||||
nodeCounter += 1;
|
||||
const elixirId = `n${nodeCounter}`;
|
||||
const result: any = {
|
||||
id: elixirId,
|
||||
topic: node.title || "(未命名)",
|
||||
children: (node.children || []).map((c) => toElixirNode(c, [...ancestors, node.title || "(未命名)"])),
|
||||
};
|
||||
// 记录路径映射
|
||||
if (props.selectable) {
|
||||
nodePathMap[elixirId] = buildPathMap(node, ancestors);
|
||||
}
|
||||
if (node.sourceType && node.sourceId != null) {
|
||||
result.hyperLink = "";
|
||||
result.tags = [node.sourceType === "REPORT" ? "报告" : node.sourceType === "FRAGMENT" ? "残片" : "应用"];
|
||||
result.sourceType = node.sourceType;
|
||||
result.sourceId = node.sourceId;
|
||||
}
|
||||
if (props.colorByCompare) {
|
||||
const status = compareStatus(node.notes);
|
||||
if (status === "MATCHED") {
|
||||
result.style = COLOR_MATCHED;
|
||||
} else if (status === "MISSED") {
|
||||
result.style = COLOR_MISSED;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const toElixirData = (tree: MindMapTreeNode): MindElixirData => {
|
||||
nodeCounter = 0;
|
||||
const rootTitle = tree.title || "思维导图";
|
||||
// register root node in path map so clicking it also works
|
||||
if (props.selectable) {
|
||||
nodePathMap["root"] = {
|
||||
title: rootTitle,
|
||||
path: rootTitle,
|
||||
childCount: (tree.children || []).reduce(
|
||||
(sum, c) => sum + 1 + countAllDescendants(c),
|
||||
0,
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
nodeData: {
|
||||
id: "root",
|
||||
topic: rootTitle,
|
||||
// pass root title as ancestor so child paths include it (e.g. "根 / 子节点")
|
||||
children: (tree.children || []).map((c) =>
|
||||
toElixirNode(c, [rootTitle]),
|
||||
),
|
||||
},
|
||||
} as MindElixirData;
|
||||
};
|
||||
|
||||
/** 从 mind-elixir 数据导出缩进大纲文本(与后端 MindMapTreeTool.parseOutline 格式一致) */
|
||||
const toOutline = (): string => {
|
||||
if (!instance) return "";
|
||||
const data = instance.getData();
|
||||
const lines: string[] = [data.nodeData.topic || "思维导图"];
|
||||
const walk = (node: any, level: number) => {
|
||||
lines.push(`${" ".repeat(level)}- ${node.topic || ""}`);
|
||||
(node.children || []).forEach((c: any) => walk(c, level + 1));
|
||||
};
|
||||
(data.nodeData.children || []).forEach((c: any) => walk(c, 1));
|
||||
return lines.join("\n");
|
||||
};
|
||||
|
||||
defineExpose({ toOutline });
|
||||
|
||||
const render = () => {
|
||||
if (!container.value || !props.tree) return;
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
instance = null;
|
||||
}
|
||||
nodePathMap = {};
|
||||
instance = new MindElixir({
|
||||
el: container.value,
|
||||
direction: MindElixir.SIDE,
|
||||
draggable: !!props.editable,
|
||||
editable: !!props.editable,
|
||||
contextMenu: !!props.editable,
|
||||
toolBar: true,
|
||||
keypress: !!props.editable,
|
||||
});
|
||||
instance.init(toElixirData(props.tree));
|
||||
|
||||
// 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
|
||||
// to hook into node clicks for both selectable and source-navigation modes.
|
||||
const origSelectNode = instance.selectNode.bind(instance);
|
||||
instance.selectNode = function (el: any, fireEvent?: boolean) {
|
||||
origSelectNode(el, fireEvent);
|
||||
if (!el?.nodeObj) return;
|
||||
const nodeData = el.nodeObj;
|
||||
// selectable mode → emit node-select with title/path/childCount
|
||||
if (props.selectable && nodeData?.id) {
|
||||
const info = nodePathMap[nodeData.id];
|
||||
if (info) {
|
||||
emit("node-select", info);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// source navigation → emit node-click with sourceType/sourceId
|
||||
if (nodeData?.sourceType && nodeData?.sourceId != null) {
|
||||
emit("node-click", {
|
||||
sourceType: String(nodeData.sourceType),
|
||||
sourceId: Number(nodeData.sourceId),
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.tree, props.editable, props.colorByCompare],
|
||||
() => render(),
|
||||
{ deep: false },
|
||||
);
|
||||
|
||||
onMounted(() => render());
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
instance = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mind-map-viewer" ref="container" :style="{ height: height || '480px' }"></div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.mind-map-viewer {
|
||||
width: 100%;
|
||||
border: 1px solid var(--border-soft, #e0e0e0);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: #fbfefc;
|
||||
}
|
||||
</style>
|
||||
@@ -20,6 +20,7 @@
|
||||
type="success"
|
||||
plain
|
||||
class="logout-btn"
|
||||
:loading="loggingOut"
|
||||
@click="handleLogout"
|
||||
>
|
||||
退出登录
|
||||
@@ -28,7 +29,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, ref } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import router from "@/router";
|
||||
@@ -38,18 +39,26 @@ const route = useRoute();
|
||||
const isLoginRoute = computed(() => route.path === "/login");
|
||||
const showBackButton = computed(() => route.path !== "/login" && route.path !== "/welcome");
|
||||
const pageTitle = computed(() => route.meta?.title as string | undefined);
|
||||
const loggingOut = ref(false);
|
||||
|
||||
const handleLogout = async () => {
|
||||
if (loggingOut.value) return;
|
||||
loggingOut.value = true;
|
||||
try {
|
||||
try {
|
||||
await logout();
|
||||
} catch {
|
||||
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
|
||||
} finally {
|
||||
}
|
||||
localStorage.removeItem("isLoggedIn");
|
||||
ElMessage.success("已退出登录");
|
||||
await router.push("/login");
|
||||
} finally {
|
||||
loggingOut.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({ isLoginRoute, showBackButton, pageTitle, loggingOut, handleLogout });
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
+100
-27
@@ -1,17 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import request from "@/utils/request";
|
||||
import { useRouter } from "vue-router";
|
||||
import {
|
||||
getReviewTaskStats,
|
||||
type ReviewTaskStats,
|
||||
} from "@/api/review";
|
||||
|
||||
interface ReviewTask {
|
||||
taskNum: string;
|
||||
taskName: string;
|
||||
reportCount: number | string;
|
||||
fragmentCount: number | string;
|
||||
effectiveTime: number | string;
|
||||
}
|
||||
const router = useRouter();
|
||||
|
||||
const loading = ref(false);
|
||||
const tasks = ref<ReviewTask[]>([]);
|
||||
const tasks = ref<ReviewTaskStats[]>([]);
|
||||
|
||||
const summary = computed(() => ({
|
||||
totalTasks: tasks.value.length,
|
||||
@@ -19,22 +17,30 @@ const summary = computed(() => ({
|
||||
totalFragments: tasks.value.reduce((acc, item) => acc + Number(item.fragmentCount || 0), 0),
|
||||
}));
|
||||
|
||||
const formatEffectiveTime = (seconds: number | string): string => {
|
||||
const s = Number(seconds);
|
||||
if (!s || s <= 0) return "0分钟";
|
||||
const hours = Math.floor(s / 3600);
|
||||
const minutes = Math.floor((s % 3600) / 60);
|
||||
if (hours > 0) return `${hours}小时${minutes}分钟`;
|
||||
return `${minutes}分钟`;
|
||||
};
|
||||
|
||||
const loadTasks = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await request.get("/tasks", { pageSize: 100, pageNum: 1 });
|
||||
tasks.value = (res?.data?.records || []).map((item: any) => ({
|
||||
taskNum: item.taskNum,
|
||||
taskName: item.taskName,
|
||||
reportCount: item.reportCount ?? "-",
|
||||
fragmentCount: item.fragmentCount ?? "-",
|
||||
effectiveTime: item.effectiveTime ?? "-",
|
||||
}));
|
||||
const res = await getReviewTaskStats();
|
||||
tasks.value = res?.data || [];
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openTaskReview = (row: ReviewTaskStats) => {
|
||||
if (!row.taskNum) return;
|
||||
router.push(`/review/detail/task/${encodeURIComponent(row.taskNum)}`);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadTasks();
|
||||
});
|
||||
@@ -44,7 +50,7 @@ onMounted(() => {
|
||||
<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>
|
||||
<el-button type="success" plain :loading="loading" @click="loadTasks">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="summary-grid">
|
||||
@@ -62,14 +68,43 @@ onMounted(() => {
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<article class="surface-card table-card">
|
||||
<el-table v-loading="loading" :data="tasks" stripe>
|
||||
<el-table-column prop="taskName" label="任务名" min-width="180" />
|
||||
<el-table-column prop="effectiveTime" label="累计有效学习时长" min-width="150" />
|
||||
<el-table-column prop="reportCount" label="学习报告数" min-width="120" />
|
||||
<el-table-column prop="fragmentCount" label="学习残片数" min-width="120" />
|
||||
</el-table>
|
||||
<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"
|
||||
>
|
||||
<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">
|
||||
<el-button
|
||||
text
|
||||
type="success"
|
||||
size="small"
|
||||
@click="openTaskReview(row)"
|
||||
>
|
||||
查看记录
|
||||
</el-button>
|
||||
<el-button
|
||||
class="recall-button"
|
||||
type="success"
|
||||
size="small"
|
||||
@click="router.push(`/review/recall/${row.taskNum}`)"
|
||||
>
|
||||
回忆复习
|
||||
</el-button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<el-empty v-if="!loading && tasks.length === 0" description="暂无复习任务" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -108,8 +143,40 @@ onMounted(() => {
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.table-card {
|
||||
padding: 10px;
|
||||
.task-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.task-card {
|
||||
padding: 14px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.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: space-between;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
@@ -117,4 +184,10 @@ onMounted(() => {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.task-actions .recall-button {
|
||||
order: -1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
+198
-49
@@ -1,21 +1,47 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { getReportDetail, getFragmentDetail, getTaskReview, type ReviewFeedItem } from "@/api/review";
|
||||
import {
|
||||
getFragmentDetail,
|
||||
getReportDetail,
|
||||
getTaskReview,
|
||||
type ReviewFeedItem,
|
||||
} from "@/api/review";
|
||||
import { getSessionDetail } from "@/api/studySessions";
|
||||
import { updateFragments } from "@/api/reportFragments";
|
||||
import { ElMessage } from "element-plus";
|
||||
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const contentType = computed(() => route.params.type as string);
|
||||
const contentId = computed(() => Number(route.params.id));
|
||||
/** 直接进入回忆复习页,节点匹配交给目标页加载后处理 */
|
||||
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 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("");
|
||||
const sourceTypeLabel = ref("");
|
||||
const taskNum = ref("");
|
||||
|
||||
// 当前会话信息
|
||||
const isEditing = ref(false);
|
||||
const editContent = ref("");
|
||||
const saving = ref(false);
|
||||
|
||||
const sessionInfo = ref<{
|
||||
taskName: string;
|
||||
sessionNum: string;
|
||||
@@ -25,7 +51,6 @@ const sessionInfo = ref<{
|
||||
startTime?: string;
|
||||
} | null>(null);
|
||||
|
||||
// 该任务下的所有学习记录(按 session 分组)
|
||||
const taskSessions = ref<{
|
||||
sessionNum: string;
|
||||
startTime: string;
|
||||
@@ -33,7 +58,7 @@ const taskSessions = ref<{
|
||||
fragments: ReviewFeedItem[];
|
||||
}[]>([]);
|
||||
|
||||
const formatDuration = (seconds: number): string => {
|
||||
const formatDuration = (seconds?: number): string => {
|
||||
if (seconds == null) return "-";
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
@@ -43,47 +68,16 @@ const formatDuration = (seconds: number): string => {
|
||||
return `${s}秒`;
|
||||
};
|
||||
|
||||
const loadDetail = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
let res;
|
||||
if (contentType.value === "report") {
|
||||
res = await getReportDetail(contentId.value);
|
||||
sourceTypeLabel.value = "学习报告";
|
||||
} else {
|
||||
res = await getFragmentDetail(contentId.value);
|
||||
sourceTypeLabel.value = "学习残片";
|
||||
}
|
||||
const data = res?.data;
|
||||
content.value = data?.content || "";
|
||||
|
||||
const sessionNum = data?.sessionNum;
|
||||
if (sessionNum) {
|
||||
try {
|
||||
const sessionRes = await getSessionDetail(sessionNum);
|
||||
const info = sessionRes?.data;
|
||||
sessionInfo.value = info || null;
|
||||
taskNum.value = info?.taskNum || "";
|
||||
|
||||
// 加载该任务下的所有报告和残片
|
||||
if (info?.taskNum) {
|
||||
await loadTaskHistory(info.taskNum, sessionNum);
|
||||
}
|
||||
} catch {
|
||||
// 非关键数据
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
const formatRatio = (ratio?: number): string => {
|
||||
if (ratio == null) return "-";
|
||||
return `${(ratio * 100).toFixed(1)}%`;
|
||||
};
|
||||
|
||||
const loadTaskHistory = async (tn: string, currentSessionNum: string) => {
|
||||
const loadTaskHistory = async (tn: string) => {
|
||||
try {
|
||||
const res = await getTaskReview(tn);
|
||||
const items: ReviewFeedItem[] = res?.data || [];
|
||||
|
||||
// 按 sessionNum 分组
|
||||
const map = new Map<string, { report: ReviewFeedItem | null; fragments: ReviewFeedItem[]; startTime: string }>();
|
||||
for (const item of items) {
|
||||
const entry = map.get(item.sessionNum) || { report: null, fragments: [], startTime: item.createdTime };
|
||||
@@ -110,13 +104,113 @@ const loadTaskHistory = async (tn: string, currentSessionNum: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const loadDetail = async () => {
|
||||
loading.value = true;
|
||||
isEditing.value = false;
|
||||
editContent.value = "";
|
||||
content.value = "";
|
||||
sourceTypeLabel.value = "";
|
||||
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);
|
||||
sourceTypeLabel.value = "学习报告";
|
||||
} else {
|
||||
res = await getFragmentDetail(contentId.value);
|
||||
sourceTypeLabel.value = "学习残片";
|
||||
}
|
||||
const data = res?.data;
|
||||
content.value = data?.content || "";
|
||||
|
||||
const sessionNum = data?.sessionNum;
|
||||
if (sessionNum) {
|
||||
try {
|
||||
const sessionRes = await getSessionDetail(sessionNum);
|
||||
const info = sessionRes?.data;
|
||||
sessionInfo.value = info || null;
|
||||
taskNum.value = info?.taskNum || "";
|
||||
|
||||
if (info?.taskNum) {
|
||||
await loadTaskHistory(info.taskNum);
|
||||
}
|
||||
} catch {
|
||||
// 非关键数据
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const goToDetail = (type: string, id: number) => {
|
||||
router.push(`/review/detail/${type}/${id}`);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
const enterEdit = () => {
|
||||
editContent.value = content.value;
|
||||
isEditing.value = true;
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
isEditing.value = false;
|
||||
editContent.value = "";
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editContent.value.trim()) {
|
||||
ElMessage.warning("内容不能为空");
|
||||
return;
|
||||
}
|
||||
if (editContent.value === content.value) {
|
||||
isEditing.value = false;
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const res = await updateFragments(contentId.value, editContent.value);
|
||||
if (res?.code === 200) {
|
||||
content.value = editContent.value;
|
||||
isEditing.value = false;
|
||||
if (taskNum.value) {
|
||||
await loadTaskHistory(taskNum.value);
|
||||
}
|
||||
ElMessage.success("保存成功");
|
||||
} else {
|
||||
ElMessage.error(res?.message || "保存失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "请求失败");
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [route.params.type, route.params.id, route.params.taskNum],
|
||||
() => {
|
||||
if (!isTaskMode.value) {
|
||||
activeType.value = undefined;
|
||||
activeId.value = undefined;
|
||||
}
|
||||
loadDetail();
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -137,14 +231,49 @@ onMounted(() => {
|
||||
<span v-if="sessionInfo?.startTime" class="meta-time">
|
||||
学习时间:{{ sessionInfo.startTime?.replace("T", " ")?.substring(0, 16) }}
|
||||
</span>
|
||||
<el-button
|
||||
v-if="contentType === 'fragment' && !isEditing"
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="enterEdit"
|
||||
>
|
||||
编辑
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="taskNum"
|
||||
type="success"
|
||||
size="small"
|
||||
@click="goToRecall"
|
||||
>
|
||||
回忆复习
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-if="sessionInfo" class="session-stats">
|
||||
<span>实际:{{ formatDuration(sessionInfo.actualTime) }}</span>
|
||||
<span>有效:{{ formatDuration(sessionInfo.effectiveTime) }}</span>
|
||||
<span>效率:{{ formatRatio(sessionInfo.effectivenessRatio) }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 编辑模式 -->
|
||||
<div v-if="isEditing" class="edit-area">
|
||||
<el-input
|
||||
v-model="editContent"
|
||||
type="textarea"
|
||||
:rows="6"
|
||||
placeholder="请输入学习内容"
|
||||
/>
|
||||
<div class="edit-actions">
|
||||
<el-button size="small" @click="cancelEdit">取消</el-button>
|
||||
<el-button type="success" size="small" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 只读模式 -->
|
||||
<template v-else>
|
||||
<div class="content-body" v-if="content">
|
||||
<p v-for="(line, idx) in content.split('\n')" :key="idx">
|
||||
{{ line || " " }}
|
||||
</p>
|
||||
<MarkdownRenderer :content="content" />
|
||||
</div>
|
||||
<div v-else class="empty-content">暂无内容</div>
|
||||
</template>
|
||||
</article>
|
||||
|
||||
<!-- 该任务下的所有学习记录 -->
|
||||
@@ -176,13 +305,13 @@ onMounted(() => {
|
||||
|
||||
<div class="session-fragments" v-if="session.fragments.length > 0">
|
||||
<span
|
||||
v-for="f in session.fragments"
|
||||
v-for="(f, idx) in session.fragments"
|
||||
:key="f.id"
|
||||
class="clickable-text"
|
||||
:class="{ active: contentType === 'fragment' && f.id === contentId }"
|
||||
@click="goToDetail('fragment', f.id)"
|
||||
>
|
||||
<span class="label-tag fragment-tag">残片</span>
|
||||
<span class="label-tag fragment-tag">残片{{ idx + 1 }}</span>
|
||||
{{ f.content.length > 150 ? f.content.substring(0, 150) + "..." : f.content }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -213,6 +342,15 @@ onMounted(() => {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.session-stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 14px;
|
||||
margin: -6px 0 16px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.meta-task-name {
|
||||
font-weight: 600;
|
||||
color: var(--green-800);
|
||||
@@ -342,4 +480,15 @@ onMounted(() => {
|
||||
color: #b8860b;
|
||||
}
|
||||
|
||||
.edit-area {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -0,0 +1,908 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
findNode,
|
||||
getStandardMindMap,
|
||||
regenerateStandardMindMap,
|
||||
recallCompare,
|
||||
updateStandardMindMap,
|
||||
listRecallRecords,
|
||||
type StandardMindMap,
|
||||
type RecallRecord,
|
||||
} from "@/api/standardMindMap";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
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 regenerating = ref(false);
|
||||
const regeneratingSeconds = ref(0);
|
||||
let regeneratingTimer: ReturnType<typeof setInterval> | null = null;
|
||||
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);
|
||||
|
||||
// 回忆输入(思维导图形式)
|
||||
const recallTree = ref<MindMapTreeNode | null>(null);
|
||||
const recallViewer = ref<InstanceType<typeof MindMapViewer> | null>(null);
|
||||
|
||||
// 标准导图展开/折叠(默认折叠,防止剧透)
|
||||
const standardExpanded = ref(false);
|
||||
|
||||
// 编辑标准导图
|
||||
const editingStandard = ref(false);
|
||||
const editOutline = ref("");
|
||||
const savingStandard = ref(false);
|
||||
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>(() => {
|
||||
if (!standard.value?.content) return null;
|
||||
try {
|
||||
return JSON.parse(standard.value.content) as MindMapTreeNode;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
// 对比结果树(带 MATCHED/MISSED 标注)
|
||||
const compareTree = computed<MindMapTreeNode | null>(() => {
|
||||
return (lastResult.value?.matchedTree as MindMapTreeNode) || null;
|
||||
});
|
||||
|
||||
// 点击着色节点跳转原文
|
||||
const goToNodeSource = (node: { sourceType: string; sourceId: number }) => {
|
||||
if (node.sourceType === "REPORT" || node.sourceType === "FRAGMENT") {
|
||||
router.push(`/review/detail/${node.sourceType.toLowerCase()}/${node.sourceId}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 格式化覆盖率
|
||||
const ratioPercent = computed(() => {
|
||||
if (!lastResult.value?.recallRatio) return "0%";
|
||||
return `${(lastResult.value.recallRatio * 100).toFixed(1)}%`;
|
||||
});
|
||||
|
||||
/** 回忆导图的初始根节点(只给根主题,内容凭记忆补全) */
|
||||
const buildEmptyRecallTree = (): MindMapTreeNode => ({
|
||||
title: standard.value?.title || `任务 ${taskNum.value}`,
|
||||
children: [],
|
||||
});
|
||||
|
||||
/** 将缩进大纲文本解析为树(兼容 "- " 前缀与 ├└│─ 等装饰符) */
|
||||
const parseOutlineToTree = (text: string): MindMapTreeNode | null => {
|
||||
const lines = (text || "").split(/\r?\n/).filter((l) => l.trim().length > 0);
|
||||
if (lines.length === 0) return null;
|
||||
const cleanTitle = (l: string) => l.replace(/^[\s│├└┌┐┘┬┴┼─\-*•]+/, "").trim();
|
||||
const indentOf = (l: string) => {
|
||||
const match = l.match(/^[\s│├└┌─]*/);
|
||||
const prefix = match ? match[0] : "";
|
||||
return Math.max(1, Math.floor(prefix.replace(/[^\s]/g, " ").length / 2));
|
||||
};
|
||||
const root: MindMapTreeNode = { title: cleanTitle(lines[0]), children: [] };
|
||||
const stack: { node: MindMapTreeNode; level: number }[] = [{ node: root, level: 0 }];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const level = indentOf(lines[i]);
|
||||
const node: MindMapTreeNode = { title: cleanTitle(lines[i]), children: [] };
|
||||
while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();
|
||||
stack[stack.length - 1].node.children!.push(node);
|
||||
stack.push({ node, level });
|
||||
}
|
||||
return root;
|
||||
};
|
||||
|
||||
// 加载数据
|
||||
const loadData = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await getStandardMindMap(taskNum.value);
|
||||
standard.value = res?.data || null;
|
||||
if (focusContent.value && standard.value) {
|
||||
try {
|
||||
const nodeRes = await findNode(taskNum.value, focusContent.value.substring(0, 500));
|
||||
const data = nodeRes?.data;
|
||||
if (data?.path) {
|
||||
focusPath.value = data.path;
|
||||
}
|
||||
} catch {
|
||||
// 匹配失败时仍可进入回忆页
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
standard.value = null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (!recallTree.value) {
|
||||
recallTree.value = buildEmptyRecallTree();
|
||||
}
|
||||
// 若从 URL 带了 focusPath,自动设置回忆导图根节点
|
||||
if (focusPath.value && standard.value?.content) {
|
||||
try {
|
||||
const tree = JSON.parse(standard.value.content) as MindMapTreeNode;
|
||||
const match = findNodeByPath(tree, focusPath.value);
|
||||
if (match) {
|
||||
recallTree.value = { title: match.title, children: [] };
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const findNodeByPath = (node: MindMapTreeNode, path: string): MindMapTreeNode | null => {
|
||||
const parts = path.split(" / ");
|
||||
let current: MindMapTreeNode | null = node;
|
||||
for (let i = 0; i < parts.length && current; i++) {
|
||||
if (current.title === parts[i] && i === parts.length - 1) return current;
|
||||
const child: MindMapTreeNode | undefined = (current.children || []).find((c) => c.title === parts[i]);
|
||||
current = child || null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// 重新生成(防抖 + 用户编辑时弹窗选模式)
|
||||
const handleRegenerate = async () => {
|
||||
// 防抖:正在生成中跳过
|
||||
if (regenerating.value) return;
|
||||
|
||||
let mode: "full" | "incremental" = "full";
|
||||
|
||||
// 如果用户编辑过,弹窗选择生成模式
|
||||
if (standard.value?.generator === "USER" || standard.value?.generator === "USER_MERGE") {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
"检测到您已编辑过标准思维导图,请选择重新生成方式:",
|
||||
"重新生成",
|
||||
{
|
||||
confirmButtonText: "全量重新生成",
|
||||
cancelButtonText: "增量更新(保留编辑)",
|
||||
type: "warning",
|
||||
distinguishCancelAndClose: true,
|
||||
}
|
||||
);
|
||||
// confirm → 全量(保持 mode = "full")
|
||||
} catch (e: any) {
|
||||
if (e === "cancel" || e?.toString()?.includes("cancel")) {
|
||||
mode = "incremental";
|
||||
} else {
|
||||
return; // 点 X 关闭 → 不做操作
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 未编辑过的简单确认
|
||||
try {
|
||||
await ElMessageBox.confirm("重新生成将从学习数据中重新生成标准思维导图,确定?", "提示", {
|
||||
confirmButtonText: "确定",
|
||||
cancelButtonText: "取消",
|
||||
type: "info",
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 开始生成
|
||||
regenerating.value = true;
|
||||
regeneratingSeconds.value = 0;
|
||||
regeneratingTimer = setInterval(() => { regeneratingSeconds.value++; }, 1000);
|
||||
try {
|
||||
const res = await regenerateStandardMindMap(taskNum.value, mode);
|
||||
standard.value = res?.data || null;
|
||||
ElMessage.success(mode === "incremental" ? "标准思维导图已增量更新" : "标准思维导图已重新生成");
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "重新生成失败");
|
||||
} finally {
|
||||
regenerating.value = false;
|
||||
if (regeneratingTimer) { clearInterval(regeneratingTimer); regeneratingTimer = null; }
|
||||
}
|
||||
};
|
||||
|
||||
// 提交回忆对比
|
||||
const handleRecallCompare = async () => {
|
||||
const outline = recallViewer.value?.toOutline() || "";
|
||||
if (outline.split(/\r?\n/).filter((l) => l.trim()).length <= 1) {
|
||||
ElMessage.warning("请先在回忆导图中添加节点(选中节点后按 Tab 加子节点)");
|
||||
return;
|
||||
}
|
||||
comparing.value = true;
|
||||
comparingSeconds.value = 0;
|
||||
comparingTimer = setInterval(() => { comparingSeconds.value++; }, 1000);
|
||||
try {
|
||||
const res = await recallCompare(taskNum.value, outline, focusPath.value || undefined);
|
||||
standard.value = res?.data || null;
|
||||
hasCompared.value = true;
|
||||
// 解析对比结果
|
||||
if (standard.value) {
|
||||
const recordRes = await listRecallRecords(taskNum.value);
|
||||
const records: RecallRecord[] = recordRes?.data || [];
|
||||
if (records.length > 0) {
|
||||
const latest = records[0];
|
||||
try {
|
||||
lastResult.value = JSON.parse(latest.compareResult);
|
||||
} catch {
|
||||
lastResult.value = null;
|
||||
}
|
||||
historyRecords.value = records;
|
||||
}
|
||||
}
|
||||
ElMessage.success("回忆对比完成");
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "对比失败");
|
||||
} finally {
|
||||
comparing.value = false;
|
||||
if (comparingTimer) { clearInterval(comparingTimer); comparingTimer = null; }
|
||||
}
|
||||
};
|
||||
|
||||
// 清空重写
|
||||
const resetRecall = () => {
|
||||
recallTree.value = buildEmptyRecallTree();
|
||||
};
|
||||
|
||||
// 返回完整标准导图,重新选择复习范围
|
||||
const resetComparison = () => {
|
||||
lastResult.value = null;
|
||||
hasCompared.value = false;
|
||||
focusPath.value = "";
|
||||
recallTree.value = buildEmptyRecallTree();
|
||||
standardExpanded.value = true;
|
||||
editingStandard.value = false;
|
||||
};
|
||||
|
||||
// 编辑标准导图
|
||||
const startEditStandard = () => {
|
||||
editOutline.value = standard.value?.outline || "";
|
||||
editingStandard.value = true;
|
||||
};
|
||||
|
||||
const saveStandardEdit = async () => {
|
||||
if (!editOutline.value.trim()) {
|
||||
ElMessage.warning("大纲不可为空");
|
||||
return;
|
||||
}
|
||||
savingStandard.value = true;
|
||||
try {
|
||||
const res = await updateStandardMindMap(taskNum.value, editOutline.value);
|
||||
standard.value = res?.data || null;
|
||||
editingStandard.value = false;
|
||||
ElMessage.success("标准思维导图已更新");
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "保存失败");
|
||||
} finally {
|
||||
savingStandard.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 从导图编辑器导出大纲并保存
|
||||
const saveStandardEditFromViewer = async () => {
|
||||
const outline = editViewer.value?.toOutline() || "";
|
||||
if (!outline.trim()) {
|
||||
ElMessage.warning("导图内容不可为空");
|
||||
return;
|
||||
}
|
||||
editOutline.value = outline;
|
||||
await saveStandardEdit();
|
||||
};
|
||||
|
||||
const cancelStandardEdit = () => {
|
||||
editingStandard.value = false;
|
||||
editOutline.value = "";
|
||||
};
|
||||
|
||||
// 查看回忆历史
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
// 选择历史记录查看结果
|
||||
const selectHistoryRecord = (record: RecallRecord) => {
|
||||
try {
|
||||
lastResult.value = JSON.parse(record.compareResult);
|
||||
// 将历史回忆内容还原到导图输入区
|
||||
const tree = parseOutlineToTree(record.recallContent);
|
||||
if (tree) recallTree.value = tree;
|
||||
hasCompared.value = true;
|
||||
focusPath.value = record.focusPath || "";
|
||||
standardExpanded.value = true;
|
||||
} catch {
|
||||
ElMessage.error("解析对比记录失败");
|
||||
}
|
||||
};
|
||||
|
||||
// 跳转到复习详情
|
||||
const goToReviewDetail = (sourceType: string, sourceId: number) => {
|
||||
router.push(`/review/detail/${sourceType.toLowerCase()}/${sourceId}`);
|
||||
};
|
||||
|
||||
// 获取遗漏项列表
|
||||
const missedItems = computed(() => {
|
||||
if (!lastResult.value?.matchedTree) return [];
|
||||
const items: { title: string; sourceType: string; sourceId: number }[] = [];
|
||||
const walk = (node: any) => {
|
||||
const notes = node.notes || "";
|
||||
if (notes.startsWith("MISSED|")) {
|
||||
items.push({
|
||||
title: node.title || "",
|
||||
sourceType: node.sourceType || "",
|
||||
sourceId: node.sourceId,
|
||||
});
|
||||
}
|
||||
(node.children || []).forEach(walk);
|
||||
};
|
||||
walk(lastResult.value.matchedTree);
|
||||
return items;
|
||||
});
|
||||
|
||||
// 额外节点列表
|
||||
const extraNodes = computed(() => {
|
||||
const raw = lastResult.value?.extraNodes || [];
|
||||
// 兼容字符串数组和对象数组两种格式
|
||||
return raw.map((item: any) => typeof item === "string" ? { title: item } : item);
|
||||
});
|
||||
|
||||
// 节点选择回调(selectable 模式下点击节点)
|
||||
const handleNodeSelect = (node: { title: string; path: string; childCount: number }) => {
|
||||
selectedNodeInfo.value = node;
|
||||
focusConfirmVisible.value = true;
|
||||
};
|
||||
|
||||
// 确认以选中节点为起点
|
||||
const confirmFocus = () => {
|
||||
if (selectedNodeInfo.value) {
|
||||
focusPath.value = selectedNodeInfo.value.path;
|
||||
recallTree.value = {
|
||||
title: selectedNodeInfo.value.title,
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
focusConfirmVisible.value = false;
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadData();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="recall-page" v-loading="loading">
|
||||
<!-- 顶部操作栏 -->
|
||||
<div class="page-header">
|
||||
<h2>回忆复习</h2>
|
||||
<el-button :loading="historyLoading" @click="loadHistory">
|
||||
{{ showHistory ? "收起历史" : "历史记录" }}
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 起点节点指示 -->
|
||||
<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="resetComparison">重选节点</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 节点选择确认弹窗 -->
|
||||
<el-dialog v-model="focusConfirmVisible" title="确认复习起点" width="400px">
|
||||
<p v-if="selectedNodeInfo" class="focus-confirm-text">
|
||||
以 「<strong>{{ selectedNodeInfo.title }}</strong>」 为起点,
|
||||
复习该知识点下的 <strong>{{ selectedNodeInfo.childCount }}</strong> 个子知识点?
|
||||
</p>
|
||||
<template #footer>
|
||||
<el-button @click="focusConfirmVisible = false">取消</el-button>
|
||||
<el-button type="success" @click="confirmFocus">确定</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 统计卡片 -->
|
||||
<div class="stats-card surface-card" v-if="hasCompared && lastResult">
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">回忆覆盖率</span>
|
||||
<strong class="stat-value highlight">{{ ratioPercent }}</strong>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">✅ 回忆命中</span>
|
||||
<strong class="stat-value matched">{{ lastResult.matchedCount }}</strong>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">❌ 遗漏</span>
|
||||
<strong class="stat-value missed">{{ lastResult.missedCount }}</strong>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">➕ 额外</span>
|
||||
<strong class="stat-value extra">{{ lastResult.extraCount }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 回忆历史 -->
|
||||
<article class="surface-card" v-if="showHistory">
|
||||
<h3>回忆历史</h3>
|
||||
<div v-if="historyRecords.length > 0" class="history-list">
|
||||
<div
|
||||
v-for="record in historyRecords"
|
||||
:key="record.id"
|
||||
class="history-item"
|
||||
@click="selectHistoryRecord(record)"
|
||||
>
|
||||
<span class="history-time">{{ record.createdTime?.replace("T", " ")?.substring(0, 16) }}</span>
|
||||
<el-tag v-if="record.focusPath" size="small" type="success" effect="plain" class="session-badge" :title="record.focusPath">节点</el-tag>
|
||||
<el-tag v-else size="small" type="info" effect="plain" class="session-badge">全部</el-tag>
|
||||
<span class="history-ratio">覆盖率 {{ (record.recallRatio * 100).toFixed(1) }}%</span>
|
||||
<span class="history-detail">✅{{ record.matchedCount }} ❌{{ record.missedCount }} ➕{{ record.extraCount }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else description="暂无回忆记录" :image-size="48" />
|
||||
</article>
|
||||
|
||||
<!-- 折叠时引导:告知用户展开标准导图 -->
|
||||
<div v-if="!focusPath && !hasCompared && !standardExpanded" class="start-guide surface-card">
|
||||
<p>展开下方「标准思维导图」后,可点击节点选择复习起点,然后在此凭记忆补全知识点。</p>
|
||||
</div>
|
||||
|
||||
<!-- 回忆输入:可编辑思维导图 -->
|
||||
<article class="surface-card recall-panel">
|
||||
<div class="panel-header">
|
||||
<h3>🧠 你的回忆</h3>
|
||||
<div class="panel-actions">
|
||||
<el-button type="success" :loading="comparing" @click="handleRecallCompare">
|
||||
提交对比
|
||||
</el-button>
|
||||
<el-button v-if="hasCompared" @click="resetRecall">
|
||||
清空重写
|
||||
</el-button>
|
||||
</div>
|
||||
<p v-if="comparing" class="ai-waiting">
|
||||
<template v-if="comparingSeconds < 3">正在提交 AI 任务…</template>
|
||||
<template v-else-if="comparingSeconds < 60">AI 对比分析中,已等待 {{ comparingSeconds }} 秒,请稍候…</template>
|
||||
<template v-else-if="comparingSeconds < 180">内容较多,AI 正在深入分析,已等待 {{ comparingSeconds }} 秒…</template>
|
||||
<template v-else>即将完成,已等待 {{ comparingSeconds }} 秒,请耐心等待…</template>
|
||||
</p>
|
||||
</div>
|
||||
<p class="panel-hint">
|
||||
凭记忆在导图上补全该任务的知识点:选中节点后 Tab 加子节点、Enter 加同级节点、双击修改文字。
|
||||
</p>
|
||||
<MindMapViewer ref="recallViewer" :tree="recallTree" :editable="true" height="60vh" />
|
||||
</article>
|
||||
|
||||
<!-- 标准导图(含对比着色) -->
|
||||
<article class="surface-card standard-panel">
|
||||
<div class="panel-header">
|
||||
<h3>
|
||||
{{ hasCompared ? '📖 标准思维导图(对比结果)' : '📖 标准思维导图' }}
|
||||
</h3>
|
||||
<div class="panel-actions">
|
||||
<el-button
|
||||
v-if="hasCompared"
|
||||
type="success"
|
||||
@click="resetComparison"
|
||||
>
|
||||
返回完整导图
|
||||
</el-button>
|
||||
<el-button @click="standardExpanded = !standardExpanded">
|
||||
{{ standardExpanded ? "折叠" : "展开" }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="standardExpanded"
|
||||
type="warning"
|
||||
:loading="regenerating"
|
||||
@click="handleRegenerate"
|
||||
>
|
||||
重新生成
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="standardExpanded && !editingStandard"
|
||||
type="primary"
|
||||
@click="startEditStandard"
|
||||
>
|
||||
编辑
|
||||
</el-button>
|
||||
</div>
|
||||
<p v-if="regenerating" class="ai-waiting" style="margin-top: 4px; width: 100%;">
|
||||
<template v-if="regeneratingSeconds < 3">正在准备生成…</template>
|
||||
<template v-else>AI 正在生成中,已等待 {{ regeneratingSeconds }} 秒,请稍候…</template>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="!standard" class="empty-state">
|
||||
<el-empty description="暂无标准思维导图" :image-size="64">
|
||||
<el-button type="success" :loading="loading" @click="loadData">
|
||||
生成
|
||||
</el-button>
|
||||
</el-empty>
|
||||
</div>
|
||||
|
||||
<div v-else-if="editingStandard" class="edit-area">
|
||||
<p class="panel-hint">直接在导图上编辑(Tab 加子节点 / Enter 加同级 / 双击改文字),保存后生效。</p>
|
||||
<MindMapViewer ref="editViewer" :tree="standardTree" :editable="true" height="60vh" />
|
||||
<div class="edit-actions">
|
||||
<el-button @click="cancelStandardEdit">取消</el-button>
|
||||
<el-button type="success" :loading="savingStandard" @click="saveStandardEditFromViewer">
|
||||
保存更新
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="standardExpanded" class="standard-content">
|
||||
<div class="standard-meta">
|
||||
<span>来源:{{ standard.generator }}</span>
|
||||
<span>参考:{{ standard.sourceReportCount }} 份学习报告</span>
|
||||
</div>
|
||||
<p v-if="!focusPath && !hasCompared" class="select-hint">
|
||||
点击导图节点即可选择复习起点,选好后凭记忆在上方补全知识点。
|
||||
</p>
|
||||
<MindMapViewer
|
||||
v-if="standardTree"
|
||||
:tree="compareTree || standardTree"
|
||||
:color-by-compare="!!compareTree"
|
||||
:selectable="!editingStandard && !hasCompared"
|
||||
height="60vh"
|
||||
@node-select="handleNodeSelect"
|
||||
@node-click="goToNodeSource"
|
||||
/>
|
||||
<pre v-else class="standard-outline">{{ standard.outline || standard.content }}</pre>
|
||||
<p v-if="standard.summary" class="generator-info">{{ standard.summary }}</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="collapsed-hint">
|
||||
<p>标准导图已生成。展开后可查看或编辑。建议先凭记忆补全回忆导图再对照。</p>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<!-- 遗漏项 + 额外项详情 -->
|
||||
<div v-if="hasCompared && lastResult" class="detail-section">
|
||||
<!-- 遗漏项 -->
|
||||
<article class="surface-card" v-if="missedItems.length > 0">
|
||||
<h3>❌ 遗漏的知识点</h3>
|
||||
<div class="missed-list">
|
||||
<div v-for="(item, idx) in missedItems" :key="idx" class="missed-item">
|
||||
<span class="missed-title">{{ item.title }}</span>
|
||||
<el-button
|
||||
v-if="item.sourceType && item.sourceId"
|
||||
text
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="goToReviewDetail(item.sourceType, item.sourceId)"
|
||||
>
|
||||
查看原文
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<!-- 额外项 -->
|
||||
<article class="surface-card" v-if="extraNodes.length > 0">
|
||||
<h3>➕ 你额外回忆到的知识点</h3>
|
||||
<div class="extra-list">
|
||||
<div v-for="(item, idx) in extraNodes" :key="idx" class="extra-item">
|
||||
{{ item.title }}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.recall-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.page-header h2 {
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
color: var(--green-900);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.focus-confirm-text {
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
padding: 20px 22px;
|
||||
}
|
||||
|
||||
.surface-card h3 {
|
||||
margin: 0 0 8px;
|
||||
color: var(--green-900);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.stats-card {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
flex-wrap: wrap;
|
||||
background: linear-gradient(135deg, #f1f8e9 0%, #e8f5e9 100%);
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #666);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
display: block;
|
||||
font-size: 28px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.highlight { color: #2e7d32; }
|
||||
.matched { color: #2e7d32; }
|
||||
.missed { color: #c62828; }
|
||||
.extra { color: #1565c0; }
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-header h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.panel-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-hint {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary, #666);
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.ai-waiting {
|
||||
font-size: 13px;
|
||||
color: #e6a23c;
|
||||
margin: 4px 0 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.ai-waiting::before {
|
||||
content: "";
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid #f3d19e;
|
||||
border-top-color: #e6a23c;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.standard-meta {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #666);
|
||||
margin-bottom: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.standard-outline {
|
||||
white-space: pre-wrap;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--text-primary, #333);
|
||||
background: #fafafa;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border-soft, #e0e0e0);
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.generator-info {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #666);
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.collapsed-hint {
|
||||
color: var(--text-secondary, #666);
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.edit-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.detail-section {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 14px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.detail-section {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.detail-section h3 {
|
||||
margin: 0 0 12px;
|
||||
color: var(--green-900);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.missed-list,
|
||||
.extra-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.missed-item,
|
||||
.extra-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
background: #fafafa;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.missed-item {
|
||||
border-left: 3px solid #c62828;
|
||||
}
|
||||
|
||||
.extra-item {
|
||||
border-left: 3px solid #1565c0;
|
||||
}
|
||||
|
||||
.missed-title {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.history-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.history-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.history-item:hover {
|
||||
background: #f1f8e9;
|
||||
}
|
||||
|
||||
.history-time {
|
||||
color: var(--text-secondary, #666);
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.history-ratio {
|
||||
font-weight: 600;
|
||||
color: var(--green-800);
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.history-detail {
|
||||
color: var(--text-secondary, #666);
|
||||
}
|
||||
|
||||
/* 复习范围选择器 */
|
||||
.review-scope {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 22px;
|
||||
}
|
||||
|
||||
.scope-label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--green-800);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.session-badge {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.start-guide {
|
||||
padding: 14px 22px;
|
||||
background: linear-gradient(135deg, #fff8e1 0%, #fff3cd 100%);
|
||||
border-left: 4px solid #ffc107;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
color: #856404;
|
||||
}
|
||||
|
||||
.start-guide p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.select-hint {
|
||||
font-size: 13px;
|
||||
color: #856404;
|
||||
margin: 0 0 8px;
|
||||
padding: 6px 12px;
|
||||
background: #fdf6ec;
|
||||
border-radius: 4px;
|
||||
border-left: 3px solid #ffc107;
|
||||
}
|
||||
</style>
|
||||
+885
-35
File diff suppressed because it is too large
Load Diff
+533
-32
@@ -1,50 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import request from "@/utils/request";
|
||||
import router from "@/router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { getReviewTaskStatsByTask } from "@/api/review";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { applicationStatusOptions } from "@/utils/taskApplication";
|
||||
|
||||
import {
|
||||
getPriorityWeights,
|
||||
getTaskApplications,
|
||||
savePriorityWeights,
|
||||
updateTaskApplication,
|
||||
type PriorityWeights,
|
||||
type TaskApplication,
|
||||
} from "@/api/tasks";
|
||||
import { getUrlTitle } from "@/utils/fetchTitle";
|
||||
|
||||
interface TaskItem {
|
||||
title: string;
|
||||
description: string;
|
||||
materialURL: string;
|
||||
lastLearningStatus: string;
|
||||
materialUrl: string;
|
||||
priority: number | string;
|
||||
taskNum: string;
|
||||
taskId: number;
|
||||
reportCount: number;
|
||||
fragmentCount: number;
|
||||
effectiveTime: number;
|
||||
statsLoaded: boolean;
|
||||
sessionCount: number;
|
||||
todayEffectiveTime: number;
|
||||
weekEffectiveTime: number;
|
||||
avgEffectiveTime: number;
|
||||
avgEffectivenessRatio: number;
|
||||
}
|
||||
|
||||
const tasks = ref<TaskItem[]>([]);
|
||||
const selectedTaskId = ref<number | null>(null);
|
||||
const loading = ref(false);
|
||||
const currentPage = ref(1);
|
||||
const totalTasks = ref(0);
|
||||
const pageSize = 20;
|
||||
const taskApplications = ref<TaskApplication[]>([]);
|
||||
const applicationsLoading = ref(false);
|
||||
const appUrlTitles = ref<Record<number, string>>({});
|
||||
const updatingApplicationId = ref<number | null>(null);
|
||||
const removingTask = ref(false);
|
||||
const weightsLoading = ref(false);
|
||||
|
||||
const selectedTask = computed(() =>
|
||||
tasks.value.find((item) => item.taskId === selectedTaskId.value) || null
|
||||
);
|
||||
|
||||
const fetchTasks = async () => {
|
||||
const materialHtml = computed(() => renderMarkdown(selectedTask.value?.materialUrl || ""));
|
||||
|
||||
const formatEffectiveTime = (seconds: number): string => {
|
||||
if (!seconds || seconds <= 0) return "0分钟";
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
if (hours > 0) return `${hours}小时${minutes}分钟`;
|
||||
return `${minutes}分钟`;
|
||||
};
|
||||
|
||||
async function loadTaskStats(taskNum: string) {
|
||||
const task = tasks.value.find(t => t.taskNum === taskNum);
|
||||
if (!task || task.statsLoaded) return;
|
||||
|
||||
try {
|
||||
const res = await getReviewTaskStatsByTask(taskNum);
|
||||
if (res?.data) {
|
||||
task.reportCount = res.data.reportCount ?? 0;
|
||||
task.fragmentCount = res.data.fragmentCount ?? 0;
|
||||
task.effectiveTime = res.data.effectiveTime ?? 0;
|
||||
task.sessionCount = res.data.sessionCount ?? 0;
|
||||
task.todayEffectiveTime = res.data.todayEffectiveTime ?? 0;
|
||||
task.weekEffectiveTime = res.data.weekEffectiveTime ?? 0;
|
||||
task.avgEffectiveTime = res.data.avgEffectiveTime ?? 0;
|
||||
task.avgEffectivenessRatio = res.data.avgEffectivenessRatio ?? 0;
|
||||
task.statsLoaded = true;
|
||||
}
|
||||
} catch {
|
||||
// 静默处理,不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTaskApplications(taskNum: string) {
|
||||
applicationsLoading.value = true;
|
||||
try {
|
||||
const res = await getTaskApplications(taskNum);
|
||||
taskApplications.value = res?.data || [];
|
||||
const map: Record<number, string> = {};
|
||||
await Promise.all(
|
||||
taskApplications.value
|
||||
.filter((a) => a.resourceUrl)
|
||||
.map(async (a) => {
|
||||
map[a.id] = await getUrlTitle(a.resourceUrl!);
|
||||
})
|
||||
);
|
||||
appUrlTitles.value = map;
|
||||
} catch (error: any) {
|
||||
taskApplications.value = [];
|
||||
ElMessage.error(error?.message || "应用场景加载失败");
|
||||
} finally {
|
||||
applicationsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const changeApplicationStatus = async (item: TaskApplication) => {
|
||||
if (updatingApplicationId.value !== null) return;
|
||||
updatingApplicationId.value = item.id;
|
||||
try {
|
||||
await updateTaskApplication(item.id, {
|
||||
title: item.title,
|
||||
description: item.description,
|
||||
resourceUrl: item.resourceUrl,
|
||||
status: item.status,
|
||||
});
|
||||
ElMessage.success("应用场景状态已更新");
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error?.message || "状态更新失败");
|
||||
if (selectedTask.value) {
|
||||
await loadTaskApplications(selectedTask.value.taskNum);
|
||||
}
|
||||
} finally {
|
||||
updatingApplicationId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const fetchTasks = async (page = currentPage.value) => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await request.get("/tasks", { pageSize: 100, pageNum: 1 });
|
||||
const previousSelectedTaskId = selectedTaskId.value;
|
||||
currentPage.value = page;
|
||||
const res = await request.get("/tasks", { pageSize, pageNum: page });
|
||||
totalTasks.value = res?.data?.total || 0;
|
||||
tasks.value = (res?.data?.records || []).map((record: any) => ({
|
||||
title: record.taskName,
|
||||
description: record.taskDescription || "",
|
||||
materialURL: record.materialURL || record.materialUrl || "",
|
||||
lastLearningStatus: record.lastLearningStatus || "未开始",
|
||||
materialUrl: record.materialUrl || "",
|
||||
priority: Number.isFinite(record.taskPriority) ? Math.round(record.taskPriority) : "-",
|
||||
taskNum: record.taskNum,
|
||||
taskId: record.id,
|
||||
reportCount: 0,
|
||||
fragmentCount: 0,
|
||||
effectiveTime: 0,
|
||||
statsLoaded: false,
|
||||
sessionCount: 0,
|
||||
todayEffectiveTime: 0,
|
||||
weekEffectiveTime: 0,
|
||||
avgEffectiveTime: 0,
|
||||
avgEffectivenessRatio: 0,
|
||||
}));
|
||||
selectedTaskId.value = tasks.value[0]?.taskId ?? null;
|
||||
const targetTask = tasks.value.find(item => item.taskId === previousSelectedTaskId) || tasks.value[0];
|
||||
const nextSelectedTaskId = targetTask?.taskId ?? null;
|
||||
const shouldLoadStats = nextSelectedTaskId === selectedTaskId.value;
|
||||
selectedTaskId.value = nextSelectedTaskId;
|
||||
if (targetTask && shouldLoadStats) {
|
||||
await loadTaskStats(targetTask.taskNum);
|
||||
await loadTaskApplications(targetTask.taskNum);
|
||||
}
|
||||
} catch (error: any) {
|
||||
tasks.value = [];
|
||||
selectedTaskId.value = null;
|
||||
taskApplications.value = [];
|
||||
ElMessage.error(error?.message || "任务列表加载失败,请重试");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(selectedTaskId, (newId) => {
|
||||
const task = tasks.value.find(t => t.taskId === newId);
|
||||
if (task) {
|
||||
loadTaskStats(task.taskNum);
|
||||
loadTaskApplications(task.taskNum);
|
||||
} else {
|
||||
taskApplications.value = [];
|
||||
}
|
||||
});
|
||||
|
||||
const handlePageChange = (page: number) => {
|
||||
selectedTaskId.value = null;
|
||||
taskApplications.value = [];
|
||||
fetchTasks(page);
|
||||
};
|
||||
|
||||
const startTask = () => {
|
||||
if (!selectedTask.value) {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
@@ -70,13 +210,86 @@ const removeTask = async () => {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
return;
|
||||
}
|
||||
if (removingTask.value) return;
|
||||
removingTask.value = true;
|
||||
const target = selectedTask.value;
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除任务「${target.title}」?关联的学习会话、学习报告、应用场景等数据将被一并删除。`, "确认删除", {
|
||||
confirmButtonText: "确定删除",
|
||||
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 {
|
||||
// 用户取消或删除失败,保持页面状态
|
||||
} finally {
|
||||
removingTask.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// ============ 优先级权重配置 ============
|
||||
const weightsDialogVisible = ref(false);
|
||||
const savingWeights = ref(false);
|
||||
const weightItems = ref([
|
||||
{ key: "urgencyWeight", label: "紧急性", value: 35 },
|
||||
{ key: "importanceWeight", label: "重要性", value: 25 },
|
||||
{ key: "contentDifficultyWeight", label: "内容难度", value: 20 },
|
||||
{ key: "futureValueWeight", label: "未来价值", value: 10 },
|
||||
{ key: "subjectivePriorityWeight", label: "主观优先级", value: 10 },
|
||||
]);
|
||||
|
||||
const weightsSum = computed(() =>
|
||||
weightItems.value.reduce((acc, item) => acc + item.value, 0)
|
||||
);
|
||||
|
||||
const openWeightsDialog = async () => {
|
||||
if (weightsLoading.value) return;
|
||||
weightsLoading.value = true;
|
||||
try {
|
||||
const res = await getPriorityWeights();
|
||||
const data = res?.data;
|
||||
if (data) {
|
||||
for (const item of weightItems.value) {
|
||||
const v = data[item.key];
|
||||
if (typeof v === "number") item.value = Math.round(v * 100);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 读取失败时保持默认值
|
||||
} finally {
|
||||
weightsLoading.value = false;
|
||||
weightsDialogVisible.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const saveWeights = async () => {
|
||||
if (weightsSum.value !== 100) {
|
||||
ElMessage.warning(`五项权重之和需为 100%,当前 ${weightsSum.value}%`);
|
||||
return;
|
||||
}
|
||||
savingWeights.value = true;
|
||||
try {
|
||||
const payload = Object.fromEntries(
|
||||
weightItems.value.map((item) => [item.key, item.value / 100])
|
||||
) as unknown as PriorityWeights;
|
||||
const res = await savePriorityWeights(payload);
|
||||
if (res?.code === 200) {
|
||||
weightsDialogVisible.value = false;
|
||||
ElMessage.success("权重已保存,任务优先级已重算");
|
||||
await fetchTasks();
|
||||
} else {
|
||||
ElMessage.error(res?.message || "保存失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "请求失败");
|
||||
} finally {
|
||||
savingWeights.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
@@ -85,6 +298,7 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<section class="study-page">
|
||||
<div class="layout-grid">
|
||||
<aside class="surface-card task-list">
|
||||
@@ -97,10 +311,22 @@ onMounted(() => {
|
||||
:class="{ active: selectedTaskId === item.taskId }"
|
||||
@click="selectedTaskId = item.taskId"
|
||||
>
|
||||
<p class="task-name">{{ item.title }}</p>
|
||||
<p class="task-meta">状态:{{ item.lastLearningStatus }}</p>
|
||||
<p class="task-name">
|
||||
<span class="task-priority">{{ item.priority }}</span>
|
||||
{{ item.title }}
|
||||
</p>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
<el-pagination
|
||||
v-if="totalTasks > pageSize"
|
||||
small
|
||||
layout="prev, pager, next"
|
||||
:total="totalTasks"
|
||||
:page-size="pageSize"
|
||||
:current-page="currentPage"
|
||||
@current-change="handlePageChange"
|
||||
class="task-pagination"
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<main class="content-zone">
|
||||
@@ -113,36 +339,124 @@ onMounted(() => {
|
||||
|
||||
<div class="detail-block">
|
||||
<p class="label">任务描述</p>
|
||||
<el-input type="textarea" :model-value="selectedTask.description" :rows="4" readonly />
|
||||
<p class="description-text">{{ selectedTask.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
|
||||
<div class="detail-block">
|
||||
<p class="label">学习材料</p>
|
||||
<el-link
|
||||
v-if="selectedTask.materialURL"
|
||||
:href="selectedTask.materialURL"
|
||||
target="_blank"
|
||||
type="primary"
|
||||
>
|
||||
{{ selectedTask.materialURL }}
|
||||
</el-link>
|
||||
<div v-if="materialHtml" class="material-content" v-html="materialHtml" />
|
||||
<p v-else class="empty-text">暂未填写材料地址</p>
|
||||
</div>
|
||||
|
||||
<div class="detail-block" v-if="selectedTask.statsLoaded">
|
||||
<p class="label">学习统计</p>
|
||||
<div class="stats-grid">
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">学习次数</span>
|
||||
<span class="stat-value">{{ selectedTask.sessionCount }} 次</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">今日有效学习</span>
|
||||
<span class="stat-value">{{ formatEffectiveTime(selectedTask.todayEffectiveTime) }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">本周有效学习</span>
|
||||
<span class="stat-value">{{ formatEffectiveTime(selectedTask.weekEffectiveTime) }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">累计有效学习</span>
|
||||
<span class="stat-value">{{ formatEffectiveTime(selectedTask.effectiveTime) }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">平均学习时长</span>
|
||||
<span class="stat-value">{{ formatEffectiveTime(selectedTask.avgEffectiveTime) }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">平均有效时间比</span>
|
||||
<span class="stat-value">{{ (selectedTask.avgEffectivenessRatio * 100).toFixed(1) }}%</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">学习报告</span>
|
||||
<span class="stat-value">{{ selectedTask.reportCount }} 篇</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">学习残片</span>
|
||||
<span class="stat-value">{{ selectedTask.fragmentCount }} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-block" v-loading="applicationsLoading">
|
||||
<p class="label">应用场景</p>
|
||||
<div v-if="taskApplications.length > 0" class="application-list">
|
||||
<div
|
||||
v-for="item in taskApplications"
|
||||
:key="item.id"
|
||||
class="application-item"
|
||||
>
|
||||
<div class="application-main">
|
||||
<strong>{{ item.title }}</strong>
|
||||
<el-select
|
||||
v-model="item.status"
|
||||
size="small"
|
||||
class="application-status"
|
||||
:loading="updatingApplicationId === item.id"
|
||||
:disabled="updatingApplicationId !== null"
|
||||
@change="changeApplicationStatus(item)"
|
||||
>
|
||||
<el-option
|
||||
v-for="option in applicationStatusOptions"
|
||||
:key="option.value"
|
||||
:label="option.label"
|
||||
:value="option.value"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
<p v-if="item.description">{{ item.description }}</p>
|
||||
<el-link v-if="item.resourceUrl" :href="item.resourceUrl" target="_blank" type="primary">
|
||||
{{ appUrlTitles[item.id] || item.resourceUrl }}
|
||||
</el-link>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="empty-text">暂未设置应用场景</p>
|
||||
</div>
|
||||
</template>
|
||||
<el-empty v-else description="暂无任务,请先创建任务" />
|
||||
</article>
|
||||
|
||||
<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 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>
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="weightsDialogVisible" title="优先级权重配置" width="560px">
|
||||
<p class="weights-hint">
|
||||
调整五个维度在优先级计算中的占比,保存后全部任务将按新权重重新排序。
|
||||
</p>
|
||||
<div v-for="item in weightItems" :key="item.key" class="weight-row">
|
||||
<span class="weight-label">{{ item.label }}</span>
|
||||
<el-slider v-model="item.value" :min="0" :max="100" :step="5" class="weight-slider" />
|
||||
<span class="weight-value">{{ item.value }}%</span>
|
||||
</div>
|
||||
<div class="weights-sum" :class="{ 'sum-error': weightsSum !== 100 }">
|
||||
合计:{{ weightsSum }}%(需为 100%)
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="weightsDialogVisible = false">取消</el-button>
|
||||
<el-button type="success" :loading="savingWeights" :disabled="weightsSum !== 100" @click="saveWeights">
|
||||
保存并重算
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@@ -152,6 +466,51 @@ onMounted(() => {
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.weights-hint {
|
||||
margin: 0 0 14px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.weight-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.weight-label {
|
||||
flex-shrink: 0;
|
||||
width: 80px;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.weight-slider {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.weight-value {
|
||||
flex-shrink: 0;
|
||||
width: 44px;
|
||||
text-align: right;
|
||||
font-size: 13px;
|
||||
color: var(--green-800);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.weights-sum {
|
||||
margin-top: 8px;
|
||||
text-align: right;
|
||||
font-size: 13px;
|
||||
color: var(--green-800);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.weights-sum.sum-error {
|
||||
color: #c62828;
|
||||
}
|
||||
|
||||
.layout-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 280px 1fr;
|
||||
@@ -196,12 +555,28 @@ onMounted(() => {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.task-meta {
|
||||
margin: 4px 0 0;
|
||||
.task-priority {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
background: var(--green-600);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 700;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.task-pagination {
|
||||
margin-top: 10px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.content-zone {
|
||||
@@ -226,14 +601,33 @@ onMounted(() => {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.description-text {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
color: var(--text-primary);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.detail-block {
|
||||
margin-top: 16px;
|
||||
margin-top: 20px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.detail-block:first-child {
|
||||
margin-top: 0;
|
||||
padding-top: 0;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.label {
|
||||
margin: 0 0 8px;
|
||||
margin: 0 0 10px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
@@ -241,6 +635,99 @@ onMounted(() => {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.material-content {
|
||||
font-size: 14px;
|
||||
line-height: 1.8;
|
||||
word-break: break-word;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.material-content :deep(a) {
|
||||
color: var(--green-600);
|
||||
text-decoration: none;
|
||||
border-bottom: 1px dashed var(--green-400);
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
}
|
||||
|
||||
.material-content :deep(a:hover) {
|
||||
color: var(--green-800);
|
||||
border-bottom-style: solid;
|
||||
}
|
||||
|
||||
.material-content :deep(a)::after {
|
||||
content: " ↗";
|
||||
font-size: 11px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.application-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.application-item {
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.application-item:first-child {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.application-item:last-child {
|
||||
border-bottom: 0;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.application-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.application-main strong {
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.application-status {
|
||||
width: 112px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.application-item p {
|
||||
margin: 8px 0 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.action-card {
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
@@ -273,12 +760,26 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.page-head {
|
||||
flex-direction: column;
|
||||
.weight-row {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.weight-label {
|
||||
width: 64px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.action-card {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.application-main {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.application-status {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
+436
-35
@@ -3,16 +3,28 @@ import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import request from "@/utils/request";
|
||||
import { ElMessage } from "element-plus";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
createTaskApplication,
|
||||
deleteTaskApplication,
|
||||
getTaskApplications,
|
||||
updateTaskApplication,
|
||||
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();
|
||||
|
||||
const taskId = route.params.taskId ? Number(route.params.taskId) : null;
|
||||
const buttonName = route.meta.buttonText as string;
|
||||
const isUpdateMode = computed(() => route.meta.action === "update");
|
||||
|
||||
const taskNum = ref("");
|
||||
const taskName = ref("");
|
||||
const taskDescription = ref("");
|
||||
const materialURL = ref("");
|
||||
const materialUrl = ref("");
|
||||
const priority = ref({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
@@ -23,32 +35,182 @@ const priority = ref({
|
||||
|
||||
const priorityOptions = [0, 1, 2, 3, 4, 5];
|
||||
|
||||
const createTask = () => {
|
||||
request
|
||||
.post("/tasks", {
|
||||
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;
|
||||
resourceUrl: string;
|
||||
status: TaskApplication["status"];
|
||||
}>({
|
||||
title: "",
|
||||
description: "",
|
||||
resourceUrl: "",
|
||||
status: "TODO",
|
||||
});
|
||||
|
||||
const openApplicationDialog = () => {
|
||||
resetApplicationForm();
|
||||
applicationDialogVisible.value = true;
|
||||
};
|
||||
|
||||
const resetApplicationForm = () => {
|
||||
editingApplicationId.value = null;
|
||||
applicationForm.value = {
|
||||
title: "",
|
||||
description: "",
|
||||
resourceUrl: "",
|
||||
status: "TODO",
|
||||
};
|
||||
};
|
||||
|
||||
const loadApplications = async (targetTaskNum: string) => {
|
||||
applicationLoading.value = true;
|
||||
try {
|
||||
const res = await getTaskApplications(targetTaskNum);
|
||||
applications.value = res?.data || [];
|
||||
// 异步抓取标题
|
||||
const map: Record<number, string> = {};
|
||||
await Promise.all(
|
||||
applications.value
|
||||
.filter((a) => a.resourceUrl)
|
||||
.map(async (a) => {
|
||||
map[a.id] = await getUrlTitle(a.resourceUrl!);
|
||||
})
|
||||
);
|
||||
appUrlTitles.value = map;
|
||||
} catch (error: any) {
|
||||
applications.value = [];
|
||||
ElMessage.error(error?.message || "应用场景加载失败");
|
||||
} finally {
|
||||
applicationLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const saveApplication = async () => {
|
||||
if (!taskNum.value) {
|
||||
ElMessage.warning("任务编号未加载,暂不能维护应用场景");
|
||||
return;
|
||||
}
|
||||
if (!applicationForm.value.title.trim()) {
|
||||
ElMessage.warning("应用项目标题不能为空");
|
||||
return;
|
||||
}
|
||||
applicationSaving.value = true;
|
||||
try {
|
||||
const payload = {
|
||||
title: applicationForm.value.title,
|
||||
description: applicationForm.value.description,
|
||||
resourceUrl: applicationForm.value.resourceUrl,
|
||||
status: applicationForm.value.status,
|
||||
};
|
||||
if (editingApplicationId.value) {
|
||||
await updateTaskApplication(editingApplicationId.value, payload);
|
||||
ElMessage.success("应用场景已更新");
|
||||
} else {
|
||||
await createTaskApplication(taskNum.value, payload);
|
||||
ElMessage.success("应用场景已添加");
|
||||
}
|
||||
applicationDialogVisible.value = false;
|
||||
resetApplicationForm();
|
||||
await loadApplications(taskNum.value);
|
||||
} finally {
|
||||
applicationSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const editApplication = (item: TaskApplication) => {
|
||||
editingApplicationId.value = item.id;
|
||||
applicationForm.value = {
|
||||
title: item.title || "",
|
||||
description: item.description || "",
|
||||
resourceUrl: item.resourceUrl || "",
|
||||
status: item.status || "TODO",
|
||||
};
|
||||
applicationDialogVisible.value = true;
|
||||
};
|
||||
|
||||
const removeApplication = async (item: TaskApplication) => {
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
const convertMaterialUrls = async () => {
|
||||
const raw = materialUrl.value || "";
|
||||
if (!raw.trim()) return;
|
||||
const bareUrls = new Set<string>();
|
||||
raw.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!??)】」』\]]+$/, "");
|
||||
// 跳过 [text](url) 内的
|
||||
if (!raw.includes(`](${clean})`)) bareUrls.add(clean);
|
||||
return url;
|
||||
});
|
||||
if (bareUrls.size === 0) return;
|
||||
const titles: Record<string, string> = {};
|
||||
const results = await Promise.all([...bareUrls].map(async (u) => ({ u, t: await getUrlTitle(u) })));
|
||||
results.forEach(({ u, t }) => { titles[u] = t; });
|
||||
let result = raw;
|
||||
for (const u of bareUrls) {
|
||||
if (titles[u] && titles[u] !== u) {
|
||||
result = result.replace(u, `[${titles[u].replace(/]/g, "\\]")}](${u})`);
|
||||
}
|
||||
}
|
||||
materialUrl.value = result;
|
||||
};
|
||||
|
||||
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,
|
||||
materialUrl: materialUrl.value,
|
||||
...priority.value,
|
||||
})
|
||||
.then((result) => {
|
||||
});
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("创建任务成功");
|
||||
router.push({ name: "study" });
|
||||
await router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务创建失败:" + result.message);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadTask = () => {
|
||||
if (taskId !== null) {
|
||||
request.get(`/tasks/${taskId}`, {}).then((result) => {
|
||||
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 || data.materialUrl || "";
|
||||
materialUrl.value = data.materialUrl || "";
|
||||
priority.value = {
|
||||
urgency: data.urgency,
|
||||
importance: data.importance,
|
||||
@@ -56,30 +218,40 @@ const loadTask = () => {
|
||||
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 = () => {
|
||||
request
|
||||
.put("/tasks/" + taskId, {
|
||||
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,
|
||||
materialUrl: materialUrl.value,
|
||||
...priority.value,
|
||||
})
|
||||
.then((result) => {
|
||||
});
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("更新任务成功");
|
||||
router.push({ name: "study" });
|
||||
await router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务更新失败:" + result.message);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const cancelTask = () => {
|
||||
@@ -87,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("该功能暂不可用,请刷新后重试");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -116,10 +289,54 @@ onMounted(() => {
|
||||
onUnmounted(() => window.removeEventListener("resize", updateWidth));
|
||||
|
||||
const isMobile = computed(() => screenWidth.value <= 900);
|
||||
|
||||
// 学习材料 Markdown 预览
|
||||
const showPreview = ref(false);
|
||||
const materialPreview = ref("");
|
||||
|
||||
async function previewMaterial() {
|
||||
if (previewLoading.value) return;
|
||||
previewLoading.value = true;
|
||||
try {
|
||||
const raw = materialUrl.value || "";
|
||||
if (!raw.trim()) {
|
||||
materialPreview.value = "";
|
||||
showPreview.value = true;
|
||||
return;
|
||||
}
|
||||
const titles: Record<string, string> = {};
|
||||
const bareUrls = new Set<string>();
|
||||
raw.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
bareUrls.add(url.replace(/[.。,,;;!!??)】」』\]]+$/, ""));
|
||||
return url;
|
||||
});
|
||||
const results = await Promise.all([...bareUrls].map(async (u) => ({ u, t: await getUrlTitle(u) })));
|
||||
results.forEach(({ u, t }) => { titles[u] = t; });
|
||||
materialPreview.value = renderMarkdown(raw, titles);
|
||||
showPreview.value = true;
|
||||
} finally {
|
||||
previewLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
priorityOptions,
|
||||
priority,
|
||||
taskNum,
|
||||
taskName,
|
||||
taskDescription,
|
||||
materialUrl,
|
||||
isUpdateMode,
|
||||
loadTask,
|
||||
createTask,
|
||||
updateTask,
|
||||
submitTask,
|
||||
convertMaterialUrls,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="task-form-page">
|
||||
<section class="task-form-page" v-loading="pageLoading">
|
||||
<el-form label-position="top" class="surface-card form-shell">
|
||||
<div class="group">
|
||||
<h3>基础信息</h3>
|
||||
@@ -129,8 +346,36 @@ const isMobile = computed(() => screenWidth.value <= 900);
|
||||
<el-form-item label="任务描述">
|
||||
<el-input v-model="taskDescription" type="textarea" :rows="5" placeholder="请输入任务描述" />
|
||||
</el-form-item>
|
||||
<el-form-item label="学习材料地址">
|
||||
<el-input v-model="materialURL" placeholder="例如:https://..." />
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<div class="material-label">
|
||||
<span>学习材料地址</span>
|
||||
<el-button
|
||||
v-if="!showPreview"
|
||||
text
|
||||
size="small"
|
||||
type="primary"
|
||||
:loading="previewLoading"
|
||||
@click="previewMaterial()"
|
||||
>预览</el-button>
|
||||
<el-button
|
||||
v-else
|
||||
text
|
||||
size="small"
|
||||
@click="showPreview = false"
|
||||
>编辑</el-button>
|
||||
<span class="material-hint" v-if="!showPreview">[链接文字](url) 或直接粘贴链接</span>
|
||||
<span class="material-hint" v-else>链接会自动获取标题展示</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-input
|
||||
v-if="!showPreview"
|
||||
v-model="materialUrl"
|
||||
type="textarea"
|
||||
:rows="6"
|
||||
placeholder="支持 Markdown 格式 例如: 参考 [Vue.js 文档](https://vuejs.org/guide) 源码在 https://github.com/vuejs/core"
|
||||
/>
|
||||
<div v-else class="material-preview" v-html="materialPreview" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
@@ -169,8 +414,66 @@ const isMobile = computed(() => screenWidth.value <= 900);
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="group" v-if="isUpdateMode" v-loading="applicationLoading">
|
||||
<div class="application-header">
|
||||
<h3>应用场景</h3>
|
||||
<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">
|
||||
<div class="application-main">
|
||||
<strong>{{ item.title }}</strong>
|
||||
<el-tag size="small" effect="plain">
|
||||
{{ applicationStatusOptions.find(option => option.value === item.status)?.label || item.status }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<p v-if="item.description">{{ item.description }}</p>
|
||||
<el-link v-if="item.resourceUrl" :href="item.resourceUrl" target="_blank" type="primary">
|
||||
{{ appUrlTitles[item.id] || item.resourceUrl }}
|
||||
</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"
|
||||
:loading="deletingApplicationId === item.id"
|
||||
:disabled="deletingApplicationId !== null"
|
||||
@click="removeApplication(item)"
|
||||
>删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="empty-text">暂未设置应用场景</p>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="applicationDialogVisible" :title="editingApplicationId ? '编辑应用场景' : '添加应用场景'" width="500px">
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="应用项目" required>
|
||||
<el-input v-model="applicationForm.title" placeholder="例如:用Vue3重构个人博客" />
|
||||
</el-form-item>
|
||||
<el-form-item label="应用描述">
|
||||
<el-input v-model="applicationForm.description" type="textarea" :rows="4" placeholder="描述如何应用所学内容" />
|
||||
</el-form-item>
|
||||
<el-form-item label="相关链接">
|
||||
<el-input v-model="applicationForm.resourceUrl" placeholder="https://..." />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="applicationForm.status" placeholder="状态">
|
||||
<el-option v-for="option in applicationStatusOptions" :key="option.value" :label="option.label" :value="option.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="applicationDialogVisible = false">取消</el-button>
|
||||
<el-button type="success" :loading="applicationSaving" @click="saveApplication">
|
||||
{{ editingApplicationId ? '更新' : '添加' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</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>
|
||||
@@ -197,6 +500,49 @@ const isMobile = computed(() => screenWidth.value <= 900);
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.material-label {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 8px;
|
||||
}
|
||||
|
||||
.material-label .material-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.material-preview {
|
||||
min-height: 120px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 8px;
|
||||
background: #fafdfb;
|
||||
font-size: 14px;
|
||||
line-height: 1.8;
|
||||
word-break: break-word;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.material-preview :deep(a) {
|
||||
color: var(--green-600);
|
||||
text-decoration: none;
|
||||
border-bottom: 1px dashed var(--green-400);
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
}
|
||||
|
||||
.material-preview :deep(a:hover) {
|
||||
color: var(--green-800);
|
||||
border-bottom-style: solid;
|
||||
}
|
||||
|
||||
.material-preview :deep(a)::after {
|
||||
content: " ↗";
|
||||
font-size: 11px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.priority-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
@@ -207,6 +553,64 @@ const isMobile = computed(() => screenWidth.value <= 900);
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.application-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.application-header h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.application-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.application-item {
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 8px;
|
||||
background: #fbfefc;
|
||||
}
|
||||
|
||||
.application-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.application-main strong {
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.application-item p {
|
||||
margin: 8px 0 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.application-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
margin: 0 0 12px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
@@ -218,13 +622,10 @@ const isMobile = computed(() => screenWidth.value <= 900);
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
.application-main {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-row .el-button {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
+282
-117
@@ -1,77 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import router from "@/router";
|
||||
import { getReviewFeed, type ReviewFeedItem } from "@/api/review";
|
||||
import { getReviewFeed, getTaskReview, type ReviewFeedItem } from "@/api/review";
|
||||
|
||||
const reviewItems = ref<ReviewFeedItem[]>([]);
|
||||
const isHovering = ref(false);
|
||||
const contentRef = ref<HTMLElement | null>(null);
|
||||
const AUTO_SCROLL_DURATION = 150_000;
|
||||
let autoScroll: Animation | null = null;
|
||||
|
||||
interface SessionGroup {
|
||||
interface FragmentChip {
|
||||
id: number;
|
||||
sessionNum: string;
|
||||
taskName: string;
|
||||
taskNum: string;
|
||||
content: string;
|
||||
hasReport: boolean;
|
||||
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");
|
||||
|
||||
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;
|
||||
});
|
||||
// 滚动条只展示学习残片,每条残片单独作为 chip
|
||||
const fragmentChips = computed<FragmentChip[]>(() =>
|
||||
reviewItems.value
|
||||
.filter(item => item.sourceType === "FRAGMENT")
|
||||
.map(item => ({
|
||||
id: item.id,
|
||||
sessionNum: item.sessionNum,
|
||||
taskName: item.taskName,
|
||||
taskNum: item.taskNum,
|
||||
content: truncateContent(item.content),
|
||||
})),
|
||||
);
|
||||
|
||||
// 复制一份实现无缝循环
|
||||
const duplicatedGroups = computed(() => [...sessionGroups.value, ...sessionGroups.value]);
|
||||
const duplicatedChips = computed(() => [...fragmentChips.value, ...fragmentChips.value]);
|
||||
|
||||
const loadReviewFeed = async () => {
|
||||
try {
|
||||
const res = await getReviewFeed(100);
|
||||
const res = await getReviewFeed(100, "smart");
|
||||
reviewItems.value = res?.data || [];
|
||||
} catch {
|
||||
// feed 加载失败不影响页面主体功能
|
||||
}
|
||||
};
|
||||
|
||||
const goToReviewDetail = (group: SessionGroup) => {
|
||||
router.push(`/review/detail/${group.navigateType}/${group.navigateId}`);
|
||||
// 回忆卡片:点击残片先尝试回忆,再展开该会话的报告和其他残片进行对照
|
||||
const recallCard = ref<{
|
||||
visible: boolean;
|
||||
fragment: FragmentChip | null;
|
||||
report: ReviewFeedItem | null;
|
||||
fragments: ReviewFeedItem[];
|
||||
revealed: boolean;
|
||||
loadingSession: boolean;
|
||||
loadError: string;
|
||||
}>({
|
||||
visible: false,
|
||||
fragment: null,
|
||||
report: null,
|
||||
fragments: [],
|
||||
revealed: false,
|
||||
loadingSession: false,
|
||||
loadError: "",
|
||||
});
|
||||
|
||||
const openRecallCard = (fragment: FragmentChip) => {
|
||||
recallCard.value = {
|
||||
visible: true,
|
||||
fragment,
|
||||
report: null,
|
||||
fragments: [],
|
||||
revealed: false,
|
||||
loadingSession: false,
|
||||
loadError: "",
|
||||
};
|
||||
};
|
||||
|
||||
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 goToRecallFromCard = () => {
|
||||
const fragment = recallCard.value.fragment;
|
||||
if (!fragment) return;
|
||||
recallCard.value.visible = false;
|
||||
const tn = fragment.taskNum;
|
||||
const content = fragment.content || "";
|
||||
if (tn && content) {
|
||||
router.push(`/review/recall/${tn}?focusContent=${encodeURIComponent(content)}`);
|
||||
} else if (tn) {
|
||||
router.push(`/review/recall/${tn}`);
|
||||
} else {
|
||||
router.push("/review");
|
||||
}
|
||||
};
|
||||
|
||||
const startStudy = () => {
|
||||
@@ -82,36 +124,80 @@ const startReview = () => {
|
||||
router.push("/review");
|
||||
};
|
||||
|
||||
const handleTrackWheel = (event: WheelEvent) => {
|
||||
const anim = autoScroll;
|
||||
const content = contentRef.value;
|
||||
if (!anim || !content) return;
|
||||
|
||||
anim.pause();
|
||||
|
||||
const rawDelta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
|
||||
const delta = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? rawDelta * 16 : rawDelta;
|
||||
if (!delta) return;
|
||||
|
||||
// 一屏内容的宽度对应一轮自动滚动
|
||||
const loopWidth = content.scrollWidth / 2;
|
||||
if (!loopWidth) return;
|
||||
|
||||
const current = anim.currentTime;
|
||||
if (typeof current !== "number") return;
|
||||
anim.currentTime = Math.min(
|
||||
Math.max(current + (delta / loopWidth) * AUTO_SCROLL_DURATION, 0),
|
||||
AUTO_SCROLL_DURATION,
|
||||
);
|
||||
};
|
||||
|
||||
const pauseAutoScroll = () => {
|
||||
autoScroll?.pause();
|
||||
};
|
||||
|
||||
const resumeAutoScroll = () => {
|
||||
autoScroll?.play();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadReviewFeed();
|
||||
autoScroll = contentRef.value?.animate(
|
||||
[
|
||||
{ transform: "translateX(0)" },
|
||||
{ transform: "translateX(-50%)" },
|
||||
],
|
||||
{ duration: AUTO_SCROLL_DURATION, iterations: Infinity, easing: "linear" },
|
||||
) || null;
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
autoScroll?.cancel();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<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>
|
||||
</div>
|
||||
<div class="review-scroll-track">
|
||||
<div
|
||||
class="review-scroll-track"
|
||||
@mouseenter="pauseAutoScroll"
|
||||
@mouseleave="resumeAutoScroll"
|
||||
@wheel.prevent="handleTrackWheel"
|
||||
>
|
||||
<div
|
||||
ref="contentRef"
|
||||
class="review-scroll-content"
|
||||
:class="{ paused: isHovering }"
|
||||
@mouseenter="isHovering = true"
|
||||
@mouseleave="isHovering = false"
|
||||
>
|
||||
<span
|
||||
v-for="(group, index) in duplicatedGroups"
|
||||
v-for="(chip, index) in duplicatedChips"
|
||||
:key="index"
|
||||
class="review-chip"
|
||||
:class="group.hasReport ? 'has-report' : 'fragments-only'"
|
||||
@click="goToReviewDetail(group)"
|
||||
class="review-chip fragment-chip"
|
||||
@click="openRecallCard(chip)"
|
||||
>
|
||||
<strong class="chip-task">{{ group.taskName }}</strong>
|
||||
<span class="chip-content">{{ group.content }}</span>
|
||||
<strong class="chip-task">{{ chip.taskName }}</strong>
|
||||
<span class="chip-content">{{ chip.content }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -124,7 +210,6 @@ onMounted(() => {
|
||||
先挑选任务开始一次会话,再在复习页回顾你的学习轨迹。
|
||||
</p>
|
||||
</div>
|
||||
<el-tag type="success" effect="dark" size="large">今日模式:稳步推进</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="quick-grid">
|
||||
@@ -140,16 +225,61 @@ onMounted(() => {
|
||||
<el-button plain type="success" size="large" @click="startReview">开始复习</el-button>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="tips-board surface-card">
|
||||
<h3>建议流程</h3>
|
||||
<ol>
|
||||
<li>进入学习页,确认任务材料地址与优先级。</li>
|
||||
<li>开始会话并在休息时记录学习残片。</li>
|
||||
<li>结束会话后填写总结,再回到复习页检视数据。</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 回忆卡片:先回忆,再对照 -->
|
||||
<el-dialog
|
||||
v-model="recallCard.visible"
|
||||
:title="recallCard.fragment?.taskName || '回忆一下'"
|
||||
width="560px"
|
||||
class="recall-card-dialog"
|
||||
>
|
||||
<template v-if="recallCard.fragment">
|
||||
<p class="recall-question">
|
||||
看着下面这个残片,先试着回忆:当时还学了什么?
|
||||
</p>
|
||||
<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 recallCard.fragments"
|
||||
:key="item.id"
|
||||
class="recall-full-item"
|
||||
:class="{ 'is-clicked': item.id === recallCard.fragment?.id }"
|
||||
>
|
||||
<span class="recall-item-tag tag-fragment">残片</span>
|
||||
<span class="recall-item-content">{{ item.content }}</span>
|
||||
</div>
|
||||
<el-empty
|
||||
v-if="!recallCard.report && recallCard.fragments.length === 0"
|
||||
description="暂未找到该会话的对照内容"
|
||||
:image-size="48"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<el-button
|
||||
v-if="!recallCard.revealed"
|
||||
type="success"
|
||||
plain
|
||||
:loading="recallCard.loadingSession"
|
||||
@click="revealRecallContent"
|
||||
>
|
||||
展开对照
|
||||
</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>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@@ -223,10 +353,6 @@ onMounted(() => {
|
||||
margin-right: 3px;
|
||||
}
|
||||
|
||||
.dot-report {
|
||||
background: var(--green-600);
|
||||
}
|
||||
|
||||
.dot-fragment {
|
||||
background: #e6a23c;
|
||||
}
|
||||
@@ -241,20 +367,6 @@ onMounted(() => {
|
||||
display: inline-flex;
|
||||
gap: 14px;
|
||||
white-space: nowrap;
|
||||
animation: review-ticker 150s linear infinite;
|
||||
}
|
||||
|
||||
.review-scroll-content.paused {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
@keyframes review-ticker {
|
||||
0% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.review-chip {
|
||||
@@ -264,7 +376,7 @@ onMounted(() => {
|
||||
padding: 8px 16px;
|
||||
background: var(--surface-strong);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-left: 3px solid transparent;
|
||||
border-left: 3px solid #e6a23c;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, box-shadow 0.2s;
|
||||
@@ -272,23 +384,8 @@ onMounted(() => {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.review-chip.has-report {
|
||||
border-left-color: var(--green-600);
|
||||
}
|
||||
|
||||
.review-chip.fragments-only {
|
||||
border-left-color: #e6a23c;
|
||||
}
|
||||
|
||||
.review-chip:hover {
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.review-chip.has-report:hover {
|
||||
background: #e8f5e9;
|
||||
}
|
||||
|
||||
.review-chip.fragments-only:hover {
|
||||
background: #fff8e1;
|
||||
}
|
||||
|
||||
@@ -306,23 +403,81 @@ onMounted(() => {
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.tips-board {
|
||||
padding: 20px 22px;
|
||||
/* 回忆卡片 */
|
||||
.recall-question {
|
||||
margin: 0 0 12px;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.tips-board h3 {
|
||||
margin: 0;
|
||||
color: var(--green-900);
|
||||
.recall-snippet {
|
||||
margin: 0 0 14px;
|
||||
padding: 12px 16px;
|
||||
border-left: 3px solid var(--green-600);
|
||||
background: #f1f8e9;
|
||||
border-radius: 0 6px 6px 0;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.7;
|
||||
word-break: break-word;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.tips-board ol {
|
||||
margin: 10px 0 0;
|
||||
padding-left: 20px;
|
||||
color: var(--text-secondary);
|
||||
.recall-error {
|
||||
margin: 0 0 10px;
|
||||
color: var(--el-color-danger, #f56c6c);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.tips-board li + li {
|
||||
margin-top: 8px;
|
||||
.recall-full-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-height: 320px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.recall-full-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
background: #fbfefc;
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.recall-full-item.is-clicked {
|
||||
background: #fff8e1;
|
||||
border-color: #e6a23c;
|
||||
}
|
||||
|
||||
.recall-item-tag {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.tag-report {
|
||||
background: #e8f5e9;
|
||||
color: var(--green-700);
|
||||
}
|
||||
|
||||
.tag-fragment {
|
||||
background: #fff8e1;
|
||||
color: #b8860b;
|
||||
}
|
||||
|
||||
.recall-item-content {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
@@ -334,4 +489,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 = '';
|
||||
@@ -25,39 +26,46 @@ export const useStudyFragment = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const confirmGenerateFragment = async (sessionNum: string) => {
|
||||
const confirmGenerateFragment = async (sessionNum: string): Promise<boolean> => {
|
||||
if (creatingFragment.value) return false;
|
||||
if (!fragmentContent.value.trim()) {
|
||||
ElMessage.warning('请输入学习内容!');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
creatingFragment.value = true;
|
||||
try {
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
})
|
||||
.then(async () => {
|
||||
try {
|
||||
});
|
||||
} catch {
|
||||
ElMessage.info('已取消生成');
|
||||
return false;
|
||||
}
|
||||
const res = await createFragments(sessionNum, fragmentContent.value);
|
||||
|
||||
if (res.code === 200) {
|
||||
ElMessage.success('学习残片生成成功!');
|
||||
fragmentsDialogVisible.value = false;
|
||||
return true;
|
||||
} else {
|
||||
ElMessage.error(res.message || '生成学习残片失败');
|
||||
return false;
|
||||
}
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '请求失败');
|
||||
return false;
|
||||
} finally {
|
||||
creatingFragment.value = false;
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
ElMessage.info('已取消生成');
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
fragmentsDialogVisible,
|
||||
fragmentContent,
|
||||
creatingFragment,
|
||||
openFragmentDialog,
|
||||
closeFragmentDialog,
|
||||
confirmGenerateFragment,
|
||||
|
||||
@@ -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>
|
||||
@@ -27,11 +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: "复习详情" },
|
||||
},
|
||||
{
|
||||
path: "/review/detail/:type/:id",
|
||||
component: () => import("@/components/ReviewDetail.vue"),
|
||||
meta: { requiresAuth: true, title: "复习详情" },
|
||||
},
|
||||
{
|
||||
path: "/review/recall/:taskNum",
|
||||
component: () => import("@/components/ReviewRecall.vue"),
|
||||
meta: { requiresAuth: true, title: "回忆复习", wide: true },
|
||||
},
|
||||
{
|
||||
path: "/start-task/:taskNum",
|
||||
name: "start-task",
|
||||
@@ -84,6 +94,18 @@ router.beforeEach((to) => {
|
||||
if (!isLoggedIn) {
|
||||
return "/login";
|
||||
}
|
||||
// 如果有活跃会话且未处于 start-task 页面,自动恢复
|
||||
if (!to.path.startsWith("/start-task")) {
|
||||
const stored = localStorage.getItem("activeSession");
|
||||
if (stored) {
|
||||
try {
|
||||
const { taskNum } = JSON.parse(stored);
|
||||
if (taskNum) {
|
||||
return `/start-task/${encodeURIComponent(taskNum)}?resume=true`;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* URL 标题缓存 + 按需抓取,调用后端 /utils/fetch-title 代理
|
||||
*/
|
||||
|
||||
import request from "@/utils/request";
|
||||
|
||||
const cache = new Map<string, string>();
|
||||
const pending = new Map<string, Promise<string>>();
|
||||
|
||||
export async function getUrlTitle(url: string): Promise<string> {
|
||||
if (cache.has(url)) return cache.get(url)!;
|
||||
if (pending.has(url)) return pending.get(url)!;
|
||||
|
||||
const promise = request
|
||||
.get("/utils/fetch-title", { url })
|
||||
.then((res: any) => {
|
||||
const title = res?.data?.title || url;
|
||||
cache.set(url, title);
|
||||
return title;
|
||||
})
|
||||
.catch(() => url)
|
||||
.finally(() => pending.delete(url));
|
||||
|
||||
pending.set(url, promise);
|
||||
return promise;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+25
-15
@@ -1,31 +1,45 @@
|
||||
import axios from 'axios';
|
||||
import { ElMessage } from "element-plus";
|
||||
import router from "@/router";
|
||||
|
||||
const basic_url = import.meta.env.VITE_BASE_URL;
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: basic_url,
|
||||
timeout: 5000,
|
||||
timeout: 600000,
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
const handleError = (error: any) => {
|
||||
console.log(error);
|
||||
|
||||
// 业务异常由 validateResponse 负责提示,这里透传,避免被网络错误文案覆盖。
|
||||
if (error && typeof error === "object" && "code" in error) {
|
||||
// 401 未授权(HTTP 层):token 过期或未登录
|
||||
if (error?.response?.status === 401) {
|
||||
localStorage.removeItem("isLoggedIn");
|
||||
router.push("/login");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
// 401 未授权(业务层):后端 GlobalExceptionHandler 返回 code=401
|
||||
if (error && typeof error === "object" && error.code === 401) {
|
||||
localStorage.removeItem("isLoggedIn");
|
||||
router.push("/login");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
// 其他业务异常(如 code !== 200)透传,由调用方自行提示
|
||||
if (error && typeof error === "object" && "code" in error && !error.response) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
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) => {
|
||||
@@ -41,14 +55,12 @@ function get(url: string, params: Record<string, any>): Promise<any>;
|
||||
function get(url: string): Promise<any>;
|
||||
|
||||
function get(url: string, params: Record<string, any> = {}) {
|
||||
console.log("开始GET请求", basic_url + url, "参数:", params);
|
||||
return axiosInstance.get(url, { params })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
}
|
||||
|
||||
const post = (url: string, data: any = null, config: any = {}) => {
|
||||
console.log("开始POST请求", url, "参数:", data, "配置:", config);
|
||||
|
||||
if (config.params) {
|
||||
// 如果传入 config.params,则作为 URL 参数
|
||||
@@ -64,22 +76,20 @@ const post = (url: string, data: any = null, config: any = {}) => {
|
||||
};
|
||||
|
||||
const put = (url: string, data: any, config: any = {}) => {
|
||||
console.log("开始PUT请求", basic_url + url, "参数:", data);
|
||||
return axiosInstance.put(url, data, config)
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
};
|
||||
|
||||
const del = (url: string, params: Record<string, any> = {}, config: any = {}) => {
|
||||
console.log("开始DELETE请求", basic_url + url, "参数:", params);
|
||||
return axiosInstance.delete(url, { params, ...config })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
};
|
||||
|
||||
const requestNotImplemented = (method: string) => {
|
||||
ElMessage.error(`请求方法 ${method} 未实现`);
|
||||
throw new Error(`请求方法 ${method} 未实现`);
|
||||
ElMessage.error("该功能暂不可用,请刷新后重试");
|
||||
throw new Error("该功能暂不可用,请刷新后重试");
|
||||
};
|
||||
|
||||
const request = (method: string, url: string, paramsOrData: any) => {
|
||||
|
||||
@@ -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" },
|
||||
];
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// https://vite.dev/config/
|
||||
@@ -23,5 +23,11 @@ export default defineConfig({
|
||||
rewrite: (path) => path.replace(/^\/api/, ""),
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./src/__tests__/setup.ts'],
|
||||
include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user