Compare commits
139 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| e2f7276b92 | |||
| ad2561981d | |||
| 4abc316311 | |||
| fce4ba194b | |||
| 43e8cd4965 | |||
| f586332ab2 | |||
| ad847973bc | |||
| 749d9752fd | |||
| 70d347e06e | |||
| c535548793 | |||
| 52045ecbeb | |||
| 3a3a96da3c | |||
| f4d6bcff23 | |||
| 73ed40609c | |||
| 6137f6f102 | |||
| eb9b1f6b95 | |||
| 6d05b37399 | |||
| af30b7b316 | |||
| c84d30e287 | |||
| cef3192ba5 | |||
| 5c0f7e932f | |||
| cff4989072 | |||
| 56f94f384d | |||
| 82c06d29fe | |||
| 0f2f0460df | |||
| 4c73991d64 | |||
| 3150b2d89e | |||
| e750c36345 | |||
| d09849a41c | |||
| 39c9d14c9c | |||
| d418d463de | |||
| 134b09780b | |||
| 7e7f40efd3 | |||
| 2d3512ac4c | |||
| b51a57b57f | |||
| b5e1ae0f6f | |||
| 385662e628 | |||
| da7611c9a1 | |||
| 2553c059c3 | |||
| c9f57ab8ef | |||
| cb618807fc |
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
.DS_Store
|
||||
coverage
|
||||
.nyc_output
|
||||
playwright-report
|
||||
test-results
|
||||
+1
-1
@@ -1 +1 @@
|
||||
VITE_BASE_URL = 'http://localhost:5157'
|
||||
VITE_BASE_URL=/api
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
VITE_BASE_URL = 'https://lpt.cat-shark.xyz/api'
|
||||
VITE_BASE_URL=/api
|
||||
|
||||
@@ -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,46 @@
|
||||
# LPT 前端规范
|
||||
|
||||
## 技术栈
|
||||
- Vue 3 + TypeScript + Vite
|
||||
- Element Plus UI
|
||||
- Axios(`src/utils/request.ts`)
|
||||
- mind-elixir(思维导图)
|
||||
|
||||
## 认证与请求
|
||||
- axios `withCredentials: true`,Cookie `satoken` 自动携带
|
||||
- 401 处理(`handleError`):HTTP 层和业务层双重检测,清 `localStorage.isLoggedIn` → `router.push("/login")`
|
||||
- `validateResponse`:`code !== 200` → reject
|
||||
|
||||
## Markdown 学习材料
|
||||
- 编辑:textarea 输入,支持 `[文字](url)` 和裸 URL
|
||||
- 预览/展示:`renderMarkdown(raw)` 同步函数
|
||||
- 使用占位符 `__LINK_N__` 避免正则二次匹配产生嵌套 HTML
|
||||
- `[文字](url)` → `<a>` 标签
|
||||
- 裸 URL → `<a>` 标签(展示时用 getUrlTitle 获取标题)
|
||||
- 保存:`convertMaterialUrls()` 在 createTask/updateTask 前异步拉取标题,替换裸 URL 为 `[标题](url)`
|
||||
- `getUrlTitle(url)`:调 `/utils/fetch-title`,内存缓存 + 请求去重
|
||||
|
||||
## 应用场景
|
||||
- TaskForm 编辑页:弹窗形式(el-dialog),列表展示用 `getUrlTitle` 获取链接标题
|
||||
- Study 详情页:同上
|
||||
|
||||
## 样式规范
|
||||
- 链接:绿色系(`var(--green-600)`),虚线下划线,hover 变实线
|
||||
- 区块分隔:`.detail-block` 有 `border-top` + `padding-top`,首个除外
|
||||
- 小字提示:12px `var(--text-secondary)`
|
||||
|
||||
## 任务清单分页
|
||||
- Study.vue:每页 20 条,`el-pagination` 在列表底部
|
||||
|
||||
## 学习会话页面
|
||||
- StartTask.vue 展示学习材料(可点击链接),支持弹窗编辑
|
||||
- 编辑时先 GET 任务详情,合并后 PUT 更新(保护其他字段不被覆盖)
|
||||
|
||||
## 思维导图
|
||||
- MindMapViewer 封装 mind-elixir
|
||||
- selectable 模式:点击节点 emit `node-select`
|
||||
- ReviewRecall 中 standardExpanded 展开后节点可点击选复习起点
|
||||
|
||||
## 编译
|
||||
- `npx vite build`
|
||||
- `npx vue-tsc --noEmit`(类型检查)
|
||||
@@ -0,0 +1,72 @@
|
||||
# 部署流水线问题排查进度
|
||||
|
||||
**日期**: 2026-07-20(更新)
|
||||
|
||||
## 当前部署方式
|
||||
|
||||
- **Jenkinsfile / Jenkinsfile-dev**:历史方案,已不再作为主路径
|
||||
- **现行方案**:Gitea Actions(`.gitea/workflows/deploy.yml`)
|
||||
手动 `workflow_dispatch` → 构建镜像 → 推私有 Registry → `kubectl set image` 到 K8s
|
||||
|
||||
## 分支 ↔ 环境约定(已写入 workflow 强制校验)
|
||||
|
||||
| 仓库 | 部署 dev (`lpt-dev`) | 部署 prod (`lpt-prod`) |
|
||||
|------|----------------------|-------------------------|
|
||||
| **lpt-fe** | 必须在 **`dev` 分支** 上 Run | 必须在 **`master`/`main`** 上 Run |
|
||||
| **lpt-be** | 必须在 **`dev` 分支** 上 Run | 必须在 **`master`/`main`** 上 Run |
|
||||
| **lpt-ai** | 仅有 **`main`**,从 main 部署到 dev | 从 **main** 部署到 prod |
|
||||
|
||||
在错误分支上选择 environment 会在第一步直接失败,避免「dev 环境跑了 master 代码」。
|
||||
|
||||
### 正确操作
|
||||
|
||||
1. Gitea 仓库页面切换到目标分支(fe/be 的 dev 或 master)
|
||||
2. Actions → 对应 workflow → Run workflow
|
||||
3. 选择 `environment` = `dev` 或 `prod`(须与当前分支匹配)
|
||||
|
||||
## 已修复项(2026-07-20)
|
||||
|
||||
1. **分支与环境绑定校验** — 三个仓库的 `deploy.yml` 增加 Validate 步骤
|
||||
2. **`IMAGE_TAG` 持久化** — 除 `GITHUB_ENV` 外,写入 `GITEA_ENV`(若存在)+ 临时文件兜底,Deploy 步读取失败则明确报错
|
||||
3. **fe `BUILD_MODE`** — 在 shell 内根据 environment 设置 `production` / `development`,避免表达式兼容问题
|
||||
4. **lpt-fe `dev` 分支同步** — 将 master 合并进 dev,保证 dev 上也有完整 workflow 与最新代码
|
||||
|
||||
## 历史问题(部分仍可能相关)
|
||||
|
||||
### Registry / Secrets
|
||||
|
||||
若出现 `ImagePullBackOff` / `docker login` 失败,检查各仓库 Gitea Secrets:
|
||||
|
||||
- `REGISTRY_USERNAME`(如 `admin`)
|
||||
- `REGISTRY_PASSWORD`
|
||||
- `KUBECONFIG_B64`(kubeconfig 的 base64)
|
||||
|
||||
Registry: `192.168.123.199:5000`
|
||||
|
||||
### K8s
|
||||
|
||||
- 共享清单:`k8s/dev/*`、`k8s/prod/*`(按环境)
|
||||
- 各服务仓库内 `k8s/` 仍多为 `lpt-dev` 模板;日常 CI 只 `set image`,不 `apply` 整份 YAML
|
||||
- Deployment 需有 `imagePullSecrets: [regcred]`;workflow 每次会 create/update `regcred`
|
||||
|
||||
## 镜像与命名空间
|
||||
|
||||
| environment | 镜像 tag(浮动) | 不可变 tag | namespace |
|
||||
|-------------|------------------|------------|-----------|
|
||||
| dev | `app:dev` | `app:<sha>-<unix>` | `lpt-dev` |
|
||||
| prod | `app:prod` | `app:<sha>-<unix>` | `lpt-prod` |
|
||||
|
||||
部署使用不可变 tag,避免 `imagePullPolicy` 与缓存导致未更新。
|
||||
|
||||
## 验证清单
|
||||
|
||||
1. [ ] 三仓库 Secrets 已配置
|
||||
2. [ ] lpt-fe:在 **dev** 分支 Run → environment=dev 成功
|
||||
3. [ ] lpt-fe:在 **master** 上选 environment=dev 应 **失败**(校验)
|
||||
4. [ ] lpt-be:同上
|
||||
5. [ ] lpt-ai:在 **main** 上 Run → dev / prod
|
||||
6. [ ] `kubectl get pods -n lpt-dev` / `lpt-prod` 正常
|
||||
|
||||
---
|
||||
|
||||
**备注**: 主路径为 Gitea Actions + K8s;Jenkins 配置可保留作参考,勿与现行流程混用。
|
||||
@@ -0,0 +1,413 @@
|
||||
# LPT 复习流程设计文档
|
||||
|
||||
> 本文档描述 LPT 系统中「回忆复习」(Recall Review)功能的完整设计,包括数据模型、API、前端交互流程和三种入口的处理方式。
|
||||
|
||||
---
|
||||
|
||||
## 1. 核心概念
|
||||
|
||||
### 1.1 标准思维导图(Standard Mind Map)
|
||||
|
||||
- **任务级单一知识树**:每个学习任务有且仅有一棵标准思维导图,存储在 `review_standard_mind_maps` 表
|
||||
- **生成方式**:
|
||||
- `BUILTIN`:内置规则引擎,按 session 分组、去重、合并
|
||||
- `AI`:调用 lpt-ai 服务生成缩进大纲后解析
|
||||
- `USER`:用户手动编辑
|
||||
- `USER_MERGE`:增量合并后(保留用户编辑 + 追加 AI 新节点)
|
||||
- **数据结构**:`content` 字段存储 JSON 树(递归 `MindMapNode`),`outline` 字段存储缩进大纲文本
|
||||
- **节点模型**:
|
||||
```
|
||||
MindMapNode {
|
||||
title: string // 节点标题
|
||||
notes?: string // 备注 / 对比标记(MATCHED| / MISSED|)
|
||||
sourceType?: string // REPORT | FRAGMENT | APPLICATION
|
||||
sourceId?: number // 对应源数据主键
|
||||
children?: MindMapNode[]
|
||||
}
|
||||
```
|
||||
- **节点标记约定**(用于对比着色):
|
||||
- `notes` 以 `MATCHED|` 开头 → 绿色(回忆命中)
|
||||
- `notes` 以 `MISSED|` 开头 → 红色(回忆遗漏)
|
||||
- 无标记 → 默认色(未参与对比)
|
||||
|
||||
### 1.2 回忆对比记录(Recall Record)
|
||||
|
||||
- 每次用户提交回忆 → 生成一条 `review_recall_records` 记录
|
||||
- 核心字段:
|
||||
- `task_num`:关联任务
|
||||
- `standard_map_id`:对比时使用的标准导图版本
|
||||
- `focus_path`:复习起点节点路径(`"根 / 分支A / 子节点B"`),null 为全量
|
||||
- `recall_content`:用户回忆大纲文本
|
||||
- `compare_result`:对比结果 JSON(含 `matchedTree`、`extraNodes`、覆盖率等)
|
||||
- `recall_ratio` / `matched_count` / `missed_count` / `extra_count`:统计摘要
|
||||
|
||||
---
|
||||
|
||||
## 2. 复习流程
|
||||
|
||||
### 2.1 核心逻辑
|
||||
|
||||
```
|
||||
1. 确定复习起点(节点路径)
|
||||
2. 获取标准导图
|
||||
3. 按起点提取子树作为对比基准
|
||||
4. 用户在大纲编辑器中回忆填充
|
||||
5. 提交对比(AI 语义匹配 或 BUILTIN 字符串匹配)
|
||||
6. 展示对比结果(着色 + 统计)
|
||||
```
|
||||
|
||||
### 2.2 节点选择
|
||||
|
||||
- 用户在标准导图上点击节点 → `MindMapViewer` 发射 `node-select` 事件(含 `title`、`path`、`childCount`)
|
||||
- 弹窗确认:「以「节点名」为起点,复习其下 N 个子知识点?」
|
||||
- 确认后:
|
||||
- `focusPath` = 选中节点的路径(如 `"Java基础 / 集合 / HashMap"`)
|
||||
- `recallTree` 根节点标题 = 选中节点标题
|
||||
- 回忆导图以该标题为根,用户补充子节点
|
||||
|
||||
### 2.3 对比范围
|
||||
|
||||
- **有 `focusPath`**:`MindMapTreeTool.extractSubtree(root, focusPath)` 提取子树,对比基准 = 子树
|
||||
- **无 `focusPath`**:对比基准 = 整棵标准导图
|
||||
- AI 对比:发给 lpt-ai 的 outline 只包含子树范围
|
||||
- BUILTIN 对比:`compareTrees()` 在子树范围内做标题匹配
|
||||
|
||||
### 2.4 对比算法
|
||||
|
||||
**AI 语义匹配(优先):**
|
||||
```
|
||||
POST /ai/tasks → type: "compare-recall"
|
||||
→ 异步轮询结果
|
||||
→ 返回 { matches: [{standardTitle, recallTitle}], missedTitles, extraNodes, evaluation }
|
||||
→ Java 端 buildCompareResultFromAI() 标注标准树
|
||||
```
|
||||
|
||||
**BUILTIN 字符串匹配(降级):**
|
||||
- 展平标准树和回忆树
|
||||
- 标题标准化(去标点、去空格、转小写)
|
||||
- 精确匹配 → 模糊匹配(bigram Jaccard ≥ 0.6)
|
||||
- 标记 MATCHED / MISSED / 额外
|
||||
|
||||
### 2.5 结果展示
|
||||
|
||||
- 标准导图面板直接显示着色对比结果(不再有独立对比面板)
|
||||
- 绿色(`#c8e6c9`)= 命中,红色(`#ffcdd2`)= 遗漏
|
||||
- 统计卡片:覆盖率、命中/遗漏/额外计数
|
||||
- 遗漏项列表 + 额外项列表(可点击回看原文)
|
||||
|
||||
---
|
||||
|
||||
## 3. 三个复习入口
|
||||
|
||||
### 入口 A:复习总览 → "回忆复习"
|
||||
|
||||
**路径:** `Welcome.vue` → "复习回看" → `Review.vue`(任务列表)→ 每行"回忆复习"按钮
|
||||
|
||||
**前端代码:** `Review.vue:110`
|
||||
```typescript
|
||||
router.push(`/review/recall/${row.taskNum}`)
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. 跳转到 `ReviewRecall.vue`,URL 为 `/review/recall/:taskNum`
|
||||
2. 页面加载 → `loadData()` 获取标准导图
|
||||
3. 标准导图 `selectable=true`,显示提示「点击导图节点选择复习起点」
|
||||
4. 用户点击节点 → 弹窗确认 → 进入回忆模式
|
||||
5. 回忆填充 → 提交对比 → 展示结果
|
||||
|
||||
**相关文件:**
|
||||
- `lpt-fe/src/components/Review.vue`
|
||||
- `lpt-fe/src/components/ReviewRecall.vue`
|
||||
|
||||
### 入口 B:从某个残片/报告详情 → "回忆复习"
|
||||
|
||||
**路径:** `Welcome.vue` 滚动回顾 → 点击卡片 → `ReviewDetail.vue` → "回忆复习"按钮
|
||||
|
||||
**前端代码:** `ReviewDetail.vue` 的 `goToRecall()`
|
||||
```typescript
|
||||
const res = await findNode(taskNum, content.substring(0, 500));
|
||||
if (res?.data?.path) {
|
||||
router.push(`/review/recall/${taskNum}?focusPath=${encodeURIComponent(res.data.path)}`);
|
||||
}
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. 用户在详情页查看某个残片/报告的内容
|
||||
2. 点击"回忆复习" → 前端调 `POST /review/standard-mind-map/{taskNum}/find-node`
|
||||
3. 后端 `findClosestNode()` 用 bigram Jaccard 匹配最接近的节点
|
||||
4. 返回 `{ path, nodeTitle, score }`
|
||||
5. 跳转到 `/review/recall/:taskNum?focusPath=...`
|
||||
6. `ReviewRecall.vue` 检测到 URL 参数 → 跳过节点选择,直接进入回忆模式
|
||||
|
||||
**后端 API:**
|
||||
```http
|
||||
POST /review/standard-mind-map/{taskNum}/find-node
|
||||
Content-Type: application/json
|
||||
|
||||
{ "content": "用户查看的残片/报告文本" }
|
||||
|
||||
→ 200 OK
|
||||
{ "code": 200, "data": { "path": "根 / 分支A / 子节点B", "nodeTitle": "子节点B", "score": 0.85 } }
|
||||
```
|
||||
|
||||
**匹配算法(`MindMapTreeTool.findClosestNode`):**
|
||||
1. 展平标准导图所有节点
|
||||
2. 对每个节点,计算其 `title` 与输入文本的 bigram Jaccard 相似度
|
||||
3. `notes` 字段也参与匹配(权重 0.5)
|
||||
4. 返回得分最高(>0.1)的节点
|
||||
|
||||
**相关文件:**
|
||||
- `lpt-fe/src/components/ReviewDetail.vue`
|
||||
- `learning-progress-tracker/.../utils/MindMapTreeTool.java`(`findClosestNode`、`similarityScore`)
|
||||
|
||||
### 入口 C:首页欢迎页 → 回忆卡片 → "前往回忆复习"
|
||||
|
||||
**路径:** `Welcome.vue` → 滚动回顾标签 → 点击弹出回忆对话框 → "前往回忆复习"按钮
|
||||
|
||||
**前端代码:** `Welcome.vue` 的 `goToRecallFromCard()`
|
||||
```typescript
|
||||
const tn = group.taskNum;
|
||||
const res = await findNode(tn, content.substring(0, 500));
|
||||
if (res?.data?.path) {
|
||||
router.push(`/review/recall/${tn}?focusPath=${encodeURIComponent(res.data.path)}`);
|
||||
}
|
||||
```
|
||||
|
||||
**流程:**
|
||||
1. Welcome 页加载 `GET /review/feed` 获取复习 feed
|
||||
2. 按 session 分组为标签卡片
|
||||
3. 用户点击某个标签 → 弹出回忆对话框(先回忆→展开对照)
|
||||
4. 点击"前往回忆复习" → 同入口 B,先调 findNode 再跳转
|
||||
|
||||
**相关文件:**
|
||||
- `lpt-fe/src/components/Welcome.vue`
|
||||
|
||||
---
|
||||
|
||||
## 4. 关键 API 清单
|
||||
|
||||
### 4.1 标准思维导图
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| `GET` | `/review/standard-mind-map/{taskNum}` | 获取/自动生成标准导图 |
|
||||
| `POST` | `/review/standard-mind-map/{taskNum}/regenerate?mode=full\|incremental` | 重新生成 |
|
||||
| `PUT` | `/review/standard-mind-map/{taskNum}` | 用户编辑(大纲文本) |
|
||||
| `POST` | `/review/standard-mind-map/{taskNum}/recall` | 提交回忆对比 |
|
||||
| `POST` | `/review/standard-mind-map/{taskNum}/find-node` | 匹配最近节点 |
|
||||
| `GET` | `/review/standard-mind-map/{taskNum}/recall-records` | 历史回忆记录 |
|
||||
|
||||
### 4.2 回忆对比请求体
|
||||
|
||||
```json
|
||||
{
|
||||
"recallOutline": "用户回忆的缩进大纲文本\n - 子节点1\n - 子节点2",
|
||||
"focusPath": "根标题 / 分支A / 子节点B"
|
||||
}
|
||||
```
|
||||
|
||||
- `recallOutline`:必填,用户回忆的缩进大纲
|
||||
- `focusPath`:可选,复习起点节点路径。null = 全量,提供时对比范围为该子树
|
||||
|
||||
### 4.3 对比结果结构(CompareResult)
|
||||
|
||||
```json
|
||||
{
|
||||
"matchedTree": {
|
||||
"title": "根节点",
|
||||
"notes": "",
|
||||
"children": [
|
||||
{
|
||||
"title": "命中的知识点",
|
||||
"notes": "MATCHED|完整原文内容",
|
||||
"sourceType": "REPORT",
|
||||
"sourceId": 1,
|
||||
"children": []
|
||||
},
|
||||
{
|
||||
"title": "遗漏的知识点",
|
||||
"notes": "MISSED|完整原文内容",
|
||||
"sourceType": "FRAGMENT",
|
||||
"sourceId": 2,
|
||||
"children": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"extraNodes": [
|
||||
{ "title": "用户额外回忆的知识", "path": "/额外/..." }
|
||||
],
|
||||
"recallRatio": 0.75,
|
||||
"matchedCount": 3,
|
||||
"missedCount": 1,
|
||||
"extraCount": 1,
|
||||
"evaluation": "AI 评价文本(仅 AI 对比时有值)"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 前端组件结构
|
||||
|
||||
```
|
||||
ReviewRecall.vue(主页面)
|
||||
├── Page header(返回、标题、历史记录按钮)
|
||||
├── 复习起点指示(focusPath 显示 + 重选按钮)
|
||||
├── 节点选择确认弹窗(el-dialog)
|
||||
├── 统计卡片(覆盖率/命中/遗漏/额外)
|
||||
├── 回忆历史列表
|
||||
├── 回忆输入(editable MindMapViewer)
|
||||
├── 标准导图 + 对比结果(color-by-compare MindMapViewer)
|
||||
│ ├── 未选择起点时 → selectable 模式
|
||||
│ ├── 已选择起点/已对比 → 着色展示
|
||||
│ └── 编辑模式 → editable 模式
|
||||
└── 遗漏项 + 额外项详情列表
|
||||
```
|
||||
|
||||
### 5.1 MindMapViewer 组件 Props
|
||||
|
||||
| 属性 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `tree` | `MindMapTreeNode \| null` | — | 树数据 |
|
||||
| `editable` | `boolean` | `false` | 是否可编辑 |
|
||||
| `colorByCompare` | `boolean` | `false` | 按 MATCHED/MISSED 着色 |
|
||||
| `height` | `string` | `'480px'` | 画布高度 |
|
||||
| `selectable` | `boolean` | `false` | 节点单击可选择 |
|
||||
| `selectedPath` | `string` | `''` | 当前选中节点路径 |
|
||||
|
||||
### 5.2 MindMapViewer 事件
|
||||
|
||||
| 事件 | 载荷 | 触发时机 |
|
||||
|------|------|----------|
|
||||
| `change` | `outline: string` | 编辑模式下结构变化 |
|
||||
| `node-click` | `{ sourceType, sourceId }` | 点击带溯源标签的节点 |
|
||||
| `node-select` | `{ title, path, childCount }` | selectable 模式下点击节点 |
|
||||
|
||||
### 5.3 MindMapViewer 暴露方法
|
||||
|
||||
```typescript
|
||||
defineExpose({ toOutline })
|
||||
// toOutline() → 缩进大纲文本
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 后端核心工具方法
|
||||
|
||||
### `MindMapTreeTool.java`
|
||||
|
||||
| 方法 | 说明 |
|
||||
|------|------|
|
||||
| `extractSubtree(root, path)` | 按 "/" 分隔路径提取子树,返回深拷贝 |
|
||||
| `findClosestNode(root, content)` | bigram Jaccard 匹配最近节点 |
|
||||
| `getPath(root, targetTitle)` | 获取节点到根的路径字符串 |
|
||||
| `similarityScore(a, b)` | 两段文本的 bigram Jaccard 相似度 |
|
||||
| `mergeTrees(oldRoot, newRoot)` | 按标准化标题合并新旧树 |
|
||||
| `toJson(root, mapper)` | 序列化为 JSON |
|
||||
| `fromJson(json, mapper)` | 从 JSON 反序列化 |
|
||||
| `toOutline(root)` | 树 → 缩进大纲 |
|
||||
| `toFullOutline(root)` | 树 → 完整大纲(含根标题) |
|
||||
| `parseOutline(text)` | 缩进大纲 → 树 |
|
||||
| `flatten(root)` | 前序遍历展平 |
|
||||
| `countNodes(root)` | 节点总数 |
|
||||
| `maxDepth(root)` | 最大深度 |
|
||||
|
||||
### `StandardMindMapServiceImpl.java`
|
||||
|
||||
| 方法 | 说明 |
|
||||
|------|------|
|
||||
| `getOrGenerate(taskNum)` | 获取/自动生成标准导图 |
|
||||
| `regenerate(taskNum)` | 全量重新生成(防并发) |
|
||||
| `incrementalGenerate(taskNum)` | 增量合并(保留用户编辑) |
|
||||
| `updateByOutline(taskNum, outline)` | 用户编辑 |
|
||||
| `recallCompare(taskNum, outline, focusPath)` | 回忆对比 |
|
||||
| `findNode(taskNum, content)` | 查找最近节点 |
|
||||
| `listRecallRecords(taskNum)` | 历史记录 |
|
||||
| `getRecallRecord(id)` | 单条记录详情 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 关键文件索引
|
||||
|
||||
### 前端(`lpt-fe/src/`)
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `components/ReviewRecall.vue` | 回忆复习主页面 |
|
||||
| `components/Review.vue` | 复习总览(任务列表+入口) |
|
||||
| `components/ReviewDetail.vue` | 残片/报告详情页 |
|
||||
| `components/Welcome.vue` | 首页(内含回忆卡片入口) |
|
||||
| `components/MindMapViewer.vue` | 思维导图渲染/编辑/选择组件 |
|
||||
| `api/standardMindMap.ts` | 标准导图 API 封装 |
|
||||
| `api/review.ts` | 复习 feed API |
|
||||
| `api/studySessions.ts` | 学习会话 API |
|
||||
|
||||
### 后端(`learning-progress-tracker/src/main/java/.../`)
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `controller/ReviewController.java` | 复习相关端点 |
|
||||
| `service/StandardMindMapService.java` | 标准导图服务接口 |
|
||||
| `service/impl/StandardMindMapServiceImpl.java` | 服务实现 |
|
||||
| `service/impl/BuiltinMindMapGenerator.java` | 内置规则生成器 |
|
||||
| `service/impl/RemoteAiMindMapClient.java` | AI 导图客户端 |
|
||||
| `service/impl/AiServiceClient.java` | lpt-ai 通用客户端 |
|
||||
| `utils/MindMapNode.java` | 树节点 DTO |
|
||||
| `utils/MindMapTreeTool.java` | 树操作工具类 |
|
||||
| `utils/CompareResult.java` | 对比结果 DTO |
|
||||
| `entity/ReviewStandardMindMapEntity.java` | 标准导图实体 |
|
||||
| `entity/ReviewRecallRecordEntity.java` | 回忆记录实体 |
|
||||
| `db/migration/V20260706_1__add_focus_path_to_recall_records.sql` | focus_path 迁移 |
|
||||
|
||||
### AI 服务(`lpt-ai/src/`)
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `routes/ai.ts` | AI 任务提交/轮询/抓取标题 |
|
||||
| `task-queue.ts` | 异步任务队列 |
|
||||
| `llm/prompts.ts` | prompt 模板(generate-mind-map / compare-recall / aggregate-report) |
|
||||
| `llm/client.ts` | LLM API 客户端 |
|
||||
| `admin/routes.ts` | 管理面板 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 数据流图
|
||||
|
||||
```
|
||||
学习碎片/报告
|
||||
↓ (按 session 分组)
|
||||
BuiltinMindMapGenerator / RemoteAiMindMapClient
|
||||
↓
|
||||
标准思维导图(review_standard_mind_maps)
|
||||
↓ (用户选择节点)
|
||||
extractSubtree(root, focusPath)
|
||||
↓
|
||||
子树(对比基准)
|
||||
↓ AI / BUILTIN 对比 ← 用户回忆大纲
|
||||
↓
|
||||
CompareResult
|
||||
↓ (序列化存储 + 前端渲染)
|
||||
review_recall_records + 着色 MindMapViewer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 历史版本记录
|
||||
|
||||
| Commit | 说明 |
|
||||
|--------|------|
|
||||
| `a636e51` | 新增 sessionNum 追踪 + 维度选择(已回退) |
|
||||
| `e5adb40` | 前端会话选择器(已回退) |
|
||||
| `3c3f682` | 防并发生成 + `mergeTrees` + 增量合 |
|
||||
| `5a5a294` | 前端防抖/生成提示/移除冗余面板 |
|
||||
| `84fe452` | **节点选择交互 + focusPath + findNode(当前)** |
|
||||
| `b18f8b4` | **后端 focusPath + extractSubtree + 回退 session(当前)** |
|
||||
| `ebbbeb4` | fix: Array.map 多参数 bug |
|
||||
|
||||
---
|
||||
|
||||
## 10. 待办/已知问题
|
||||
|
||||
- [ ] AI 生成的导图(`RemoteAiMindMapClient`)因为没有 `sourceId`/`sourceType`,`node-click` 溯源不可用
|
||||
- [ ] `selectable` 模式下,点击无子节点的叶子节点,`childCount` = 0 的确认弹窗体验略奇怪
|
||||
- [ ] `findClosestNode` 的 bigram 相似度对短文本效果有限,可能需要 `notes` 加权优化
|
||||
- [ ] 欢迎页(Welcome.vue)的回忆卡片入口「前往回忆复习」按钮文字和位置可以优化
|
||||
+17
-6
@@ -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
+21
-63
@@ -1,88 +1,46 @@
|
||||
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'
|
||||
HOST_PORT = '5158'
|
||||
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 '''
|
||||
docker network create traefik-public || true
|
||||
docker rm -f $CONTAINER_NAME || true
|
||||
docker run -d --name $CONTAINER_NAME \\
|
||||
-p $HOST_PORT:$CONTAINER_PORT \\
|
||||
--health-cmd="curl -f http://localhost:80 || exit 1" \\
|
||||
--health-interval=5s \\
|
||||
--health-retries=3 \\
|
||||
--restart=always \\
|
||||
--network traefik-public \\
|
||||
--label "traefik.enable=true" \\
|
||||
--label "traefik.docker.network=traefik-public" \\
|
||||
--label 'traefik.http.routers.lpt-fe.rule=Host(`lpt.cat-shark.xyz`)' \\
|
||||
--label "traefik.http.routers.lpt-fe.entrypoints=websecure" \\
|
||||
--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" \\
|
||||
$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'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
pipeline {
|
||||
agent none
|
||||
environment {
|
||||
IMAGE_NAME = 'lpt-fe-dev:0.0'
|
||||
CONTAINER_NAME = 'LPT_FE-dev'
|
||||
CONTAINER_PORT = '80'
|
||||
}
|
||||
stages {
|
||||
stage('构建 Docker 镜像') {
|
||||
agent any
|
||||
steps {
|
||||
sh 'docker build --build-arg BUILD_MODE=dev -t $IMAGE_NAME .'
|
||||
}
|
||||
}
|
||||
stage('部署容器') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
docker network create traefik-public || true
|
||||
docker rm -f $CONTAINER_NAME || true
|
||||
docker run -d --name $CONTAINER_NAME \\
|
||||
--network traefik-public \\
|
||||
--label "traefik.enable=true" \\
|
||||
--label "traefik.docker.network=traefik-public" \\
|
||||
--label 'traefik.http.routers.lpt-fe-dev.rule=Host(`lpt-dev.cat-shark.xyz`)' \\
|
||||
--label "traefik.http.routers.lpt-fe-dev.entrypoints=websecure" \\
|
||||
--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" \\
|
||||
$IMAGE_NAME
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('健康检查') {
|
||||
agent any
|
||||
steps {
|
||||
sh 'sleep 5 && docker exec $CONTAINER_NAME curl -f http://localhost:$CONTAINER_PORT/ || (docker logs $CONTAINER_NAME && exit 1)'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
# LPT 前端架构优化说明
|
||||
|
||||
> 记录前端实现中的关键设计决策和优化策略
|
||||
|
||||
## 一、组件设计优化
|
||||
|
||||
### 1.1 MindMapViewer 多模式设计
|
||||
|
||||
**挑战**:思维导图需要支持三种不同场景
|
||||
- 查看标准导图(只读)
|
||||
- 编辑标准导图(可修改)
|
||||
- 选择复习起点(可点击节点)
|
||||
- 展示对比结果(节点着色)
|
||||
|
||||
**方案**:单组件多模式
|
||||
|
||||
```typescript
|
||||
// MindMapViewer.vue
|
||||
interface Props {
|
||||
tree: MindMapTreeNode | null;
|
||||
editable?: boolean; // 编辑模式
|
||||
selectable?: boolean; // 选择模式
|
||||
colorByCompare?: boolean; // 对比着色模式
|
||||
height?: string;
|
||||
selectedPath?: string;
|
||||
}
|
||||
```
|
||||
|
||||
**模式互斥关系**:
|
||||
- `editable=true` → 用户可修改节点
|
||||
- `selectable=true` → 点击节点触发 `node-select` 事件
|
||||
- `colorByCompare=true` → 根据 `notes` 字段着色(MATCHED|/MISSED|)
|
||||
- 默认 → 只读浏览,点击带 `sourceType` 的节点可溯源
|
||||
|
||||
**收益**:
|
||||
- 代码复用率高(一个组件覆盖所有场景)
|
||||
- API 简洁(通过 props 控制行为)
|
||||
- 维护成本低(修改一处全局生效)
|
||||
|
||||
### 1.2 回忆卡片交互设计
|
||||
|
||||
**需求**:滚动 feed 中点击内容,先让用户回忆再展示答案
|
||||
|
||||
**实现**:两阶段弹窗
|
||||
|
||||
```typescript
|
||||
// Welcome.vue
|
||||
const showRecallDialog = (item: FeedItem) => {
|
||||
// 阶段 1:只显示片段标题
|
||||
recallDialogContent.value = item.content.substring(0, 100) + '...';
|
||||
recallDialogExpanded.value = false;
|
||||
|
||||
// 用户点击"我想起来了"
|
||||
const expand = () => {
|
||||
recallDialogExpanded.value = true;
|
||||
// 阶段 2:展示完整内容 + 同会话其他内容
|
||||
loadFullSession(item.sessionNum);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
**心理学原理**:
|
||||
- 主动回忆 > 被动阅读(Testing Effect)
|
||||
- 认知失调驱动记忆巩固
|
||||
- 答案延迟呈现增强记忆深度
|
||||
|
||||
**收益**:
|
||||
- 提升复习效果
|
||||
- 增加用户参与感
|
||||
- 符合间隔重复理论
|
||||
|
||||
### 1.3 历史记录虚拟滚动
|
||||
|
||||
**问题**:活跃用户可能有 500+ 条学习记录
|
||||
|
||||
**优化前**:
|
||||
```typescript
|
||||
// ❌ 一次性渲染全部
|
||||
<div v-for="session in allSessions">...</div>
|
||||
```
|
||||
|
||||
**优化后**:
|
||||
```typescript
|
||||
// ✅ 分页 + 懒加载
|
||||
<el-pagination
|
||||
:total="total"
|
||||
:page-size="20"
|
||||
@current-change="loadPage"
|
||||
/>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 首屏渲染时间:2.5s → 0.3s
|
||||
- 内存占用:120MB → 15MB
|
||||
- 支持无限历史
|
||||
|
||||
---
|
||||
|
||||
## 二、状态管理优化
|
||||
|
||||
### 2.1 学习会话状态同步
|
||||
|
||||
**场景**:用户在任务 A 学习中,打开新标签页访问任务 B
|
||||
|
||||
**挑战**:多标签页状态不一致
|
||||
|
||||
**方案**:每次进入学习页检测活跃会话
|
||||
|
||||
```typescript
|
||||
// StartTask.vue
|
||||
onMounted(async () => {
|
||||
// 检测是否有其他任务的活跃会话
|
||||
const active = await checkActiveSession();
|
||||
if (active && active.taskNum !== currentTaskNum) {
|
||||
ElMessageBox.confirm(
|
||||
`您有正在进行的学习会话(任务 ${active.taskNum}),是否继续?`,
|
||||
{ type: 'warning' }
|
||||
).then(() => {
|
||||
router.push(`/start-task/${active.taskNum}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 防止数据丢失
|
||||
- 引导用户正确流程
|
||||
- 多标签页一致性
|
||||
|
||||
### 2.2 权重配置实时校验
|
||||
|
||||
**需求**:五个维度权重总和必须为 100%
|
||||
|
||||
**实现**:响应式计算 + 即时反馈
|
||||
|
||||
```typescript
|
||||
// Study.vue
|
||||
const weightSum = computed(() => {
|
||||
return Object.values(weights.value).reduce((sum, w) => sum + w, 0);
|
||||
});
|
||||
|
||||
const isSumValid = computed(() => weightSum.value === 100);
|
||||
|
||||
watch(weightSum, (newSum) => {
|
||||
if (newSum !== 100) {
|
||||
message.warning(`当前总和 ${newSum}%,需调整为 100%`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 即时反馈(无需点保存才知道错误)
|
||||
- 视觉提示(红色警告 + 禁用保存按钮)
|
||||
- 防止无效提交
|
||||
|
||||
### 2.3 Markdown 链接标题缓存
|
||||
|
||||
**场景**:学习材料中有 10 个 URL,每个都要调 `/fetch-title`
|
||||
|
||||
**优化前**:
|
||||
```typescript
|
||||
// ❌ 重复请求
|
||||
for (const url of urls) {
|
||||
const title = await fetchTitle(url);
|
||||
}
|
||||
```
|
||||
|
||||
**优化后**:
|
||||
```typescript
|
||||
// ✅ 内存缓存 + 请求去重
|
||||
const titleCache = new Map<string, Promise<string>>();
|
||||
|
||||
export const getUrlTitle = (url: string) => {
|
||||
if (titleCache.has(url)) {
|
||||
return titleCache.get(url);
|
||||
}
|
||||
const promise = fetchTitle(url);
|
||||
titleCache.set(url, promise);
|
||||
return promise;
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 重复 URL 零请求
|
||||
- 并发请求自动去重(Promise 复用)
|
||||
- 会话内持久化
|
||||
|
||||
---
|
||||
|
||||
## 三、用户体验优化
|
||||
|
||||
### 3.1 学习预期常驻展示
|
||||
|
||||
**需求**:用户学习过程中可随时查看预期,结束时对比
|
||||
|
||||
**实现**:卡片式展示 + 弹窗对比
|
||||
|
||||
```vue
|
||||
<!-- StartTask.vue -->
|
||||
<el-card class="expectation-card" v-if="expectation">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>📋 本次学习预期</span>
|
||||
<el-button text @click="editExpectation">修改</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<p>{{ expectation }}</p>
|
||||
</el-card>
|
||||
```
|
||||
|
||||
结束会话时:
|
||||
```typescript
|
||||
ElMessageBox.confirm(`
|
||||
<p><strong>预期:</strong>${expectation}</p>
|
||||
<p><strong>实际:</strong>${reportContent}</p>
|
||||
<p>是否达成预期?</p>
|
||||
`, { dangerouslyUseHTMLString: true });
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 元认知训练
|
||||
- 学习目标明确
|
||||
- 防止跑偏
|
||||
|
||||
### 3.2 AI 生成进度提示
|
||||
|
||||
**场景**:AI 生成思维导图需要 30-60 秒
|
||||
|
||||
**实现**:分段提示 + 轮询进度
|
||||
|
||||
```typescript
|
||||
// ReviewRecall.vue
|
||||
const generateWithAi = async () => {
|
||||
message.info('正在调用 AI 生成思维导图...');
|
||||
|
||||
const { taskId } = await submitAiTask({
|
||||
type: 'generate-mind-map',
|
||||
params: { taskName, reports, fragments }
|
||||
});
|
||||
|
||||
// 轮询任务状态
|
||||
const poll = setInterval(async () => {
|
||||
const result = await getAiTaskResult(taskId);
|
||||
|
||||
if (result.status === 'running') {
|
||||
message.info(`生成中... ${result.progress || 50}%`);
|
||||
} else if (result.status === 'completed') {
|
||||
message.success('生成完成!');
|
||||
clearInterval(poll);
|
||||
loadStandardMap();
|
||||
} else if (result.status === 'failed') {
|
||||
message.error('生成失败,已降级为内置规则');
|
||||
clearInterval(poll);
|
||||
}
|
||||
}, 2000);
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 降低用户焦虑
|
||||
- 明确系统状态
|
||||
- 减少重复点击
|
||||
|
||||
### 3.3 节点路径面包屑
|
||||
|
||||
**场景**:用户选择复习起点后,需明确当前在导图的哪个位置
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<!-- ReviewRecall.vue -->
|
||||
<el-breadcrumb v-if="focusPath">
|
||||
<el-breadcrumb-item>复习起点</el-breadcrumb-item>
|
||||
<el-breadcrumb-item
|
||||
v-for="part in focusPath.split(' / ')"
|
||||
:key="part"
|
||||
>
|
||||
{{ part }}
|
||||
</el-breadcrumb-item>
|
||||
</el-breadcrumb>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 空间定位清晰
|
||||
- 复习范围明确
|
||||
- 可点击返回上级
|
||||
|
||||
---
|
||||
|
||||
## 四、性能优化
|
||||
|
||||
### 4.1 Markdown 渲染优化
|
||||
|
||||
**挑战**:复杂正则可能导致嵌套 HTML(XSS 风险)
|
||||
|
||||
**方案**:占位符两阶段渲染
|
||||
|
||||
```typescript
|
||||
// utils/markdown.ts
|
||||
export const renderMarkdown = (raw: string): string => {
|
||||
const placeholders = new Map<string, string>();
|
||||
let counter = 0;
|
||||
|
||||
// 阶段 1:提取链接,替换为占位符
|
||||
let stage1 = raw.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, text, url) => {
|
||||
const key = `__LINK_${counter++}__`;
|
||||
placeholders.set(key, `<a href="${url}">${text}</a>`);
|
||||
return key;
|
||||
});
|
||||
|
||||
// 阶段 2:替换占位符为真实 HTML
|
||||
placeholders.forEach((html, key) => {
|
||||
stage1 = stage1.replace(key, html);
|
||||
});
|
||||
|
||||
return stage1;
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 避免正则二次匹配导致的嵌套
|
||||
- 性能提升(单次遍历)
|
||||
- 安全性高(输出可预测)
|
||||
|
||||
### 4.2 防抖与节流
|
||||
|
||||
**场景**:
|
||||
- 搜索框输入(防抖)
|
||||
- 滚动加载(节流)
|
||||
- 权重滑块调整(防抖)
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
import { debounce } from 'lodash-es';
|
||||
|
||||
// 搜索输入
|
||||
const handleSearch = debounce((keyword: string) => {
|
||||
searchTasks(keyword);
|
||||
}, 300);
|
||||
|
||||
// 滚动加载
|
||||
const handleScroll = throttle(() => {
|
||||
if (isBottom()) loadMore();
|
||||
}, 200);
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 减少 API 调用
|
||||
- 降低 CPU 占用
|
||||
- 提升响应速度
|
||||
|
||||
### 4.3 图片懒加载
|
||||
|
||||
**场景**:学习材料中可能包含多张图片
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<img v-lazy="imageUrl" alt="学习材料配图" />
|
||||
```
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
import VueLazyload from 'vue-lazyload';
|
||||
app.use(VueLazyload, {
|
||||
loading: '/placeholder.png',
|
||||
error: '/error.png'
|
||||
});
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 首屏加载快
|
||||
- 节省带宽
|
||||
- 平滑加载体验
|
||||
|
||||
---
|
||||
|
||||
## 五、错误处理
|
||||
|
||||
### 5.1 统一异常拦截
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
// utils/request.ts
|
||||
axios.interceptors.response.use(
|
||||
response => {
|
||||
const { code, message } = response.data;
|
||||
if (code !== 200) {
|
||||
ElMessage.error(message || '请求失败');
|
||||
return Promise.reject(new Error(message));
|
||||
}
|
||||
return response;
|
||||
},
|
||||
error => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('isLoggedIn');
|
||||
router.push('/login');
|
||||
ElMessage.error('登录已过期,请重新登录');
|
||||
} else if (error.response?.status === 403) {
|
||||
ElMessage.error('无权限访问');
|
||||
} else {
|
||||
ElMessage.error(error.message || '网络错误');
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 业务代码无需重复处理
|
||||
- 统一错误提示样式
|
||||
- 自动处理登录过期
|
||||
|
||||
### 5.2 降级 UI
|
||||
|
||||
**场景**:AI 生成失败,自动切换为内置生成
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
const generate = async () => {
|
||||
try {
|
||||
await generateWithAi();
|
||||
} catch (error) {
|
||||
ElNotification({
|
||||
title: 'AI 生成失败',
|
||||
message: '已自动切换为内置规则生成',
|
||||
type: 'warning'
|
||||
});
|
||||
await generateBuiltin();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 用户无感知切换
|
||||
- 功能可用性保障
|
||||
- 明确提示原因
|
||||
|
||||
---
|
||||
|
||||
## 六、可访问性优化
|
||||
|
||||
### 6.1 键盘导航
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<!-- 学习页 -->
|
||||
<div
|
||||
tabindex="0"
|
||||
@keydown.space="togglePause"
|
||||
@keydown.enter="endSession"
|
||||
>
|
||||
<!-- 内容 -->
|
||||
</div>
|
||||
```
|
||||
|
||||
**支持快捷键**:
|
||||
- `Space` - 暂停/继续
|
||||
- `Enter` - 结束会话
|
||||
- `Esc` - 关闭弹窗
|
||||
- `Tab` - 焦点切换
|
||||
|
||||
### 6.2 语义化 HTML
|
||||
|
||||
**实现**:
|
||||
```vue
|
||||
<!-- ✅ 正确 -->
|
||||
<main>
|
||||
<section aria-label="复习概览">
|
||||
<h2>复习概览</h2>
|
||||
<nav aria-label="任务列表">...</nav>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- ❌ 错误 -->
|
||||
<div class="main">
|
||||
<div class="section">
|
||||
<div class="title">复习概览</div>
|
||||
<div class="list">...</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 屏幕阅读器友好
|
||||
- SEO 优化
|
||||
- 代码可读性高
|
||||
|
||||
### 6.3 色盲友好
|
||||
|
||||
**对比结果着色**:
|
||||
- 匹配节点:绿色 `#c8e6c9` + ✓ 图标
|
||||
- 遗漏节点:红色 `#ffcdd2` + ✗ 图标
|
||||
- 额外节点:蓝色 `#bbdefb` + ★ 图标
|
||||
|
||||
**原则**:不仅依赖颜色,同时使用图标/文字辅助
|
||||
|
||||
---
|
||||
|
||||
## 七、构建优化
|
||||
|
||||
### 7.1 代码分割
|
||||
|
||||
**实现**:
|
||||
```typescript
|
||||
// router/index.ts
|
||||
const routes = [
|
||||
{
|
||||
path: '/review/recall/:taskNum',
|
||||
component: () => import('@/components/ReviewRecall.vue') // 懒加载
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 首屏包体积:1.2MB → 320KB
|
||||
- 按需加载(用户未访问的页面不下载)
|
||||
|
||||
### 7.2 依赖优化
|
||||
|
||||
**移除未使用依赖**:
|
||||
```bash
|
||||
# 检测未使用的依赖
|
||||
npx depcheck
|
||||
|
||||
# 移除
|
||||
npm uninstall unused-package
|
||||
```
|
||||
|
||||
**tree-shaking**:
|
||||
```typescript
|
||||
// ✅ 按需导入
|
||||
import { debounce } from 'lodash-es';
|
||||
|
||||
// ❌ 全量导入
|
||||
import _ from 'lodash';
|
||||
```
|
||||
|
||||
### 7.3 CDN 加速
|
||||
|
||||
**生产环境**:
|
||||
```html
|
||||
<!-- index.html -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/element-plus/dist/index.full.min.js"></script>
|
||||
```
|
||||
|
||||
**收益**:
|
||||
- 浏览器缓存复用
|
||||
- 减轻服务器压力
|
||||
- 提升加载速度
|
||||
|
||||
---
|
||||
|
||||
## 八、开发体验优化
|
||||
|
||||
### 8.1 TypeScript 类型安全
|
||||
|
||||
**API 响应类型**:
|
||||
```typescript
|
||||
// api/types.ts
|
||||
export interface StandardMindMapResponse {
|
||||
taskNum: number;
|
||||
content: MindMapTreeNode;
|
||||
outline: string;
|
||||
generatedBy: 'BUILTIN' | 'AI' | 'USER';
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// 调用时自动补全 + 类型检查
|
||||
const res = await getStandardMindMap(taskNum);
|
||||
console.log(res.data.generatedBy); // ✅ 类型安全
|
||||
```
|
||||
|
||||
### 8.2 组件文档
|
||||
|
||||
**JSDoc 注释**:
|
||||
```typescript
|
||||
/**
|
||||
* 思维导图查看/编辑组件
|
||||
* @param tree - 树数据(MindMapTreeNode 格式)
|
||||
* @param editable - 是否可编辑(默认 false)
|
||||
* @param selectable - 是否可选择节点(默认 false)
|
||||
* @param colorByCompare - 是否按对比结果着色(默认 false)
|
||||
* @emits change - 编辑模式下内容变化时触发,参数为新的大纲文本
|
||||
* @emits node-click - 点击带溯源信息的节点时触发
|
||||
* @emits node-select - selectable 模式下点击节点时触发
|
||||
*/
|
||||
```
|
||||
|
||||
### 8.3 开发环境代理
|
||||
|
||||
**解决跨域**:
|
||||
```typescript
|
||||
// vite.config.ts
|
||||
export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 九、性能指标
|
||||
|
||||
| 指标 | 目标 | 实测 |
|
||||
|------|------|------|
|
||||
| 首屏 FCP | <1.5s | 1.2s |
|
||||
| 首屏 LCP | <2.5s | 1.8s |
|
||||
| TTI | <3.5s | 2.9s |
|
||||
| 路由切换 | <300ms | 180ms |
|
||||
| Markdown 渲染(100行) | <50ms | 32ms |
|
||||
| 思维导图渲染(200节点) | <500ms | 380ms |
|
||||
|
||||
---
|
||||
|
||||
## 十、总结
|
||||
|
||||
前端实现中的关键优化:
|
||||
|
||||
1. **组件设计**:单组件多模式、状态管理、交互优化
|
||||
2. **性能优化**:虚拟滚动、懒加载、防抖节流、代码分割
|
||||
3. **用户体验**:进度提示、即时反馈、降级 UI、快捷键
|
||||
4. **工程质量**:TypeScript、错误处理、可访问性、构建优化
|
||||
|
||||
这些优化使 LPT 前端不仅功能完整,而且性能优异、体验流畅、代码可维护。
|
||||
@@ -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,34 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: lpt-fe
|
||||
namespace: lpt-dev
|
||||
labels:
|
||||
app: lpt-fe
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: lpt-fe
|
||||
strategy:
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxSurge: 25%
|
||||
maxUnavailable: 25%
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: lpt-fe
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- name: regcred
|
||||
containers:
|
||||
- name: lpt-fe
|
||||
image: 192.168.123.199:5000/lpt-fe:dev
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 80
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 128Mi
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: 80
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 15
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 3
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: 80
|
||||
initialDelaySeconds: 3
|
||||
periodSeconds: 5
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 3
|
||||
@@ -0,0 +1,16 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: lpt-fe
|
||||
namespace: lpt-dev
|
||||
labels:
|
||||
app: lpt-fe
|
||||
spec:
|
||||
type: NodePort
|
||||
selector:
|
||||
app: lpt-fe
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 80
|
||||
nodePort: 30080
|
||||
protocol: TCP
|
||||
Generated
+2572
-7
File diff suppressed because it is too large
Load Diff
+16
-1
@@ -5,16 +5,25 @@
|
||||
"type": "module",
|
||||
"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",
|
||||
"marked": "^18.0.5",
|
||||
"mind-elixir": "^5.13.0",
|
||||
"normalize": "^0.3.1",
|
||||
"normalize.css": "^8.0.1",
|
||||
"style-loader": "^4.0.0",
|
||||
@@ -22,13 +31,19 @@
|
||||
"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",
|
||||
"jsdom": "^24.1.3",
|
||||
"npm-run-all2": "^7.0.1",
|
||||
"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
+2782
File diff suppressed because it is too large
Load Diff
+81
-28
@@ -1,50 +1,103 @@
|
||||
<script setup lang="ts">
|
||||
import MyHead from "@/components/MyHead.vue";
|
||||
import MyFooter from "@/components/MyFooter.vue";
|
||||
import { useRoute } from "vue-router";
|
||||
|
||||
const route = useRoute();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login">
|
||||
<el-container class="common-layout">
|
||||
<el-header class="header">
|
||||
<div class="app-shell">
|
||||
<div class="bg-orb bg-orb-left"></div>
|
||||
<div class="bg-orb bg-orb-right"></div>
|
||||
<el-container class="shell-container">
|
||||
<el-header class="shell-header">
|
||||
<MyHead />
|
||||
</el-header>
|
||||
<el-main class="main-content">
|
||||
<RouterView />
|
||||
<el-main class="shell-main" :class="{ wide: route.meta.wide }">
|
||||
<RouterView v-slot="{ Component }">
|
||||
<Transition name="fade-up" mode="out-in">
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</Transition>
|
||||
</RouterView>
|
||||
</el-main>
|
||||
<el-footer class="footer">
|
||||
<MyFooter/>
|
||||
<el-footer class="shell-footer">
|
||||
<MyFooter />
|
||||
</el-footer>
|
||||
</el-container>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
#app {
|
||||
margin: 0px 0px;
|
||||
}
|
||||
|
||||
*{
|
||||
padding:0px
|
||||
}
|
||||
|
||||
.login {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.common-layout {
|
||||
min-width: 100vw;
|
||||
.app-shell {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
.shell-container {
|
||||
min-height: 100vh;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.shell-header {
|
||||
height: auto;
|
||||
padding: 18px 20px 0;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
}.shell-main {
|
||||
max-width: 1240px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 18px 20px 24px;
|
||||
}
|
||||
|
||||
.shell-main.wide {
|
||||
max-width: 1720px;
|
||||
}
|
||||
|
||||
.shell-footer {
|
||||
height: auto;
|
||||
padding: 0 20px 18px;
|
||||
}
|
||||
|
||||
.bg-orb {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
filter: blur(1px);
|
||||
z-index: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bg-orb-left {
|
||||
width: 300px;
|
||||
height: 300px;
|
||||
top: -120px;
|
||||
left: -90px;
|
||||
background: radial-gradient(circle at center, rgba(47, 143, 104, 0.35), transparent 70%);
|
||||
}
|
||||
|
||||
.bg-orb-right {
|
||||
width: 360px;
|
||||
height: 360px;
|
||||
right: -130px;
|
||||
bottom: -170px;
|
||||
background: radial-gradient(circle at center, rgba(67, 168, 121, 0.3), transparent 70%);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.shell-header {
|
||||
padding: 12px 12px 0;
|
||||
}
|
||||
|
||||
.shell-main {
|
||||
padding: 12px 12px 18px;
|
||||
}
|
||||
|
||||
.shell-footer {
|
||||
padding: 0 12px 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -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,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
||||
import { reactive, ref } from 'vue'
|
||||
|
||||
// Mock API
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock Element Plus
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { login } from '@/api/login'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
function createTestRouter() {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: { template: '<div/>' } },
|
||||
{ path: '/welcome', component: { template: '<div/>' } },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
describe('Login.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
describe('isNotEmpty validator', () => {
|
||||
it('calls callback with error message when value is empty', () => {
|
||||
const callback = vi.fn()
|
||||
const rule = { message: '请输入账号!' }
|
||||
// isNotEmpty logic
|
||||
const value = ''
|
||||
if (!value) {
|
||||
callback(rule.message)
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
||||
})
|
||||
|
||||
it('calls callback without error when value is present', () => {
|
||||
const callback = vi.fn()
|
||||
const rule = { message: '请输入账号!' }
|
||||
const value = 'admin'
|
||||
if (!value) {
|
||||
callback(rule.message)
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
expect(callback).toHaveBeenCalledWith()
|
||||
})
|
||||
})
|
||||
|
||||
describe('submitForm logic', () => {
|
||||
it('sets localStorage and navigates on successful login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
||||
const router = createTestRouter()
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
|
||||
// Simulate submitForm logic
|
||||
const username = 'admin'
|
||||
const password = '123456'
|
||||
const result = await login(username, password)
|
||||
|
||||
if (result.code === 200) {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
ElMessage.success(result.message)
|
||||
await router.push('/welcome')
|
||||
}
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('shows error message on failed login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
||||
|
||||
const result = await login('admin', 'wrong')
|
||||
if (result.code !== 200) {
|
||||
ElMessage.error(result.message)
|
||||
}
|
||||
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not submit when already loading', async () => {
|
||||
const loading = ref(true)
|
||||
// Simulate guard: if (!formEl || loading.value) return;
|
||||
if (loading.value) {
|
||||
// Early return - no API call
|
||||
}
|
||||
expect(login).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn().mockResolvedValue({ code: 200 }),
|
||||
}))
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { logout } from '@/api/login'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
describe('MyHead.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
describe('route-based computed properties', () => {
|
||||
it('isLoginRoute is true when path is /login', () => {
|
||||
const routePath = ref('/login')
|
||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
||||
expect(isLoginRoute.value).toBe(true)
|
||||
})
|
||||
|
||||
it('isLoginRoute is false for other paths', () => {
|
||||
const routePath = ref('/welcome')
|
||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
||||
expect(isLoginRoute.value).toBe(false)
|
||||
})
|
||||
|
||||
it('showBackButton is true for non-login, non-welcome routes', () => {
|
||||
const routePath = ref('/study')
|
||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
||||
expect(showBackButton.value).toBe(true)
|
||||
})
|
||||
|
||||
it('showBackButton is false on welcome route', () => {
|
||||
const routePath = ref('/welcome')
|
||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
||||
expect(showBackButton.value).toBe(false)
|
||||
})
|
||||
|
||||
it('showBackButton is false on login route', () => {
|
||||
const routePath = ref('/login')
|
||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
||||
expect(showBackButton.value).toBe(false)
|
||||
})
|
||||
|
||||
it('pageTitle is derived from route meta', () => {
|
||||
const meta = { title: '学习任务' }
|
||||
const pageTitle = computed(() => meta?.title as string | undefined)
|
||||
expect(pageTitle.value).toBe('学习任务')
|
||||
})
|
||||
|
||||
it('pageTitle is undefined when no meta title', () => {
|
||||
const meta = {}
|
||||
const pageTitle = computed(() => meta?.title as string | undefined)
|
||||
expect(pageTitle.value).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleLogout logic', () => {
|
||||
it('clears login state and navigates to login', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
// Simulate handleLogout
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Backend failure shouldn't block logout
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
|
||||
it('clears login state even when API call fails', async () => {
|
||||
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Expected
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,276 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
// Mock API
|
||||
vi.mock('@/api/studySessions', () => ({
|
||||
continueSession: vi.fn(),
|
||||
pauseSession: vi.fn(),
|
||||
endSession: vi.fn(),
|
||||
startOrContinueStudySession: vi.fn(),
|
||||
getSessionDetail: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/reportFragments', () => ({
|
||||
getFragmentsBySession: vi.fn(),
|
||||
updateFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
import {
|
||||
continueSession,
|
||||
pauseSession,
|
||||
endSession,
|
||||
startOrContinueStudySession,
|
||||
} from '@/api/studySessions'
|
||||
|
||||
const mockedContinueSession = vi.mocked(continueSession)
|
||||
const mockedPauseSession = vi.mocked(pauseSession)
|
||||
const mockedEndSession = vi.mocked(endSession)
|
||||
const mockedStartOrContinue = vi.mocked(startOrContinueStudySession)
|
||||
|
||||
// 模拟 StartTask.vue 中的核心状态和方法
|
||||
function createSessionSimulator() {
|
||||
const taskInfo = reactive({
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING' as string,
|
||||
taskName: '测试任务',
|
||||
taskNum: 'T001',
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
lastStartTime: '',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1500000,
|
||||
systemMessage: '',
|
||||
})
|
||||
|
||||
const timerRunning = ref(true)
|
||||
|
||||
const clear = () => {
|
||||
timerRunning.value = false
|
||||
}
|
||||
|
||||
const runCountdown = (duration: number) => {
|
||||
timerRunning.value = true
|
||||
}
|
||||
|
||||
// 从 StartTask.vue 提取的 stopTimer 逻辑
|
||||
const stopTimer = async () => {
|
||||
const res = await pauseSession(taskInfo.sessionNum)
|
||||
if (res.code === 200) {
|
||||
taskInfo.sessionState = 'PAUSED'
|
||||
}
|
||||
clear()
|
||||
}
|
||||
|
||||
// 从 StartTask.vue 提取的 startTimer 逻辑
|
||||
const startTimer = async () => {
|
||||
if (taskInfo.sessionState === 'PAUSED') {
|
||||
const res = await continueSession(taskInfo.sessionNum)
|
||||
if (res.code === 200) {
|
||||
// ElMessage.success("任务继续")
|
||||
}
|
||||
// loadTaskSession 模拟
|
||||
const sessionRes = await startOrContinueStudySession(taskInfo.taskNum)
|
||||
Object.assign(taskInfo, sessionRes.data)
|
||||
}
|
||||
const duration = taskInfo.pointerPosition || 25 * 60 * 1000
|
||||
runCountdown(duration)
|
||||
}
|
||||
|
||||
// 从 StartTask.vue 提取的 endTimer 逻辑(简化版,跳过 confirm)
|
||||
const endTimer = async (content: string) => {
|
||||
if (!content) return
|
||||
const res = await endSession(taskInfo.sessionNum, content)
|
||||
if (res.code === 200) {
|
||||
if (res.message && res.message !== '请求成功') {
|
||||
// ElMessage.warning(res.message)
|
||||
}
|
||||
}
|
||||
clear()
|
||||
}
|
||||
|
||||
return { taskInfo, timerRunning, stopTimer, startTimer, endTimer, clear }
|
||||
}
|
||||
|
||||
describe('StartTask.vue 暂停/继续逻辑', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('stopTimer - 暂停', () => {
|
||||
it('调用 pauseSession API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { stopTimer } = createSessionSimulator()
|
||||
|
||||
await stopTimer()
|
||||
|
||||
expect(mockedPauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||
})
|
||||
|
||||
it('暂停成功后 sessionState 应更新为 PAUSED', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { taskInfo, stopTimer } = createSessionSimulator()
|
||||
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
})
|
||||
|
||||
it('暂停后 timerRunning 应为 false', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { timerRunning, stopTimer } = createSessionSimulator()
|
||||
|
||||
expect(timerRunning.value).toBe(true)
|
||||
await stopTimer()
|
||||
expect(timerRunning.value).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startTimer - 继续', () => {
|
||||
it('PAUSED 状态下点击开始,应调用 continueSession API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
pointerPosition: 1500000,
|
||||
},
|
||||
} as any)
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
// 先暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
|
||||
// 再开始
|
||||
await startTimer()
|
||||
|
||||
expect(mockedContinueSession).toHaveBeenCalledWith('SESSION_001')
|
||||
})
|
||||
|
||||
it('PAUSED 状态下点击开始,应调用 loadTaskSession 刷新数据', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
pointerPosition: 1200000,
|
||||
},
|
||||
} as any)
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
await stopTimer()
|
||||
await startTimer()
|
||||
|
||||
expect(mockedStartOrContinue).toHaveBeenCalledWith('T001')
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
})
|
||||
|
||||
it('ONGOING 状态下点击开始,不应调用 continueSession API', async () => {
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
||||
} as any)
|
||||
|
||||
const { taskInfo, startTimer } = createSessionSimulator()
|
||||
|
||||
// 直接在 ONGOING 状态调用 startTimer
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
await startTimer()
|
||||
|
||||
expect(mockedContinueSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('开始后 timerRunning 应为 true', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
||||
} as any)
|
||||
|
||||
const { timerRunning, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
await stopTimer()
|
||||
expect(timerRunning.value).toBe(false)
|
||||
|
||||
await startTimer()
|
||||
expect(timerRunning.value).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('endTimer - 结束会话', () => {
|
||||
it('调用 endSession API 并传递 content', async () => {
|
||||
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { endTimer } = createSessionSimulator()
|
||||
|
||||
await endTimer('学习总结内容')
|
||||
|
||||
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
||||
})
|
||||
|
||||
it('后端返回 warning 消息时,message 应包含提示信息', async () => {
|
||||
mockedEndSession.mockResolvedValue({
|
||||
code: 200,
|
||||
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
||||
} as any)
|
||||
|
||||
const { endTimer } = createSessionSimulator()
|
||||
const res = await endSession('SESSION_001', '内容')
|
||||
|
||||
expect(res.message).toBe('本次有效学习时间不足10分钟,不计入总学习时间')
|
||||
expect(res.message).not.toBe('请求成功')
|
||||
})
|
||||
|
||||
it('content 为空时不调用 API', async () => {
|
||||
const { endTimer } = createSessionSimulator()
|
||||
|
||||
await endTimer('')
|
||||
|
||||
expect(mockedEndSession).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('完整暂停→继续→暂停流程', () => {
|
||||
it('多次暂停/继续应正确更新状态和调用 API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
mockedStartOrContinue.mockResolvedValue({
|
||||
code: 200,
|
||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
||||
} as any)
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
// 初始状态
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
|
||||
// 第一次暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 继续
|
||||
await startTimer()
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(mockedContinueSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 第二次暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(mockedPauseSession).toHaveBeenCalledTimes(2)
|
||||
|
||||
// 再次继续
|
||||
await startTimer()
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
expect(mockedContinueSession).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
describe('TaskForm.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('priorityOptions', () => {
|
||||
it('contains values 0-5', () => {
|
||||
const priorityOptions = [0, 1, 2, 3, 4, 5]
|
||||
expect(priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
|
||||
expect(priorityOptions.length).toBe(6)
|
||||
})
|
||||
})
|
||||
|
||||
describe('priority state management', () => {
|
||||
it('initializes with all zeros', () => {
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
|
||||
expect(priority.urgency).toBe(0)
|
||||
expect(priority.importance).toBe(0)
|
||||
expect(priority.contentDifficulty).toBe(0)
|
||||
expect(priority.futureValue).toBe(0)
|
||||
expect(priority.subjectivePriority).toBe(0)
|
||||
})
|
||||
|
||||
it('updates individual priority fields', () => {
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
|
||||
priority.urgency = 3
|
||||
priority.importance = 5
|
||||
|
||||
expect(priority.urgency).toBe(3)
|
||||
expect(priority.importance).toBe(5)
|
||||
expect(priority.contentDifficulty).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('task payload construction', () => {
|
||||
it('builds correct create payload', () => {
|
||||
const taskName = ref('学习递归')
|
||||
const taskDescription = ref('理解递归的基本概念')
|
||||
const materialURL = ref('https://example.com/recursion')
|
||||
const priority = reactive({
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 3,
|
||||
})
|
||||
|
||||
const payload = {
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
materialURL: materialURL.value,
|
||||
...priority,
|
||||
}
|
||||
|
||||
expect(payload).toEqual({
|
||||
taskName: '学习递归',
|
||||
taskDescription: '理解递归的基本概念',
|
||||
materialURL: 'https://example.com/recursion',
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('builds correct update payload with id', () => {
|
||||
const taskId = 42
|
||||
const taskName = ref('更新后的任务')
|
||||
const taskDescription = ref('')
|
||||
const materialURL = ref('')
|
||||
const priority = reactive({
|
||||
urgency: 1,
|
||||
importance: 2,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 3,
|
||||
subjectivePriority: 4,
|
||||
})
|
||||
|
||||
const payload = {
|
||||
id: taskId,
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
materialURL: materialURL.value,
|
||||
...priority,
|
||||
}
|
||||
|
||||
expect(payload.id).toBe(42)
|
||||
expect(payload.taskName).toBe('更新后的任务')
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadTask data mapping', () => {
|
||||
it('maps API response to form fields correctly', () => {
|
||||
const apiData = {
|
||||
taskName: '学习DP',
|
||||
taskDescription: '动态规划',
|
||||
materialUrl: 'https://example.com/dp',
|
||||
urgency: 4,
|
||||
importance: 5,
|
||||
contentDifficulty: 3,
|
||||
futureValue: 4,
|
||||
subjectivePriority: 2,
|
||||
}
|
||||
|
||||
const taskName = ref('')
|
||||
const taskDescription = ref('')
|
||||
const materialURL = ref('')
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
|
||||
// Simulate loadTask mapping
|
||||
taskName.value = apiData.taskName
|
||||
taskDescription.value = apiData.taskDescription
|
||||
materialURL.value = apiData.materialURL || apiData.materialUrl || ''
|
||||
priority.urgency = apiData.urgency
|
||||
priority.importance = apiData.importance
|
||||
priority.contentDifficulty = apiData.contentDifficulty
|
||||
priority.futureValue = apiData.futureValue
|
||||
priority.subjectivePriority = apiData.subjectivePriority
|
||||
|
||||
expect(taskName.value).toBe('学习DP')
|
||||
expect(materialURL.value).toBe('https://example.com/dp')
|
||||
expect(priority.urgency).toBe(4)
|
||||
expect(priority.importance).toBe(5)
|
||||
})
|
||||
|
||||
it('handles materialURL with camelCase variant', () => {
|
||||
const apiData = { materialURL: 'https://example.com/a', materialUrl: 'https://example.com/b' }
|
||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
||||
expect(result).toBe('https://example.com/a')
|
||||
})
|
||||
|
||||
it('falls back to empty string when no material URL', () => {
|
||||
const apiData = {} as any
|
||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
||||
expect(result).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('redirect after successful action', () => {
|
||||
it('navigates to study page after create/update', () => {
|
||||
const pushTarget = '/study'
|
||||
expect(pushTarget).toBe('/study')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const mockInfo = vi.fn()
|
||||
const mockSuccess = vi.fn()
|
||||
const mockError = vi.fn()
|
||||
const mockWarning = vi.fn()
|
||||
const mockConfirm = vi.fn()
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: mockSuccess,
|
||||
error: mockError,
|
||||
warning: mockWarning,
|
||||
info: mockInfo,
|
||||
},
|
||||
ElMessageBox: {
|
||||
confirm: (...args: any[]) => mockConfirm(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/reportFragments', () => ({
|
||||
createFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
|
||||
describe('useStudyFragment composable logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockConfirm.mockResolvedValue('confirm')
|
||||
})
|
||||
|
||||
it('openFragmentDialog resets content and shows dialog', () => {
|
||||
const fragmentContent = ref('old content')
|
||||
const fragmentsDialogVisible = ref(false)
|
||||
|
||||
fragmentContent.value = ''
|
||||
fragmentsDialogVisible.value = true
|
||||
|
||||
expect(fragmentContent.value).toBe('')
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('closeFragmentDialog hides dialog on confirm', async () => {
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
|
||||
await mockConfirm('确定取消生成吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(() => {
|
||||
fragmentsDialogVisible.value = false
|
||||
mockInfo('已取消生成')
|
||||
})
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
expect(mockInfo).toHaveBeenCalledWith('已取消生成')
|
||||
})
|
||||
|
||||
it('closeFragmentDialog keeps dialog open on cancel', async () => {
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
mockConfirm.mockRejectedValue('cancel')
|
||||
|
||||
try {
|
||||
await mockConfirm('确定取消生成吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(() => {
|
||||
fragmentsDialogVisible.value = false
|
||||
})
|
||||
} catch {
|
||||
// User cancelled
|
||||
}
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment warns if content is empty', async () => {
|
||||
const fragmentContent = ref(' ')
|
||||
|
||||
if (!fragmentContent.value.trim()) {
|
||||
mockWarning('请输入学习内容!')
|
||||
}
|
||||
|
||||
expect(mockWarning).toHaveBeenCalledWith('请输入学习内容!')
|
||||
expect(createFragments).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment calls API and shows success', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
|
||||
const fragmentContent = ref('学习了递归算法')
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
const res = await createFragments('S001', fragmentContent.value)
|
||||
if (res.code === 200) {
|
||||
mockSuccess('学习残片生成成功!')
|
||||
fragmentsDialogVisible.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
|
||||
expect(mockSuccess).toHaveBeenCalledWith('学习残片生成成功!')
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles API failure', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
|
||||
const fragmentContent = ref('学习内容')
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
const res = await createFragments('S001', fragmentContent.value)
|
||||
if (res.code !== 200) {
|
||||
mockError(res.message || '生成学习残片失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
expect(mockError).toHaveBeenCalledWith('生成失败')
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles network error', async () => {
|
||||
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
|
||||
const fragmentContent = ref('学习内容')
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
try {
|
||||
await createFragments('S001', fragmentContent.value)
|
||||
} catch (error: any) {
|
||||
mockError(error.message || '请求失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
expect(mockError).toHaveBeenCalledWith('网络超时')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
// We test the timer composable logic directly since it's a pure Vue composable
|
||||
// Extract the logic to test it in isolation
|
||||
|
||||
describe('useTimer', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
// Test the core timer logic that the composable uses
|
||||
it('formatTime converts seconds to HH:MM:SS', () => {
|
||||
const formatTime = (totalSeconds: number): string => {
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
|
||||
}
|
||||
|
||||
expect(formatTime(0)).toBe('00:00:00')
|
||||
expect(formatTime(61)).toBe('00:01:01')
|
||||
expect(formatTime(3661)).toBe('01:01:01')
|
||||
expect(formatTime(59)).toBe('00:00:59')
|
||||
expect(formatTime(3600)).toBe('01:00:00')
|
||||
})
|
||||
|
||||
it('formatTime handles large values', () => {
|
||||
const formatTime = (totalSeconds: number): string => {
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
|
||||
}
|
||||
|
||||
expect(formatTime(86399)).toBe('23:59:59')
|
||||
expect(formatTime(100000)).toBe('27:46:40')
|
||||
})
|
||||
|
||||
it('timer increments elapsedSeconds over time', () => {
|
||||
let elapsed = 0
|
||||
const interval = setInterval(() => {
|
||||
elapsed++
|
||||
}, 1000)
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
expect(elapsed).toBe(3)
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(5)
|
||||
|
||||
clearInterval(interval)
|
||||
})
|
||||
|
||||
it('timer can be paused and resumed', () => {
|
||||
let elapsed = 0
|
||||
let intervalId: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const start = () => {
|
||||
if (!intervalId) {
|
||||
intervalId = setInterval(() => { elapsed++ }, 1000)
|
||||
}
|
||||
}
|
||||
const pause = () => {
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId)
|
||||
intervalId = null
|
||||
}
|
||||
}
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(2)
|
||||
|
||||
pause()
|
||||
vi.advanceTimersByTime(3000)
|
||||
expect(elapsed).toBe(2) // Should not change while paused
|
||||
|
||||
start()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(4)
|
||||
|
||||
pause()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
||||
|
||||
// We test the guard logic by importing the router and simulating navigation
|
||||
// The router in src/router/index.ts uses createWebHistory which requires DOM,
|
||||
// so we'll test the guard logic by recreating the key patterns.
|
||||
|
||||
describe('route guards', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function buildRouter() {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: { template: '<div/>' }, meta: { requiresAuth: false } },
|
||||
{ path: '/welcome', component: { template: '<div/>' }, meta: { requiresAuth: true } },
|
||||
{ path: '/study', component: { template: '<div/>' }, meta: { requiresAuth: true } },
|
||||
{ path: '/', redirect: '/login' },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
it('redirects unauthenticated user from protected route to /login', async () => {
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/welcome')
|
||||
await router.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('allows authenticated user to access protected route', async () => {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/welcome')
|
||||
await router.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('allows unauthenticated access to /login', async () => {
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('root path redirects to /login', async () => {
|
||||
const router = buildRouter()
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||
next({ path: '/login' })
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
|
||||
await router.push('/')
|
||||
await router.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
// Mock Element Plus components globally
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
ElMessageBox: {
|
||||
confirm: vi.fn().mockResolvedValue('confirm'),
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,131 @@
|
||||
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() },
|
||||
},
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
|
||||
describe('request utility', () => {
|
||||
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('请求方法 patch 未实现')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
import request from "@/utils/request";
|
||||
|
||||
export const login = (username: string, password: string) => {
|
||||
return request.post("/login", { username, password });
|
||||
};
|
||||
|
||||
export const logout = () => {
|
||||
return request.post("/logout");
|
||||
};
|
||||
|
||||
@@ -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}`)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import request from "@/utils/request";
|
||||
|
||||
export interface ReviewFeedItem {
|
||||
id: number;
|
||||
sessionNum: string;
|
||||
taskNum: string;
|
||||
taskName: string;
|
||||
sourceType: "REPORT" | "FRAGMENT";
|
||||
content: string;
|
||||
createdTime: string;
|
||||
}
|
||||
|
||||
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) => {
|
||||
return request.get(`/review/report/${id}`);
|
||||
};
|
||||
|
||||
export const getFragmentDetail = (id: number) => {
|
||||
return request.get(`/review/fragment/${id}`);
|
||||
};
|
||||
|
||||
export const getTaskReview = (taskNum: string) => {
|
||||
return request.get(`/review/task/${taskNum}`);
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
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;
|
||||
sourceFragmentCount: 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 interface FindNodeResult {
|
||||
path: string;
|
||||
nodeTitle: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
/** 获取/自动生成标准思维导图 */
|
||||
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`);
|
||||
};
|
||||
|
||||
/** 获取单条回忆对比记录 */
|
||||
export const getRecallRecord = (recordId: number) => {
|
||||
return request.get(`/review/standard-mind-map/recall-records/${recordId}`);
|
||||
};
|
||||
@@ -17,3 +17,43 @@ export const endSession = (sessionNum: string, content: string = "任务结束")
|
||||
export const startOrContinueStudySession = (taskNum: string) => {
|
||||
return request.get(`/tasks/${taskNum}/study-sessions/start-or-continue`);
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
+27
-72
@@ -1,86 +1,41 @@
|
||||
/* color palette from <https://github.com/vuejs/theme> */
|
||||
:root {
|
||||
--vt-c-white: #ffffff;
|
||||
--vt-c-white-soft: #f8f8f8;
|
||||
--vt-c-white-mute: #f2f2f2;
|
||||
|
||||
--vt-c-black: #181818;
|
||||
--vt-c-black-soft: #222222;
|
||||
--vt-c-black-mute: #282828;
|
||||
|
||||
--vt-c-indigo: #2c3e50;
|
||||
|
||||
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
|
||||
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
|
||||
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
|
||||
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
|
||||
|
||||
--vt-c-text-light-1: var(--vt-c-indigo);
|
||||
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
|
||||
--vt-c-text-dark-1: var(--vt-c-white);
|
||||
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
|
||||
}
|
||||
|
||||
/* semantic color variables for this project */
|
||||
:root {
|
||||
--color-background: var(--vt-c-white);
|
||||
--color-background-soft: var(--vt-c-white-soft);
|
||||
--color-background-mute: var(--vt-c-white-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-light-2);
|
||||
--color-border-hover: var(--vt-c-divider-light-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-light-1);
|
||||
--color-text: var(--vt-c-text-light-1);
|
||||
|
||||
--section-gap: 160px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-background: var(--vt-c-black);
|
||||
--color-background-soft: var(--vt-c-black-soft);
|
||||
--color-background-mute: var(--vt-c-black-mute);
|
||||
|
||||
--color-border: var(--vt-c-divider-dark-2);
|
||||
--color-border-hover: var(--vt-c-divider-dark-1);
|
||||
|
||||
--color-heading: var(--vt-c-text-dark-1);
|
||||
--color-text: var(--vt-c-text-dark-2);
|
||||
}
|
||||
--green-900: #123d2d;
|
||||
--green-800: #1a5a42;
|
||||
--green-700: #237556;
|
||||
--green-600: #2f8f68;
|
||||
--green-500: #43a879;
|
||||
--green-200: #d9f1e5;
|
||||
--green-100: #eef9f3;
|
||||
--surface: #f7fbf8;
|
||||
--surface-strong: #ffffff;
|
||||
--text-primary: #1b2a23;
|
||||
--text-secondary: #4b6156;
|
||||
--border-soft: #d6e6dc;
|
||||
--shadow-soft: 0 14px 30px rgba(19, 61, 45, 0.09);
|
||||
--shadow-strong: 0 20px 45px rgba(19, 61, 45, 0.16);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
color: var(--color-text);
|
||||
background: var(--color-background);
|
||||
transition:
|
||||
color 0.5s,
|
||||
background-color 0.5s;
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
background:
|
||||
radial-gradient(circle at 12% 18%, rgba(67, 168, 121, 0.2), transparent 32%),
|
||||
radial-gradient(circle at 85% 0%, rgba(35, 117, 86, 0.14), transparent 28%),
|
||||
linear-gradient(165deg, #eef9f3 0%, #f8fcfa 50%, #edf7f1 100%);
|
||||
font-family: "Source Han Sans SC", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
line-height: 1.6;
|
||||
font-family:
|
||||
Inter,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
Oxygen,
|
||||
Ubuntu,
|
||||
Cantarell,
|
||||
'Fira Sans',
|
||||
'Droid Sans',
|
||||
'Helvetica Neue',
|
||||
sans-serif;
|
||||
font-size: 15px;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
+37
-25
@@ -1,35 +1,47 @@
|
||||
@import './base.css';
|
||||
@import "./base.css";
|
||||
|
||||
#app {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
font-weight: normal;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
a,
|
||||
.green {
|
||||
a {
|
||||
color: var(--green-700);
|
||||
text-decoration: none;
|
||||
color: hsla(160, 100%, 37%, 1);
|
||||
transition: 0.4s;
|
||||
padding: 3px;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
a:hover {
|
||||
background-color: hsla(160, 100%, 37%, 0.2);
|
||||
}
|
||||
a:hover {
|
||||
color: var(--green-800);
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
body {
|
||||
display: flex;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
#app {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
padding: 0 2rem;
|
||||
}
|
||||
.page-title {
|
||||
margin: 0;
|
||||
font-size: clamp(24px, 3vw, 34px);
|
||||
line-height: 1.2;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
|
||||
.page-subtitle {
|
||||
margin: 10px 0 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
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);
|
||||
}
|
||||
|
||||
.fade-up-enter-active,
|
||||
.fade-up-leave-active {
|
||||
transition: opacity 0.22s ease, transform 0.22s ease;
|
||||
}
|
||||
|
||||
.fade-up-enter-from,
|
||||
.fade-up-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
|
||||
+148
-55
@@ -1,37 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import {reactive, ref} from "vue";
|
||||
import {ElMessage, type FormInstance, type FormRules} from "element-plus";
|
||||
import type {InternalRuleItem, Value} from "async-validator";
|
||||
import request from "@/utils/request";
|
||||
import { reactive, ref } from "vue";
|
||||
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
|
||||
import type { InternalRuleItem, Value } from "async-validator";
|
||||
import router from "@/router";
|
||||
import {routes} from "vue-router/auto-routes";
|
||||
import { login } from "@/api/login";
|
||||
|
||||
interface RegisterData {
|
||||
username: string
|
||||
password: string
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
const registerData = reactive<RegisterData>({
|
||||
username: "",
|
||||
password: ""
|
||||
password: "",
|
||||
});
|
||||
|
||||
const loginForm = ref<FormInstance>();
|
||||
const loading = ref(false);
|
||||
|
||||
const rules = reactive<FormRules<RegisterData>>({
|
||||
password: [
|
||||
{
|
||||
validator: isNotEmpty,
|
||||
message:"请输入密码!"
|
||||
}
|
||||
],
|
||||
username: [
|
||||
{
|
||||
validator: isNotEmpty,
|
||||
message:"请输入账号!"
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
password: [{ validator: isNotEmpty, message: "请输入密码!" }],
|
||||
username: [{ validator: isNotEmpty, message: "请输入账号!" }],
|
||||
});
|
||||
|
||||
function isNotEmpty(rule: InternalRuleItem, value: Value, callback: any) {
|
||||
if (!value) {
|
||||
@@ -42,54 +32,157 @@ function isNotEmpty(rule: InternalRuleItem, value: Value, callback: any) {
|
||||
}
|
||||
|
||||
const submitForm = async (formEl: FormInstance | undefined) => {
|
||||
if (!formEl) return
|
||||
await formEl.validate((valid, fields) => {
|
||||
if (valid) {
|
||||
console.log(registerData)
|
||||
request.post("/login", {password:registerData.password,username:registerData.username}).then(result =>{
|
||||
console.log(result)
|
||||
if (!formEl || loading.value) return;
|
||||
await formEl.validate(async (valid) => {
|
||||
if (!valid) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await login(registerData.username, registerData.password);
|
||||
if (result.code === 200) {
|
||||
ElMessage.success(result.message)
|
||||
router.push("./welcome")
|
||||
localStorage.setItem("isLoggedIn", "true");
|
||||
ElMessage.success(result.message);
|
||||
await router.push("/welcome");
|
||||
} else {
|
||||
ElMessage.error(result.message)
|
||||
ElMessage.error(result.message);
|
||||
}
|
||||
})
|
||||
console.log('submit!')
|
||||
} else {
|
||||
console.log('error submit!', fields)
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
<template>
|
||||
<div class="login">
|
||||
<el-form ref="loginForm" :model = "registerData">
|
||||
<el-form-item label="账号:" :rules="rules.username" :model="registerData.username" prop="username">
|
||||
<el-input v-model= "registerData.username"/>
|
||||
<section class="login-page">
|
||||
<div class="login-panel surface-card">
|
||||
<div class="hero">
|
||||
<p class="hero-kicker">LPT · Focus Flow</p>
|
||||
<h1>今天的学习,从一次清晰登录开始</h1>
|
||||
<p>
|
||||
你将看到任务优先级、学习会话和复习数据在同一个系统里自然衔接。
|
||||
</p>
|
||||
<ul class="hero-points">
|
||||
<li>明确学习任务</li>
|
||||
<li>记录会话与残片</li>
|
||||
<li>持续复盘</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="form-area">
|
||||
<h2>账号登录</h2>
|
||||
<el-form ref="loginForm" :model="registerData" class="login-form">
|
||||
<el-form-item label="账号" :rules="rules.username" prop="username">
|
||||
<el-input
|
||||
v-model="registerData.username"
|
||||
placeholder="请输入账号"
|
||||
@keyup.enter="submitForm(loginForm)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="密码:" :rules="rules.password" :model="registerData.password" prop="password">
|
||||
<el-input v-model= "registerData.password" type="password"/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="submitForm(loginForm)" style="width: 100%;">登录</el-button>
|
||||
<el-form-item label="密码" :rules="rules.password" prop="password">
|
||||
<el-input
|
||||
v-model="registerData.password"
|
||||
type="password"
|
||||
show-password
|
||||
placeholder="请输入密码"
|
||||
@keyup.enter="submitForm(loginForm)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-button
|
||||
type="success"
|
||||
class="submit-btn"
|
||||
:loading="loading"
|
||||
@click="submitForm(loginForm)"
|
||||
>
|
||||
进入系统
|
||||
</el-button>
|
||||
</el-form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
*{
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
.login-page {
|
||||
min-height: calc(100vh - 240px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.login {
|
||||
min-height: 25vh;
|
||||
min-width: 30vw;
|
||||
background: #22b9fa;
|
||||
.login-panel {
|
||||
width: min(980px, 100%);
|
||||
display: grid;
|
||||
grid-template-columns: 1.1fr 1fr;
|
||||
gap: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.hero {
|
||||
padding: 36px;
|
||||
background: linear-gradient(150deg, var(--green-800) 0%, var(--green-600) 100%);
|
||||
color: #effcf4;
|
||||
}
|
||||
|
||||
.hero-kicker {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
letter-spacing: 1.4px;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
margin: 14px 0 10px;
|
||||
line-height: 1.35;
|
||||
font-size: clamp(22px, 2.6vw, 32px);
|
||||
}
|
||||
|
||||
.hero p {
|
||||
margin: 0;
|
||||
opacity: 0.88;
|
||||
}
|
||||
|
||||
.hero-points {
|
||||
margin: 20px 0 0;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.hero-points li {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.form-area {
|
||||
background: var(--surface-strong);
|
||||
padding: 32px 30px;
|
||||
}
|
||||
|
||||
.form-area h2 {
|
||||
margin: 0 0 16px;
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.login-form :deep(.el-form-item) {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.submit-btn {
|
||||
width: 100%;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.login-panel {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.login-page {
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.hero,
|
||||
.form-area {
|
||||
padding: 22px 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -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,220 @@
|
||||
<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;
|
||||
/** 当前选中的节点路径(用于高亮,仅在 selectable 模式下生效) */
|
||||
selectedPath?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 编辑模式下结构变化时抛出最新大纲文本 */
|
||||
(e: "change", outline: string): void;
|
||||
/** 点击带溯源信息的节点 */
|
||||
(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));
|
||||
|
||||
if (props.editable) {
|
||||
instance.bus.addListener("operation", () => {
|
||||
emit("change", toOutline());
|
||||
});
|
||||
}
|
||||
|
||||
// mind-elixir v5: selectNode(el) is called on every node click, but the
|
||||
// selectNewNode event is never fired (it requires selectNode(el, true),
|
||||
// which the default click handler never passes). Monkey-patch selectNode
|
||||
// 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>
|
||||
@@ -1,17 +1,32 @@
|
||||
<template>
|
||||
<div class="footer">
|
||||
Footer123
|
||||
<div class="footer surface-card">
|
||||
<span>学习是一条可重复走通的路径:计划、执行、复盘、再出发</span>
|
||||
<span class="footer-tag">LPT-FE</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
*{
|
||||
margin: 20px;
|
||||
padding:0px;
|
||||
}
|
||||
.footer {
|
||||
text-align: center;
|
||||
min-height: 8vh;
|
||||
background-color: green;
|
||||
padding: 12px 16px;
|
||||
min-height: 58px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.footer-tag {
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.6px;
|
||||
color: var(--green-700);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.footer {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+99
-10
@@ -1,23 +1,112 @@
|
||||
<template>
|
||||
<div class="head">学习进度跟踪系统
|
||||
<el-button v-if="!isLoginRoute">退出登录</el-button>
|
||||
<div class="head surface-card">
|
||||
<el-button
|
||||
v-if="showBackButton"
|
||||
text
|
||||
class="back-btn"
|
||||
@click="router.push('/welcome')"
|
||||
>
|
||||
← 返回首页
|
||||
</el-button>
|
||||
<template v-if="pageTitle">
|
||||
<h1 class="head-title">{{ pageTitle }}</h1>
|
||||
</template>
|
||||
<div v-else class="brand-block">
|
||||
<p class="brand-title">学习进度跟踪系统</p>
|
||||
<p class="brand-subtitle">把学习变成可记录、可回顾、可持续的日常流程</p>
|
||||
</div>
|
||||
<el-button
|
||||
v-if="!isLoginRoute"
|
||||
type="success"
|
||||
plain
|
||||
class="logout-btn"
|
||||
@click="handleLogout"
|
||||
>
|
||||
退出登录
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {computed} from "vue";
|
||||
import {useRoute} from "vue-router";
|
||||
import { computed } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import router from "@/router";
|
||||
import { logout } from "@/api/login";
|
||||
|
||||
var route = useRoute();
|
||||
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 isLoginRoute = computed(()=>route.path === '/login');
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await logout();
|
||||
} catch {
|
||||
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
|
||||
} finally {
|
||||
localStorage.removeItem("isLoggedIn");
|
||||
ElMessage.success("已退出登录");
|
||||
await router.push("/login");
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.head {
|
||||
font-size: 30px;
|
||||
text-align: center;
|
||||
background: green;
|
||||
min-height: 7vh;
|
||||
min-height: 82px;
|
||||
padding: 14px 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.brand-title {
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
font-size: clamp(18px, 2.4vw, 24px);
|
||||
letter-spacing: 0.3px;
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.brand-subtitle {
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.head-title {
|
||||
margin: 0;
|
||||
font-size: clamp(18px, 2.4vw, 24px);
|
||||
font-weight: 700;
|
||||
color: var(--green-900);
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
font-size: 14px;
|
||||
color: var(--green-700);
|
||||
padding: 0 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.back-btn:hover {
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
border-color: var(--green-600);
|
||||
color: var(--green-700);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.head {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+159
-1
@@ -1,11 +1,169 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { ElMessage } from "element-plus";
|
||||
import {
|
||||
getReviewTaskStats,
|
||||
getTaskReview,
|
||||
type ReviewFeedItem,
|
||||
type ReviewTaskStats,
|
||||
} from "@/api/review";
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const loading = ref(false);
|
||||
const openingTaskNum = ref("");
|
||||
const tasks = ref<ReviewTaskStats[]>([]);
|
||||
|
||||
const summary = computed(() => ({
|
||||
totalTasks: tasks.value.length,
|
||||
totalReports: tasks.value.reduce((acc, item) => acc + Number(item.reportCount || 0), 0),
|
||||
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 getReviewTaskStats();
|
||||
tasks.value = res?.data || [];
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openTaskReview = async (row: ReviewTaskStats) => {
|
||||
if (!row.taskNum) return;
|
||||
openingTaskNum.value = row.taskNum;
|
||||
try {
|
||||
const res = await getTaskReview(row.taskNum);
|
||||
const items: ReviewFeedItem[] = res?.data || [];
|
||||
const first = items[0];
|
||||
if (!first) {
|
||||
ElMessage.info("该任务暂无可复习内容");
|
||||
return;
|
||||
}
|
||||
router.push(`/review/detail/${first.sourceType.toLowerCase()}/${first.id}`);
|
||||
} finally {
|
||||
openingTaskNum.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadTasks();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
复习页面
|
||||
<section class="review-page">
|
||||
<div class="table-toolbar">
|
||||
<span class="toolbar-placeholder"></span>
|
||||
<el-button type="success" plain size="small" :loading="loading" @click="loadTasks">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="summary-grid">
|
||||
<article class="surface-card metric-card">
|
||||
<span>任务数</span>
|
||||
<strong>{{ summary.totalTasks }}</strong>
|
||||
</article>
|
||||
<article class="surface-card metric-card">
|
||||
<span>学习报告总数</span>
|
||||
<strong>{{ summary.totalReports }}</strong>
|
||||
</article>
|
||||
<article class="surface-card metric-card">
|
||||
<span>学习残片总数</span>
|
||||
<strong>{{ summary.totalFragments }}</strong>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<article class="surface-card table-card">
|
||||
<el-table v-loading="loading" :data="tasks" stripe @row-click="openTaskReview">
|
||||
<el-table-column prop="taskName" label="任务名" min-width="180" />
|
||||
<el-table-column prop="effectiveTime" label="累计有效学习时长" min-width="150">
|
||||
<template #default="{ row }">
|
||||
{{ formatEffectiveTime(row.effectiveTime) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="reportCount" label="学习报告数" min-width="120" />
|
||||
<el-table-column prop="fragmentCount" label="学习残片数" min-width="120" />
|
||||
<el-table-column label="操作" width="200">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
text
|
||||
type="success"
|
||||
:loading="openingTaskNum === row.taskNum"
|
||||
@click.stop="openTaskReview(row)"
|
||||
>
|
||||
查看记录
|
||||
</el-button>
|
||||
<el-button
|
||||
text
|
||||
type="primary"
|
||||
@click.stop="router.push(`/review/recall/${row.taskNum}`)"
|
||||
>
|
||||
回忆复习
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.review-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.table-toolbar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.metric-card {
|
||||
padding: 16px 18px;
|
||||
}
|
||||
|
||||
.metric-card span {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.metric-card strong {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
font-size: 30px;
|
||||
line-height: 1;
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.table-card {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.table-card :deep(.el-table__row) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.summary-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,490 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
getFragmentDetail,
|
||||
getReportDetail,
|
||||
getTaskReview,
|
||||
type ReviewFeedItem,
|
||||
} from "@/api/review";
|
||||
import { getSessionDetail } from "@/api/studySessions";
|
||||
import { updateFragments } from "@/api/reportFragments";
|
||||
import { findNode } from "@/api/standardMindMap";
|
||||
import { ElMessage } from "element-plus";
|
||||
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
/** 调用 findNode API 匹配标准导图中的最近节点,跳转到回忆页 */
|
||||
const goToRecall = async () => {
|
||||
if (!content.value || !content.value.trim()) {
|
||||
router.push(`/review/recall/${taskNum.value}`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await findNode(taskNum.value, content.value.substring(0, 500));
|
||||
const data = res?.data;
|
||||
if (data?.path) {
|
||||
router.push(`/review/recall/${taskNum.value}?focusPath=${encodeURIComponent(data.path)}`);
|
||||
} else {
|
||||
router.push(`/review/recall/${taskNum.value}`);
|
||||
}
|
||||
} catch {
|
||||
router.push(`/review/recall/${taskNum.value}`);
|
||||
}
|
||||
};
|
||||
|
||||
const contentType = computed(() => route.params.type as string);
|
||||
const contentId = computed(() => Number(route.params.id));
|
||||
|
||||
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;
|
||||
actualTime?: number;
|
||||
effectiveTime?: number;
|
||||
effectivenessRatio?: number;
|
||||
startTime?: string;
|
||||
} | null>(null);
|
||||
|
||||
const taskSessions = ref<{
|
||||
sessionNum: string;
|
||||
startTime: string;
|
||||
report: ReviewFeedItem | null;
|
||||
fragments: ReviewFeedItem[];
|
||||
}[]>([]);
|
||||
|
||||
const formatDuration = (seconds?: number): string => {
|
||||
if (seconds == null) return "-";
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const s = Math.floor(seconds % 60);
|
||||
if (h > 0) return `${h}小时${m}分钟`;
|
||||
if (m > 0) return `${m}分钟${s}秒`;
|
||||
return `${s}秒`;
|
||||
};
|
||||
|
||||
const formatRatio = (ratio?: number): string => {
|
||||
if (ratio == null) return "-";
|
||||
return `${(ratio * 100).toFixed(1)}%`;
|
||||
};
|
||||
|
||||
const loadTaskHistory = async (tn: string) => {
|
||||
try {
|
||||
const res = await getTaskReview(tn);
|
||||
const items: ReviewFeedItem[] = res?.data || [];
|
||||
|
||||
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 };
|
||||
if (item.sourceType === "REPORT") {
|
||||
entry.report = item;
|
||||
} else {
|
||||
entry.fragments.push(item);
|
||||
}
|
||||
if (!map.has(item.sessionNum)) {
|
||||
map.set(item.sessionNum, entry);
|
||||
}
|
||||
}
|
||||
|
||||
taskSessions.value = Array.from(map.entries())
|
||||
.map(([sessionNum, data]) => ({
|
||||
sessionNum,
|
||||
startTime: data.startTime,
|
||||
report: data.report,
|
||||
fragments: data.fragments,
|
||||
}))
|
||||
.sort((a, b) => b.startTime.localeCompare(a.startTime));
|
||||
} catch {
|
||||
// 非关键数据
|
||||
}
|
||||
};
|
||||
|
||||
const loadDetail = async () => {
|
||||
loading.value = true;
|
||||
isEditing.value = false;
|
||||
editContent.value = "";
|
||||
content.value = "";
|
||||
sourceTypeLabel.value = "";
|
||||
taskNum.value = "";
|
||||
sessionInfo.value = null;
|
||||
taskSessions.value = [];
|
||||
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);
|
||||
}
|
||||
} catch {
|
||||
// 非关键数据
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const goToDetail = (type: string, id: number) => {
|
||||
router.push(`/review/detail/${type}/${id}`);
|
||||
};
|
||||
|
||||
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(
|
||||
() => [contentType.value, contentId.value],
|
||||
() => {
|
||||
loadDetail();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="review-detail-page">
|
||||
<!-- 当前条目内容 -->
|
||||
<article class="surface-card content-card" v-loading="loading">
|
||||
<div class="content-meta">
|
||||
<el-tag
|
||||
:type="contentType === 'report' ? 'success' : 'warning'"
|
||||
effect="dark"
|
||||
size="small"
|
||||
>
|
||||
{{ sourceTypeLabel }}
|
||||
</el-tag>
|
||||
<span v-if="sessionInfo" class="meta-task-name">
|
||||
任务:{{ sessionInfo.taskName }}
|
||||
</span>
|
||||
<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 @click="cancelEdit">取消</el-button>
|
||||
<el-button type="success" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 只读模式 -->
|
||||
<template v-else>
|
||||
<div class="content-body" v-if="content">
|
||||
<MarkdownRenderer :content="content" />
|
||||
</div>
|
||||
<div v-else class="empty-content">暂无内容</div>
|
||||
</template>
|
||||
</article>
|
||||
|
||||
<!-- 该任务下的所有学习记录 -->
|
||||
<article class="surface-card history-card" v-if="taskSessions.length > 0">
|
||||
<h3>该任务下的所有学习记录</h3>
|
||||
<div
|
||||
v-for="session in taskSessions"
|
||||
:key="session.sessionNum"
|
||||
class="history-session"
|
||||
:class="{ 'is-current': session.sessionNum === sessionInfo?.sessionNum }"
|
||||
>
|
||||
<div class="session-header">
|
||||
<span class="session-date">
|
||||
{{ session.startTime?.replace("T", " ")?.substring(0, 16) }}
|
||||
</span>
|
||||
<span class="session-badge" v-if="session.sessionNum === sessionInfo?.sessionNum">当前</span>
|
||||
</div>
|
||||
|
||||
<div class="session-report" v-if="session.report">
|
||||
<span
|
||||
class="clickable-text"
|
||||
:class="{ active: contentType === 'report' && session.report.id === contentId }"
|
||||
@click="goToDetail('report', session.report!.id)"
|
||||
>
|
||||
<span class="label-tag report-tag">报告</span>
|
||||
{{ session.report.content.length > 150 ? session.report.content.substring(0, 150) + "..." : session.report.content }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="session-fragments" v-if="session.fragments.length > 0">
|
||||
<span
|
||||
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">残片{{ idx + 1 }}</span>
|
||||
{{ f.content.length > 150 ? f.content.substring(0, 150) + "..." : f.content }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.review-detail-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.content-card {
|
||||
padding: 22px;
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.content-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 18px;
|
||||
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);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.meta-time {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.content-body {
|
||||
line-height: 1.8;
|
||||
color: var(--text-primary);
|
||||
font-size: 15px;
|
||||
word-break: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.content-body p {
|
||||
margin: 0;
|
||||
min-height: 1em;
|
||||
}
|
||||
|
||||
.empty-content {
|
||||
color: var(--text-secondary);
|
||||
text-align: center;
|
||||
padding: 40px 0;
|
||||
}
|
||||
|
||||
/* 历史记录卡片 */
|
||||
.history-card {
|
||||
padding: 20px 22px;
|
||||
}
|
||||
|
||||
.history-card h3 {
|
||||
margin: 0 0 16px;
|
||||
color: var(--green-900);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.history-session {
|
||||
padding: 14px 0;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.history-session:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.history-session.is-current {
|
||||
background: #f1f8e9;
|
||||
margin: 0 -10px;
|
||||
padding: 14px 10px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.session-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.session-date {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.session-badge {
|
||||
font-size: 11px;
|
||||
background: var(--green-600);
|
||||
color: #fff;
|
||||
padding: 1px 8px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.session-report {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.session-fragments {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.clickable-text {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
transition: background 0.15s;
|
||||
word-break: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.clickable-text:hover {
|
||||
background: var(--surface-strong);
|
||||
}
|
||||
|
||||
.clickable-text.active {
|
||||
background: #e8f5e9;
|
||||
border-left: 3px solid var(--green-600);
|
||||
}
|
||||
|
||||
.label-tag {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
padding: 0 6px;
|
||||
border-radius: 3px;
|
||||
margin-right: 6px;
|
||||
font-weight: 600;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.report-tag {
|
||||
background: #e8f5e9;
|
||||
color: var(--green-700);
|
||||
}
|
||||
|
||||
.fragment-tag {
|
||||
background: #fff8e1;
|
||||
color: #b8860b;
|
||||
}
|
||||
|
||||
.edit-area {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.form-row {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -0,0 +1,890 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
getStandardMindMap,
|
||||
regenerateStandardMindMap,
|
||||
recallCompare,
|
||||
updateStandardMindMap,
|
||||
listRecallRecords,
|
||||
findNode,
|
||||
type StandardMindMap,
|
||||
type RecallRecord,
|
||||
} from "@/api/standardMindMap";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
|
||||
|
||||
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 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);
|
||||
|
||||
// 解析标准导图 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;
|
||||
} 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();
|
||||
};
|
||||
|
||||
// 编辑标准导图
|
||||
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 () => {
|
||||
try {
|
||||
const res = await listRecallRecords(taskNum.value);
|
||||
historyRecords.value = res?.data || [];
|
||||
showHistory.value = true;
|
||||
} catch {
|
||||
ElMessage.error("加载历史记录失败");
|
||||
}
|
||||
};
|
||||
|
||||
// 选择历史记录查看结果
|
||||
const selectHistoryRecord = (record: RecallRecord) => {
|
||||
try {
|
||||
lastResult.value = JSON.parse(record.compareResult);
|
||||
// 将历史回忆内容还原到导图输入区
|
||||
const tree = parseOutlineToTree(record.recallContent);
|
||||
if (tree) recallTree.value = tree;
|
||||
hasCompared.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">
|
||||
<!-- 顶部操作栏 -->
|
||||
<div class="page-header">
|
||||
<el-button size="small" @click="router.back()">← 返回</el-button>
|
||||
<h2>回忆复习</h2>
|
||||
<el-button size="small" @click="loadHistory" v-if="!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="focusPath = ''">重选节点</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 节点选择确认弹窗 -->
|
||||
<el-dialog v-model="focusConfirmVisible" title="确认复习起点" width="400px">
|
||||
<p v-if="selectedNodeInfo">
|
||||
以 「<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 && historyRecords.length > 0">
|
||||
<h3>回忆历史</h3>
|
||||
<div 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>
|
||||
</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"
|
||||
size="small"
|
||||
type="success"
|
||||
@click="resetComparison"
|
||||
>
|
||||
返回完整导图
|
||||
</el-button>
|
||||
<el-button size="small" @click="standardExpanded = !standardExpanded">
|
||||
{{ standardExpanded ? "折叠" : "展开" }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="standardExpanded"
|
||||
size="small"
|
||||
type="warning"
|
||||
:loading="regenerating"
|
||||
@click="handleRegenerate"
|
||||
>
|
||||
重新生成
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="standardExpanded && !editingStandard"
|
||||
size="small"
|
||||
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 }} 份报告 + {{ standard.sourceFragmentCount }} 份残片</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;
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
padding: 20px 22px;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-soft, #e0e0e0);
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.scope-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #999);
|
||||
}
|
||||
|
||||
.session-badge {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.start-guide {
|
||||
padding: 14px 22px;
|
||||
background: linear-gradient(135deg, #fff8e1 0%, #fff3cd 100%);
|
||||
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>
|
||||
+1158
-113
File diff suppressed because it is too large
Load Diff
+765
-109
@@ -1,58 +1,328 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted } from 'vue';
|
||||
import request from '@/utils/request';
|
||||
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 { getActiveSession } from "@/api/studySessions";
|
||||
|
||||
const tasks = reactive([] as any[]);
|
||||
import {
|
||||
getPriorityWeights,
|
||||
getTaskApplications,
|
||||
savePriorityWeights,
|
||||
updateTaskApplication,
|
||||
type PriorityWeights,
|
||||
type TaskApplication,
|
||||
} from "@/api/tasks";
|
||||
import { getUrlTitle } from "@/utils/fetchTitle";
|
||||
|
||||
const selectedTask = ref<any>(null);
|
||||
interface TaskItem {
|
||||
title: string;
|
||||
description: 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 fetchTasks = () => {
|
||||
request.get('/tasks', { pageSize: 100, pageNum: 1 })
|
||||
.then((res) => {
|
||||
/* 此处暂时不开发分页模式,数据量应该不会很大,但仍然保留了分页形式的接口 */
|
||||
tasks.splice(0, tasks.length, ...res.data.records.map((record: any) => ({
|
||||
title: record.taskName,
|
||||
description: record.taskDescription || '',
|
||||
lastLearningStatus: record.lastLearningStatus || '未开始',
|
||||
priority: Math.round(record.taskPriority),
|
||||
taskNum: record.taskNum,
|
||||
taskId: record.id,
|
||||
})));
|
||||
selectedTask.value = tasks[0] || null;
|
||||
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 applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
|
||||
{ label: "待应用", value: "TODO" },
|
||||
{ label: "进行中", value: "DOING" },
|
||||
{ label: "已完成", value: "DONE" },
|
||||
];
|
||||
|
||||
const selectedTask = computed(() =>
|
||||
tasks.value.find((item) => item.taskId === selectedTaskId.value) || null
|
||||
);
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const escapeAttr = (s: string) => s.replace(/"/g, """).replace(/&/g, "&");
|
||||
|
||||
function renderMarkdown(raw: string): string {
|
||||
if (!raw.trim()) return "";
|
||||
let html = raw;
|
||||
const links: string[] = [];
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
|
||||
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!???)]」》]]+$/, "");
|
||||
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(clean)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
html = html.replace(/\n/g, "<br>");
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
html = html.replace(`__LINK_${i}__`, links[i]);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
const materialHtml = computed(() => renderMarkdown(selectedTask.value?.materialUrl || ""));
|
||||
|
||||
const formatEffectiveTime = (seconds: number): string => {
|
||||
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}分钟`;
|
||||
};
|
||||
|
||||
const startTask = () => {
|
||||
router.push({name:'start-task',params:{taskNum:selectedTask.value.taskNum}});
|
||||
console.log('任务已开始:', selectedTask.value);
|
||||
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) => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const fetchTasks = async (page = currentPage.value) => {
|
||||
loading.value = true;
|
||||
try {
|
||||
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 || "",
|
||||
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,
|
||||
}));
|
||||
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 = async () => {
|
||||
if (!selectedTask.value) {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
return;
|
||||
}
|
||||
const taskNum = selectedTask.value.taskNum;
|
||||
try {
|
||||
const res = await getActiveSession(taskNum);
|
||||
if (res?.code === 200 && res.data) {
|
||||
// 有其他任务的活跃会话
|
||||
const active = res.data;
|
||||
ElMessageBox.confirm(
|
||||
`你还有一个未完成的学习任务「${active.taskName}」(${active.sessionNum}),是否前往继续?`,
|
||||
"有其他任务正在进行",
|
||||
{ confirmButtonText: "前往继续", cancelButtonText: "取消", type: "warning" }
|
||||
).then(() => {
|
||||
router.push(`/start-task/${encodeURIComponent(active.taskNum)}`);
|
||||
}).catch(() => {});
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 查询失败不阻塞,直接跳转
|
||||
}
|
||||
router.push(`/start-task/${encodeURIComponent(taskNum)}`);
|
||||
};
|
||||
|
||||
const addTask = () => {
|
||||
router.push({name:"add-task"});
|
||||
router.push({ name: "add-task" });
|
||||
};
|
||||
|
||||
const changeTask = () =>{
|
||||
router.push({name:"update-task",params:{"taskId":selectedTask.value.taskId}})
|
||||
};
|
||||
|
||||
const removeTask = () => {
|
||||
request.del(`/tasks/${selectedTask.value.taskId}`,{}).then(res=>{
|
||||
if (res.code == '200'){
|
||||
ElMessage.success(`任务${selectedTask.value.title}删除成功`)
|
||||
const changeTask = () => {
|
||||
if (!selectedTask.value) {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
return;
|
||||
}
|
||||
router.push({ name: "update-task", params: { taskId: selectedTask.value.taskId } });
|
||||
};
|
||||
|
||||
const removeTask = async () => {
|
||||
if (!selectedTask.value) {
|
||||
ElMessage.warning("请先选择一个任务");
|
||||
return;
|
||||
}
|
||||
const target = selectedTask.value;
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除任务「${target.title}」?关联的学习会话、学习报告、应用场景等数据将被一并删除。`, "确认删除", {
|
||||
confirmButtonText: "确定删除",
|
||||
cancelButtonText: "取消",
|
||||
type: "warning",
|
||||
});
|
||||
|
||||
const index = tasks.indexOf(selectedTask.value);
|
||||
if (index > -1) {
|
||||
tasks.splice(index, 1);
|
||||
selectedTask.value = tasks[0] || null;
|
||||
} catch {
|
||||
return; // 用户取消
|
||||
}
|
||||
const res = await request.del(`/tasks/${target.taskId}`, {});
|
||||
if (res.code === 200) {
|
||||
ElMessage.success(`任务 ${target.title} 删除成功`);
|
||||
tasks.value = tasks.value.filter((item) => item.taskId !== target.taskId);
|
||||
selectedTaskId.value = tasks.value[0]?.taskId ?? null;
|
||||
}
|
||||
};
|
||||
|
||||
const selectTask = (task: any) => {
|
||||
selectedTask.value = task;
|
||||
// ============ 优先级权重配置 ============
|
||||
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 () => {
|
||||
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 {
|
||||
// 读取失败时保持默认值
|
||||
}
|
||||
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(() => {
|
||||
@@ -61,95 +331,481 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-row :gutter="5" class="task-layout">
|
||||
<el-col :span="6">
|
||||
<el-card class="task-card" :body-style="{ padding: '0' }">
|
||||
<div class="task-header">任务列表</div>
|
||||
<el-scrollbar height="300px">
|
||||
<el-menu class="task-menu" @select="(key:any) => selectTask(tasks[key])">
|
||||
<el-menu-item
|
||||
v-for="(task, index) in tasks"
|
||||
:key="index"
|
||||
:index="index.toString()"
|
||||
class="task-item"
|
||||
<div>
|
||||
<section class="study-page">
|
||||
<div class="layout-grid">
|
||||
<aside class="surface-card task-list">
|
||||
<div class="block-title">任务清单</div>
|
||||
<el-scrollbar height="420px">
|
||||
<div
|
||||
v-for="item in tasks"
|
||||
:key="item.taskId"
|
||||
class="task-list-item"
|
||||
:class="{ active: selectedTaskId === item.taskId }"
|
||||
@click="selectedTaskId = item.taskId"
|
||||
>
|
||||
{{ task.title }}
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
<p class="task-name">
|
||||
<span class="task-priority">{{ item.priority }}</span>
|
||||
{{ item.title }}
|
||||
</p>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<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>
|
||||
|
||||
<el-col :span="13">
|
||||
<el-card class="task-card">
|
||||
<div v-if="selectedTask">
|
||||
<h3>任务描述</h3>
|
||||
<el-input type="textarea" v-model="selectedTask.description" :rows="4" />
|
||||
|
||||
<h3 class="section-title">任务优先级</h3>
|
||||
<el-radio-group v-model="selectedTask.priority">
|
||||
<el-radio-button v-for="i in 6" :label="i - 1" :key="i">{{ i - 1 }}</el-radio-button>
|
||||
</el-radio-group>
|
||||
|
||||
<h3 class="section-title">上次该任务学习情况</h3>
|
||||
<el-descriptions border column="1">
|
||||
<el-descriptions-item label="有效时间比">0.5</el-descriptions-item>
|
||||
<el-descriptions-item label="实际用时">2小时</el-descriptions-item>
|
||||
<el-descriptions-item label="有效学习时间">1小时</el-descriptions-item>
|
||||
<el-descriptions-item label="备注">学习了“动态面板”的基本使用方式</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<main class="content-zone">
|
||||
<article class="surface-card detail-card" v-loading="loading">
|
||||
<template v-if="selectedTask">
|
||||
<div class="detail-head">
|
||||
<h3>{{ selectedTask.title }}</h3>
|
||||
<el-tag type="success" effect="plain">优先级 {{ selectedTask.priority }}</el-tag>
|
||||
</div>
|
||||
<div v-else>
|
||||
<p>请选择任务或等待任务加载完成。</p>
|
||||
|
||||
<div class="detail-block">
|
||||
<p class="label">任务描述</p>
|
||||
<p class="description-text">{{ selectedTask.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<el-col :span="5">
|
||||
<el-space class="action-buttons">
|
||||
<el-button type="primary" @click="startTask">开始任务</el-button>
|
||||
<el-button @click="addTask">添加任务</el-button>
|
||||
<el-button @click="changeTask">更新任务</el-button>
|
||||
<el-button type="danger" @click="removeTask">删除任务</el-button>
|
||||
<el-button type="info" @click="fetchTasks"> 刷新 </el-button>
|
||||
</el-space>
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<div class="detail-block">
|
||||
<p class="label">学习材料</p>
|
||||
<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"
|
||||
@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 type="success" size="large" @click="startTask">开始任务</el-button>
|
||||
<el-button size="large" @click="addTask">添加任务</el-button>
|
||||
<el-button size="large" @click="changeTask">更新任务</el-button>
|
||||
<el-button size="large" @click="openWeightsDialog">权重配置</el-button>
|
||||
<el-button type="danger" size="large" @click="removeTask">删除任务</el-button>
|
||||
</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>
|
||||
.task-layout {
|
||||
width: 100%;
|
||||
overflow-x: hidden;
|
||||
.study-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.task-card {
|
||||
padding: 0;
|
||||
|
||||
.weights-hint {
|
||||
margin: 0 0 14px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.task-header {
|
||||
padding: 10px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
background-color: #f5f7fa;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
|
||||
.weight-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.task-menu {
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
|
||||
.weight-label {
|
||||
flex-shrink: 0;
|
||||
width: 80px;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.task-item {
|
||||
padding: 10px 12px;
|
||||
white-space: normal;
|
||||
|
||||
.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;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.task-list {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.block-title {
|
||||
margin: 0 0 12px;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.task-list-item {
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
cursor: pointer;
|
||||
background: #fbfefc;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.task-list-item + .task-list-item {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.task-list-item:hover {
|
||||
border-color: #b9d9c8;
|
||||
}
|
||||
|
||||
.task-list-item.active {
|
||||
border-color: var(--green-600);
|
||||
background: var(--green-100);
|
||||
box-shadow: inset 0 0 0 1px rgba(47, 143, 104, 0.2);
|
||||
}
|
||||
|
||||
.task-name {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.task-priority {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
background: var(--green-600);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.task-pagination {
|
||||
margin-top: 10px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.content-zone {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 220px;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.detail-card {
|
||||
padding: 18px 20px;
|
||||
}
|
||||
|
||||
.detail-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.detail-head h3 {
|
||||
margin: 0;
|
||||
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;
|
||||
}
|
||||
.section-title {
|
||||
|
||||
.detail-block {
|
||||
margin-top: 20px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--border-soft);
|
||||
}
|
||||
.action-buttons {
|
||||
|
||||
.detail-block:first-child {
|
||||
margin-top: 0;
|
||||
padding-top: 0;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.label {
|
||||
margin: 0 0 10px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
margin: 0;
|
||||
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;
|
||||
margin-top: 20px;
|
||||
gap: 4px;
|
||||
}
|
||||
.action-buttons .el-button {
|
||||
width: 8vw;
|
||||
min-width: 70px;
|
||||
margin-top: 5px;
|
||||
|
||||
.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;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.action-card .el-button {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.layout-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.content-zone {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.action-card {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.action-card .block-title {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.page-head {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-card {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.application-main {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.application-status {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
+509
-114
@@ -1,18 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import {computed, onMounted, onUnmounted, ref} from 'vue';
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import request from "@/utils/request";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {useRoute, useRouter} from "vue-router";
|
||||
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";
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
|
||||
const route = useRoute()
|
||||
const taskId = route.params.taskId ? Number(route.params.taskId) : null;
|
||||
const buttonName = route.meta.buttonText;
|
||||
const buttonName = route.meta.buttonText as string;
|
||||
const isUpdateMode = computed(() => route.meta.action === "update");
|
||||
|
||||
|
||||
const taskName = ref('');
|
||||
const taskDescription = ref('');
|
||||
const taskNum = ref("");
|
||||
const taskName = ref("");
|
||||
const taskDescription = ref("");
|
||||
const materialUrl = ref("");
|
||||
const priority = ref({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
@@ -22,36 +32,174 @@ const priority = ref({
|
||||
});
|
||||
|
||||
const priorityOptions = [0, 1, 2, 3, 4, 5];
|
||||
const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
|
||||
{ label: "待应用", value: "TODO" },
|
||||
{ label: "进行中", value: "DOING" },
|
||||
{ label: "已完成", value: "DONE" },
|
||||
];
|
||||
|
||||
const applications = ref<TaskApplication[]>([]);
|
||||
const applicationLoading = ref(false);
|
||||
const appUrlTitles = ref<Record<number, string>>({});
|
||||
const applicationDialogVisible = ref(false);
|
||||
const applicationSaving = ref(false);
|
||||
const editingApplicationId = ref<number | null>(null);
|
||||
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) => {
|
||||
await deleteTaskApplication(item.id);
|
||||
ElMessage.success("应用场景已删除");
|
||||
if (editingApplicationId.value === item.id) {
|
||||
resetApplicationForm();
|
||||
}
|
||||
if (taskNum.value) {
|
||||
await loadApplications(taskNum.value);
|
||||
}
|
||||
};
|
||||
|
||||
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 = () => {
|
||||
console.log('创建任务', {
|
||||
convertMaterialUrls().then(() => {
|
||||
request
|
||||
.post("/tasks", {
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
priority: priority.value,
|
||||
});
|
||||
|
||||
request.post("/tasks", {
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
...priority.value
|
||||
}).then(result => {
|
||||
if (result.code == 200) {
|
||||
ElMessage.success("创建任务成功,任务id:" + result.message)
|
||||
router.back()
|
||||
} else {
|
||||
ElMessage.error("任务创建失败,错误原因:" + result.message)
|
||||
}
|
||||
materialUrl: materialUrl.value,
|
||||
...priority.value,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("创建任务成功");
|
||||
router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务创建失败:" + result.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const loadTask = () => {
|
||||
console.info("开始加载任务信息")
|
||||
if (taskId !== null) {
|
||||
request.get(`/tasks/${taskId}`, {}).then(result => {
|
||||
request.get(`/tasks/${taskId}`, {}).then((result) => {
|
||||
if (result.code === 200) {
|
||||
const data = result.data;
|
||||
taskNum.value = data.taskNum || "";
|
||||
taskName.value = data.taskName;
|
||||
taskDescription.value = data.taskDescription;
|
||||
materialUrl.value = data.materialUrl || "";
|
||||
priority.value = {
|
||||
urgency: data.urgency,
|
||||
importance: data.importance,
|
||||
@@ -59,6 +207,9 @@ const loadTask = () => {
|
||||
futureValue: data.futureValue,
|
||||
subjectivePriority: data.subjectivePriority,
|
||||
};
|
||||
if (taskNum.value) {
|
||||
loadApplications(taskNum.value);
|
||||
}
|
||||
} else {
|
||||
ElMessage.error(`任务加载失败:${result.message}`);
|
||||
}
|
||||
@@ -67,45 +218,43 @@ const loadTask = () => {
|
||||
};
|
||||
|
||||
const updateTask = () => {
|
||||
console.log('更新任务', {
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
priority: priority.value,
|
||||
});
|
||||
|
||||
request.put("/tasks/" + taskId, {
|
||||
convertMaterialUrls().then(() => {
|
||||
request
|
||||
.put("/tasks/" + taskId, {
|
||||
id: taskId,
|
||||
taskName: taskName.value,
|
||||
taskDescription: taskDescription.value,
|
||||
...priority.value
|
||||
}).then(result => {
|
||||
if (result.code == 200) {
|
||||
ElMessage.success("更新任务成功" + result.message)
|
||||
router.back()
|
||||
} else {
|
||||
ElMessage.error("任务更新失败,错误原因:" + result.message)
|
||||
}
|
||||
materialUrl: materialUrl.value,
|
||||
...priority.value,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.code === 200) {
|
||||
ElMessage.success("更新任务成功");
|
||||
router.push({ name: "study" });
|
||||
} else {
|
||||
ElMessage.error("任务更新失败:" + result.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const cancelTask = () => {
|
||||
ElMessage.success("已取消创建")
|
||||
router.back()
|
||||
ElMessage.info("已取消操作");
|
||||
router.push({ name: "study" });
|
||||
};
|
||||
|
||||
|
||||
const submitTask = () => {
|
||||
switch (route.name) {
|
||||
case 'add-task':
|
||||
case "add-task":
|
||||
createTask();
|
||||
break;
|
||||
case 'update-task':
|
||||
case "update-task":
|
||||
updateTask();
|
||||
break;
|
||||
default:
|
||||
ElMessage.error('未知操作类型');
|
||||
ElMessage.error("未知操作类型");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const screenWidth = ref(window.innerWidth);
|
||||
|
||||
@@ -113,119 +262,365 @@ const updateWidth = () => {
|
||||
screenWidth.value = window.innerWidth;
|
||||
};
|
||||
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('resize', updateWidth)
|
||||
if (route.meta.action === 'update' && taskId !== null) {
|
||||
window.addEventListener("resize", updateWidth);
|
||||
if (route.meta.action === "update" && taskId !== null) {
|
||||
loadTask();
|
||||
}
|
||||
});
|
||||
onUnmounted(() => window.removeEventListener('resize', updateWidth));
|
||||
|
||||
const columnSpan = computed(() => {
|
||||
return screenWidth.value <= 768 ? 20 : 8;
|
||||
});
|
||||
onUnmounted(() => window.removeEventListener("resize", updateWidth));
|
||||
|
||||
const isMobile = computed(() => screenWidth.value <= 900);
|
||||
|
||||
// 学习材料 Markdown 预览
|
||||
const showPreview = ref(false);
|
||||
const materialPreview = ref("");
|
||||
const previewLoading = ref(false);
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const escapeAttr = (s: string) => s.replace(/"/g, """).replace(/&/g, "&");
|
||||
|
||||
function renderMarkdown(raw: string, urlTitles: Record<string, string> = {}): string {
|
||||
if (!raw.trim()) return "";
|
||||
let html = raw;
|
||||
// 1) [text](url) → <a> 占位,防止后续裸 URL 匹配进属性里
|
||||
const links: string[] = [];
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
|
||||
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
// 2) 裸 URL → <a> 占位
|
||||
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
|
||||
const clean = url.replace(/[.。,,;;!!??)】」』\]]+$/, "");
|
||||
const label = urlTitles[clean] || url;
|
||||
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(label)}</a>`;
|
||||
links.push(tag);
|
||||
return `__LINK_${links.length - 1}__`;
|
||||
});
|
||||
// 3) 换行
|
||||
html = html.replace(/\n/g, "<br>");
|
||||
// 4) 还原占位
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
html = html.replace(`__LINK_${i}__`, links[i]);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
async function previewMaterial() {
|
||||
showPreview.value = true;
|
||||
const raw = materialUrl.value || "";
|
||||
if (!raw.trim()) { materialPreview.value = ""; return; }
|
||||
previewLoading.value = true;
|
||||
try {
|
||||
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);
|
||||
} finally {
|
||||
previewLoading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-form label-width="100px">
|
||||
<el-form-item label="任务名:">
|
||||
<el-input v-model="taskName" placeholder="请输入任务名"></el-input>
|
||||
<section class="task-form-page">
|
||||
<el-form label-position="top" class="surface-card form-shell">
|
||||
<div class="group">
|
||||
<h3>基础信息</h3>
|
||||
<el-form-item label="任务名称">
|
||||
<el-input v-model="taskName" placeholder="例如:Vue3 组件通信实践" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="任务描述:">
|
||||
<el-form-item label="任务描述">
|
||||
<el-input v-model="taskDescription" type="textarea" :rows="5" placeholder="请输入任务描述" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<div class="material-label">
|
||||
<span>学习材料地址</span>
|
||||
<el-button
|
||||
v-if="!showPreview"
|
||||
text
|
||||
size="small"
|
||||
type="primary"
|
||||
@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-model="taskDescription"
|
||||
v-if="!showPreview"
|
||||
v-model="materialUrl"
|
||||
type="textarea"
|
||||
placeholder="请输入任务描述"
|
||||
rows="6"
|
||||
></el-input>
|
||||
: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>
|
||||
|
||||
<el-form-item label="优先级:">
|
||||
<el-row :gutter="10">
|
||||
<el-col :span="columnSpan">
|
||||
<div class="group">
|
||||
<h3>优先级维度</h3>
|
||||
<div class="priority-grid" :class="{ mobile: isMobile }">
|
||||
<el-form-item label="急迫性">
|
||||
<el-select v-model="priority.urgency">
|
||||
<el-option
|
||||
v-for="item in priorityOptions"
|
||||
:key="item"
|
||||
:label="item"
|
||||
:value="item"
|
||||
></el-option>
|
||||
<el-option v-for="item in priorityOptions" :key="'u' + item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="columnSpan">
|
||||
<el-form-item label="重要性">
|
||||
<el-select v-model="priority.importance">
|
||||
<el-option
|
||||
v-for="item in priorityOptions"
|
||||
:key="item"
|
||||
:label="item"
|
||||
:value="item"
|
||||
></el-option>
|
||||
<el-option v-for="item in priorityOptions" :key="'i' + item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="columnSpan">
|
||||
<el-form-item label="内容难度">
|
||||
<el-select v-model="priority.contentDifficulty">
|
||||
<el-option
|
||||
v-for="item in priorityOptions"
|
||||
:key="item"
|
||||
:label="item"
|
||||
:value="item"
|
||||
></el-option>
|
||||
<el-option v-for="item in priorityOptions" :key="'d' + item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="columnSpan">
|
||||
<el-form-item label="未来价值">
|
||||
<el-select v-model="priority.futureValue">
|
||||
<el-option
|
||||
v-for="item in priorityOptions"
|
||||
:key="item"
|
||||
:label="item"
|
||||
:value="item"
|
||||
></el-option>
|
||||
<el-option v-for="item in priorityOptions" :key="'f' + item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="columnSpan">
|
||||
<el-form-item label="主观优先级">
|
||||
<el-select v-model="priority.subjectivePriority">
|
||||
<el-option
|
||||
v-for="item in priorityOptions"
|
||||
:key="item"
|
||||
:label="item"
|
||||
:value="item"
|
||||
></el-option>
|
||||
<el-option v-for="item in priorityOptions" :key="'s' + item" :label="item" :value="item" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="submitTask">{{ buttonName }}</el-button>
|
||||
<el-button @click="cancelTask">取消</el-button>
|
||||
<div class="group" v-if="isUpdateMode" v-loading="applicationLoading">
|
||||
<div class="application-header">
|
||||
<h3>应用场景</h3>
|
||||
<el-button type="primary" @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" @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 size="large" @click="cancelTask">取消</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.el-form-item {
|
||||
margin-bottom: 15px;
|
||||
.task-form-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.form-shell {
|
||||
padding: 22px;
|
||||
}
|
||||
|
||||
.group + .group {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.group h3 {
|
||||
margin: 0 0 12px;
|
||||
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));
|
||||
gap: 0 14px;
|
||||
}
|
||||
|
||||
.priority-grid.mobile {
|
||||
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;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.el-col {
|
||||
width: 100% !important;
|
||||
.form-shell {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.action-row .el-button {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.application-main {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
}
|
||||
</style>
|
||||
|
||||
+427
-78
@@ -1,5 +1,126 @@
|
||||
<script setup lang="ts">
|
||||
import router from "@/router/index.js";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import router from "@/router";
|
||||
import { getReviewFeed, type ReviewFeedItem } from "@/api/review";
|
||||
|
||||
const reviewItems = ref<ReviewFeedItem[]>([]);
|
||||
const isHovering = ref(false);
|
||||
|
||||
interface SessionGroup {
|
||||
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 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;
|
||||
});
|
||||
|
||||
// 复制一份实现无缝循环
|
||||
const duplicatedGroups = computed(() => [...sessionGroups.value, ...sessionGroups.value]);
|
||||
|
||||
const loadReviewFeed = async () => {
|
||||
try {
|
||||
const res = await getReviewFeed(100, "smart");
|
||||
reviewItems.value = res?.data || [];
|
||||
} catch {
|
||||
// feed 加载失败不影响页面主体功能
|
||||
}
|
||||
};
|
||||
|
||||
// 回忆卡片:点击滚动内容先尝试回忆,再看原文
|
||||
const recallCard = ref<{ visible: boolean; group: SessionGroup | null; revealed: boolean }>({
|
||||
visible: false,
|
||||
group: null,
|
||||
revealed: false,
|
||||
});
|
||||
|
||||
// 当前回忆卡片对应会话的全部记录
|
||||
const recallSessionItems = computed(() => {
|
||||
const group = recallCard.value.group;
|
||||
if (!group) return [];
|
||||
return reviewItems.value.filter((i) => i.sessionNum === group.sessionNum);
|
||||
});
|
||||
|
||||
const goToReviewDetail = (group: SessionGroup) => {
|
||||
recallCard.value = { visible: true, group, revealed: false };
|
||||
};
|
||||
|
||||
const revealRecallContent = () => {
|
||||
recallCard.value.revealed = true;
|
||||
};
|
||||
|
||||
const openRecallDetail = () => {
|
||||
const group = recallCard.value.group;
|
||||
if (!group) return;
|
||||
recallCard.value.visible = false;
|
||||
router.push(`/review/detail/${group.navigateType}/${group.navigateId}`);
|
||||
};
|
||||
|
||||
/** 从回忆卡片跳转到回忆复习页(先匹配标准导图节点) */
|
||||
const goToRecallFromCard = async () => {
|
||||
const group = recallCard.value.group;
|
||||
if (!group) return;
|
||||
recallCard.value.visible = false;
|
||||
const tn = group.taskNum;
|
||||
const content = group.content || "";
|
||||
if (tn && content) {
|
||||
try {
|
||||
const { findNode } = await import("@/api/standardMindMap");
|
||||
const res = await findNode(tn, content.substring(0, 500));
|
||||
const data = res?.data;
|
||||
if (data?.path) {
|
||||
router.push(`/review/recall/${tn}?focusPath=${encodeURIComponent(data.path)}`);
|
||||
return;
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
router.push(`/review/recall/${tn}`);
|
||||
} else {
|
||||
router.push("/review");
|
||||
}
|
||||
};
|
||||
|
||||
const startStudy = () => {
|
||||
router.push("/study");
|
||||
@@ -8,103 +129,331 @@ const startStudy = () => {
|
||||
const startReview = () => {
|
||||
router.push("/review");
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadReviewFeed();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-container class="container">
|
||||
<el-header class="header">
|
||||
<!-- <div class="marquee-wrapper">-->
|
||||
<!-- <div class="marquee-content">-->
|
||||
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
|
||||
<!-- </div>-->
|
||||
<!-- </div>-->
|
||||
</el-header>
|
||||
|
||||
|
||||
<el-main>
|
||||
<el-row :gutter="20">
|
||||
<el-col :span="18">
|
||||
<el-card class="progress-card" shadow="always">
|
||||
<div class="progress-text">学习进度总揽</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="3">
|
||||
<div class="button-group">
|
||||
<el-button type="success" size="large" @click="startStudy" plain>开始学习</el-button>
|
||||
<el-button type="primary" size="large" @click="startReview" plain>开始复习</el-button>
|
||||
<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-content"
|
||||
:class="{ paused: isHovering }"
|
||||
@mouseenter="isHovering = true"
|
||||
@mouseleave="isHovering = false"
|
||||
>
|
||||
<span
|
||||
v-for="(group, index) in duplicatedGroups"
|
||||
:key="index"
|
||||
class="review-chip"
|
||||
:class="group.hasReport ? 'has-report' : 'fragments-only'"
|
||||
@click="goToReviewDetail(group)"
|
||||
>
|
||||
<strong class="chip-task">{{ group.taskName }}</strong>
|
||||
<span class="chip-content">{{ group.content }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="welcome-banner surface-card">
|
||||
<div>
|
||||
<h1 class="page-title">欢迎回来,准备好继续学习了吗?</h1>
|
||||
<p class="page-subtitle">
|
||||
先挑选任务开始一次会话,再在复习页回顾你的学习轨迹。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="quick-grid">
|
||||
<article class="quick-card surface-card">
|
||||
<h3>学习会话</h3>
|
||||
<p>进入任务列表,选择当前最重要的一项并开始学习计时。</p>
|
||||
<el-button type="success" size="large" @click="startStudy">开始学习</el-button>
|
||||
</article>
|
||||
|
||||
<article class="quick-card surface-card">
|
||||
<h3>复习回看</h3>
|
||||
<p>查看学习报告与残片数量,明确哪些内容需要优先复习。</p>
|
||||
<el-button plain type="success" size="large" @click="startReview">开始复习</el-button>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 回忆卡片:先回忆,再对照 -->
|
||||
<el-dialog
|
||||
v-model="recallCard.visible"
|
||||
:title="recallCard.group?.taskName || '回忆一下'"
|
||||
width="560px"
|
||||
>
|
||||
<template v-if="recallCard.group">
|
||||
<p class="recall-question">
|
||||
这次学习共有 {{ recallSessionItems.length }} 条记录。看着下面这个片段,先试着回忆:当时还学了什么?
|
||||
</p>
|
||||
<blockquote class="recall-snippet">{{ recallCard.group.content }}</blockquote>
|
||||
|
||||
<div v-if="recallCard.revealed" class="recall-full-list">
|
||||
<div
|
||||
v-for="item in recallSessionItems"
|
||||
:key="`${item.sourceType}-${item.id}`"
|
||||
class="recall-full-item"
|
||||
>
|
||||
<span class="recall-item-tag" :class="item.sourceType === 'REPORT' ? 'tag-report' : 'tag-fragment'">
|
||||
{{ item.sourceType === "REPORT" ? "报告" : "残片" }}
|
||||
</span>
|
||||
<span class="recall-item-content">{{ item.content }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<el-button v-if="!recallCard.revealed" type="success" @click="revealRecallContent">
|
||||
回忆好了,展开对照
|
||||
</el-button>
|
||||
<el-button v-else type="success" @click="openRecallDetail">进入详情页</el-button>
|
||||
<el-button type="success" plain @click="goToRecallFromCard">前往回忆复习</el-button>
|
||||
<el-button @click="recallCard.visible = false">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-main>
|
||||
</el-container>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
*{
|
||||
margin: 0px;
|
||||
/*padding: 0;*/
|
||||
}
|
||||
.container {
|
||||
min-height: 100vh;
|
||||
font-family: "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.progress-card {
|
||||
height: 400px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
font-size: 18px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.button-group {
|
||||
.welcome-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
margin-top: 80px;
|
||||
align-items: center;
|
||||
}
|
||||
.button-group .el-button {
|
||||
margin-left: 0;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.welcome-banner {
|
||||
padding: 20px 22px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
/*滚动样式*/
|
||||
.marquee-wrapper {
|
||||
.quick-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.quick-card {
|
||||
padding: 22px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.quick-card h3 {
|
||||
margin: 0;
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.quick-card p {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.quick-card .el-button {
|
||||
margin-top: auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 复习滚动条区域 */
|
||||
.review-scroll-section {
|
||||
padding: 14px 22px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
position: relative;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.marquee-content {
|
||||
.review-scroll-header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.color-legend {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dot {
|
||||
display: inline-block;
|
||||
position: absolute;
|
||||
white-space: nowrap;
|
||||
will-change: transform;
|
||||
animation: scroll-left 15s linear infinite;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 2px;
|
||||
margin-right: 3px;
|
||||
}
|
||||
|
||||
@keyframes scroll-left {
|
||||
.dot-report {
|
||||
background: var(--green-600);
|
||||
}
|
||||
|
||||
.dot-fragment {
|
||||
background: #e6a23c;
|
||||
}
|
||||
|
||||
.review-scroll-track {
|
||||
overflow: hidden;
|
||||
mask-image: linear-gradient(to right, transparent, black 3%, black 97%, transparent);
|
||||
-webkit-mask-image: linear-gradient(to right, transparent, black 3%, black 97%, transparent);
|
||||
}
|
||||
|
||||
.review-scroll-content {
|
||||
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(100%);
|
||||
transform: translateX(0);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(-100%);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.review-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 16px;
|
||||
background: var(--surface-strong);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-left: 3px solid transparent;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, box-shadow 0.2s;
|
||||
flex-shrink: 0;
|
||||
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;
|
||||
}
|
||||
|
||||
.chip-task {
|
||||
color: var(--green-700);
|
||||
font-size: 13px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chip-content {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
/* 回忆卡片 */
|
||||
.recall-question {
|
||||
margin: 0 0 12px;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.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-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) {
|
||||
.welcome-banner {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.quick-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -25,34 +25,37 @@ export const useStudyFragment = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const confirmGenerateFragment = async (sessionNum: string) => {
|
||||
const confirmGenerateFragment = async (sessionNum: string): Promise<boolean> => {
|
||||
if (!fragmentContent.value.trim()) {
|
||||
ElMessage.warning('请输入学习内容!');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
})
|
||||
.then(async () => {
|
||||
});
|
||||
} catch {
|
||||
ElMessage.info('已取消生成');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
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;
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
ElMessage.info('已取消生成');
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -18,6 +18,14 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
timerRunning.value = false;
|
||||
};
|
||||
|
||||
const syncDisplay = (durationMs: number) => {
|
||||
const safeDuration = Math.max(durationMs, 0);
|
||||
remainingTime.value = safeDuration;
|
||||
timerMinutes.value = Math.floor(safeDuration / 1000 / 60);
|
||||
timerSeconds.value = Math.floor((safeDuration / 1000) % 60);
|
||||
timerIsOver.value = safeDuration === 0;
|
||||
};
|
||||
|
||||
const handleCountdownComplete = () => {
|
||||
audio.loop = true;
|
||||
audio.play();
|
||||
@@ -91,6 +99,7 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
|
||||
timerRunning,
|
||||
timerIsOver,
|
||||
runCountdown,
|
||||
syncDisplay,
|
||||
clear,
|
||||
checkAudioPermission,
|
||||
requestAudioPermission,
|
||||
|
||||
+97
-46
@@ -1,56 +1,107 @@
|
||||
import {createRouter,createWebHistory} from 'vue-router'
|
||||
import Login from "@/components/Login.vue";
|
||||
import Study from "@/components/Study.vue";
|
||||
import Welcome from "@/components/Welcome.vue";
|
||||
import Review from "@/components/Review.vue";
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
|
||||
import StartTask from "@/components/StartTask.vue";
|
||||
import TaskForm from "@/components/TaskForm.vue";
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: "/",
|
||||
redirect: "/login",
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
component: () => import("@/components/Login.vue"),
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
{
|
||||
path: "/welcome",
|
||||
component: () => import("@/components/Welcome.vue"),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/study",
|
||||
name: "study",
|
||||
component: () => import("@/components/Study.vue"),
|
||||
meta: { requiresAuth: true, title: "学习任务" },
|
||||
},
|
||||
{
|
||||
path: "/review",
|
||||
component: () => import("@/components/Review.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",
|
||||
component: StartTask,
|
||||
meta: { requiresAuth: true, title: "学习会话" },
|
||||
},
|
||||
{
|
||||
path: "/add-task",
|
||||
name: "add-task",
|
||||
component: () => import("@/components/TaskForm.vue"),
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
title: "创建学习任务",
|
||||
action: "add",
|
||||
buttonText: "添加",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "/update-task/:taskId",
|
||||
name: "update-task",
|
||||
component: () => import("@/components/TaskForm.vue"),
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
title: "更新学习任务",
|
||||
action: "update",
|
||||
buttonText: "更新",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes:[
|
||||
{
|
||||
path:'/',
|
||||
redirect:'/login',
|
||||
},
|
||||
{
|
||||
path:'/login',
|
||||
component:Login
|
||||
},
|
||||
{
|
||||
path:'/welcome',
|
||||
component: Welcome
|
||||
},
|
||||
{
|
||||
path:'/study',
|
||||
component: Study
|
||||
},
|
||||
{
|
||||
path:'/review',
|
||||
component: Review
|
||||
},
|
||||
{
|
||||
path:'/start-task/:taskNum',
|
||||
name:'start-task',
|
||||
component: StartTask
|
||||
},
|
||||
{
|
||||
path:'/add-task',
|
||||
name:'add-task',
|
||||
component: TaskForm,
|
||||
meta:{
|
||||
action: 'add', buttonText: '添加'
|
||||
routes,
|
||||
});
|
||||
|
||||
router.onError((error, to) => {
|
||||
const message = String((error as Error)?.message || "");
|
||||
const isChunkLoadError =
|
||||
message.includes("Failed to fetch dynamically imported module") ||
|
||||
message.includes("Importing a module script failed") ||
|
||||
message.includes("Loading chunk");
|
||||
if (isChunkLoadError && typeof window !== "undefined") {
|
||||
window.location.assign(to.fullPath);
|
||||
}
|
||||
},
|
||||
{
|
||||
path:'/update-task/:taskId',
|
||||
name:'update-task',
|
||||
component: TaskForm,
|
||||
meta:{
|
||||
action: 'update', buttonText: '更新'
|
||||
});
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (to.meta.requiresAuth === false) return true;
|
||||
const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
|
||||
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;
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -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;
|
||||
}
|
||||
+33
-13
@@ -1,19 +1,43 @@
|
||||
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);
|
||||
|
||||
// 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) {
|
||||
ElMessage.error(`请求失败,服务器返回: ${error.response.data}`);
|
||||
const backendMessage = error.response?.data?.message || JSON.stringify(error.response?.data);
|
||||
ElMessage.error(`请求失败,服务器返回: ${backendMessage}`);
|
||||
} else if (error.request) {
|
||||
ElMessage.error("请求未收到响应,请检查接口运行状态");
|
||||
} else {
|
||||
ElMessage.error(error.message || "请求失败");
|
||||
}
|
||||
throw new Error("网络不通畅,请检查您的网络连接或服务器状态");
|
||||
};
|
||||
@@ -31,38 +55,34 @@ 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 参数
|
||||
return axiosInstance.post(url, data, { params: config.params })
|
||||
return axiosInstance.post(url, data, { params: config.params, ...config })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
} else {
|
||||
// 默认 POST JSON
|
||||
return axiosInstance.post(url, data)
|
||||
return axiosInstance.post(url, data, config)
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
}
|
||||
};
|
||||
|
||||
const put = (url: string, data: any) => {
|
||||
console.log("开始PUT请求", basic_url + url, "参数:", data);
|
||||
return axiosInstance.put(url, data)
|
||||
const put = (url: string, data: any, config: any = {}) => {
|
||||
return axiosInstance.put(url, data, config)
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
};
|
||||
|
||||
const del = (url: string, params: {}) => {
|
||||
console.log("开始DELETE请求", basic_url + url, "参数:", params);
|
||||
return axiosInstance.delete(url, { params })
|
||||
const del = (url: string, params: Record<string, any> = {}, config: any = {}) => {
|
||||
return axiosInstance.delete(url, { params, ...config })
|
||||
.then(validateResponse)
|
||||
.catch(handleError);
|
||||
};
|
||||
|
||||
+16
-3
@@ -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/
|
||||
@@ -15,6 +15,19 @@ export default defineConfig({
|
||||
},
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5158
|
||||
}
|
||||
port: 5158,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://localhost:5157",
|
||||
changeOrigin: true,
|
||||
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