29 Commits
Author SHA1 Message Date
cat-shark fe45ec0f76 docs: 移除仓库文档 2026-08-05 23:35:10 +08:00
cat-shark d01b6dcaa3 fix: 生成残片防抖覆盖确认弹窗期间 2026-08-05 21:50:16 +08:00
cat-shark 4e8aa15b71 fix: 退出登录补防抖加载 2026-08-05 21:45:40 +08:00
cat-shark 370d8e7769 fix: 任务表单补页面加载与提交防抖 2026-08-05 21:44:37 +08:00
cat-shark be4db68550 fix: 任务页操作补防抖加载 2026-08-05 21:43:28 +08:00
cat-shark c95e593cf1 fix: 学习会话按钮补防抖加载 2026-08-05 21:42:45 +08:00
cat-shark 9ed53aa4bc feat: 开始任务直接跳转并补会话页加载 2026-08-05 21:41:27 +08:00
cat-shark 4d9b3c0b02 feat: 复习跳转改为先进入目标页 2026-08-05 21:40:12 +08:00
cat-shark 605495fd53 docs: 补充前端防抖与加载原则 2026-08-05 21:37:39 +08:00
cat-shark eb992a47b7 merge: 合并残片报告拆分到dev 2026-08-03 23:20:07 +08:00
cat-shark 2a36e28f74 refactor: 优化前端错误提示 2026-08-03 23:08:36 +08:00
cat-shark e82a87d104 docs: 补充前端用户提示规范 2026-08-03 23:08:31 +08:00
cat-shark f408076187 style: 调整复习总览操作按钮与参考文案 2026-08-03 22:21:57 +08:00
cat-shark 7610b34621 docs: 补充前端测试规范与代码标准 2026-08-03 22:21:46 +08:00
cat-shark 6595ed0dfc test: 单元测试改为直接测试真实代码 2026-08-03 22:21:36 +08:00
cat-shark f71abdd000 refactor: 为测试暴露组件内部状态 2026-08-03 22:21:25 +08:00
cat-shark 9bba684fb2 feat: 首页滚动条展示学习残片并支持滚轮手动滚动 2026-08-03 22:21:13 +08:00
cat-shark 8d5c9db47f docs: 补充前端代码标准 2026-08-02 12:02:07 +08:00
cat-shark b8b0b73cd8 style: 复习总览统一样式并补全字段名 2026-08-02 11:59:47 +08:00
cat-shark 81f91b320a style: 适配复习总览移动端列表 2026-08-02 11:57:31 +08:00
cat-shark de45c8039c style: 适配各页面弹窗窄屏布局 2026-08-02 11:48:37 +08:00
cat-shark c2493e4c71 style: 增加移动端弹窗全局适配 2026-08-02 11:48:00 +08:00
cat-shark 0059e0ec71 style: 统一历史记录按钮尺寸 2026-08-02 11:40:10 +08:00
cat-shark 96d574b99f refactor: 收敛重复的 Markdown 渲染与应用状态常量 2026-08-02 11:36:18 +08:00
cat-shark 69861d54bb chore: 删除模板遗留文件与无用依赖 2026-08-02 11:35:03 +08:00
cat-shark 769d26fa97 style: 清理未使用的样式 2026-08-02 11:33:02 +08:00
cat-shark 04df078fcf refactor: 清理未使用的源码片段 2026-08-02 11:32:39 +08:00
cat-shark bcec8512f4 fix: 修复回忆页历史记录与重选节点交互 2026-08-02 11:31:58 +08:00
cat-shark 297320446c style: 统一页面按钮样式与尺寸 2026-08-01 19:06:41 +08:00
41 changed files with 1706 additions and 3167 deletions
+46
View File
@@ -74,6 +74,52 @@ lpt-fe/src/
- `MindMapViewer.vue` 支持只读、编辑、selectable、colorByCompare 模式;selectable 模式下点击节点 emit `node-select`
- ReviewRecall 中 `standardExpanded` 展开后节点可点击,用于选择复习起点。
## 前端代码标准
### 交互防抖与加载原则
- 点击后需要跳转到其他页面时,应立刻执行跳转,不要在跳转前等待接口返回;目标页面在数据未加载完成时必须展示页面级 loading。
- 点击后不跳转页面时,触发接口的按钮必须自身展示 loading 或在请求期间禁用,防止网络慢时被多次触发。
- 登录、创建/更新、结束会话等必须确认后端成功的操作属于例外:按钮先进入 loading,成功后再跳转。
- 同一异步动作执行期间必须通过 loading 或 disabled 阻止重复触发,不能只依赖路由跳转后的页面卸载。
### 按钮规范
- 页面主操作 / 卡片 CTA`size="large"`,如 Study 开始任务、TaskForm 保存、Welcome 快速入口。
- 区块工具栏 / 页内操作:默认尺寸,如 Review 刷新、ReviewRecall 面板操作、历史记录。
- 表格/列表行内操作:`size="small"`,主操作实底 `type="success"`,次操作 `text`;如 Review 卡片中「回忆复习」为主、「查看记录」为次。
- 弹窗 footer:默认尺寸;确认按钮 `type="success"`,取消按钮默认;危险操作统一 `type="danger"`
- 正向/保存语义统一 `success`,次级编辑语义可用 `primary`,不要在同一功能上混用。
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css``.action-row / .edit-actions / .fragment-edit-actions / .task-actions``.task-actions` 中主操作在上、次操作在下(如 Review 的回忆复习/查看记录)。
### 移动端适配
- 断点约定:按钮/弹窗使用 768px,卡片与汇总布局使用 900px。
- 弹窗:窄屏宽度 `calc(100% - 24px)`body 允许纵向滚动,footer 按钮等宽;全局规则位于 `main.css``@media (max-width: 768px)`,新增弹窗不需要再逐页适配。
- 多按钮弹窗(如 Welcome 回忆卡片)在窄屏纵向堆叠。
- 列表页优先使用卡片列表而非 `el-table`,桌面与移动端视觉统一,参考 `Review.vue``.task-list`
- 文案不缩写:使用完整字段名,如 `学习报告数量``学习残片数量`,不使用 `报告数``残片数`
### 代码整洁
- Markdown 渲染统一使用 `src/utils/markdown.ts``renderMarkdown`,禁止在组件内复制实现。
- 应用场景状态常量统一使用 `src/utils/taskApplication.ts``applicationStatusOptions`
- 用户可见错误提示必须口语化、可理解,不要直接展示接口原始 message、JSON、参数名或“服务器返回”等技术信息;技术细节留在日志。
- 不保留无消费者代码:未使用的 import、prop、事件、API 封装、CSS class、组件文件与依赖应及时删除。
- 组件公开 props/events 只在有实际消费者时保留,例如 MindMapViewer 通过 `toOutline()` 导出编辑内容,不依赖无人监听的 change 事件。
- Vite 模板遗留文件(示例组件、icon、logo)不进入业务代码。
### 测试规范
- 单元测试必须直接测试真实代码:直接调用 composable、挂载真实组件、使用真实路由;禁止把组件或 composable 的逻辑复制到测试里再自测。
- 测试中可以 mock 外部依赖(API、Element Plus 服务、Audio 等),但被测逻辑本身必须来自生产模块。
- `script setup` 内部状态需要测试访问时,通过 `defineExpose` 暴露,而不是在测试里重写一份相同逻辑。
### 提交前检查
- 运行 `npx vue-tsc --noEmit``npm run test``npm run build`
- 提交信息按 Git 提交规范使用中文短句;样式类改动用 `style:`,清理类用 `refactor:` / `chore:`
## 开发配置
- 开发端口:5158
Vendored
+47
View File
@@ -0,0 +1,47 @@
pipeline {
agent none
environment {
IMAGE_NAME = "lpt-fe:${env.GIT_COMMIT?.take(8) ?: '0.0'}"
CONTAINER_NAME = 'LPT_FE'
CONTAINER_PORT = '80'
}
stages {
stage('构建 Docker 镜像') {
agent any
steps {
sh 'docker build --build-arg BUILD_MODE=production -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.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('健康检查') {
agent any
steps {
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'
}
}
}
}
+41
View File
@@ -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)'
}
}
}
}
+40
View File
@@ -31,4 +31,44 @@ test.describe('Welcome page', () => {
await page.locator('.quick-card').nth(1).locator('button').click();
await expect(page).toHaveURL(/\/review/);
});
test('wheel scrolls review ticker manually while hovering', async ({ page }) => {
const items = Array.from({ length: 10 }, (_, i) => ({
id: i + 1,
sessionNum: `S${i + 1}`,
taskNum: `T${i + 1}`,
taskName: `任务 ${i + 1}`,
sourceType: 'FRAGMENT',
content: `${i + 1} 条学习残片内容,用来撑起首页滚动区域。`,
createdTime: `2026-08-01 10:00:${String(i).padStart(2, '0')}`,
}));
await page.route('**/api/review/feed**', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ code: 200, data: items }),
}),
);
await page.goto('/welcome');
const track = page.locator('.review-scroll-track');
const content = page.locator('.review-scroll-content');
await expect(track).toBeVisible();
await track.hover();
const readTime = () =>
content.evaluate((el) => {
const anim = el.getAnimations()[0];
return anim && typeof anim.currentTime === 'number' ? anim.currentTime : -1;
});
const before = await readTime();
await page.mouse.wheel(0, 200);
await expect.poll(readTime).toBeGreaterThan(before);
await page.mouse.move(10, 10);
const after = await readTime();
await expect.poll(readTime).toBeGreaterThan(after);
});
});
+208 -1631
View File
File diff suppressed because it is too large Load Diff
-4
View File
@@ -20,13 +20,10 @@
"dependencies": {
"async-validator": "^4.2.5",
"axios": "^1.7.7",
"css-loader": "^7.1.2",
"element-plus": "^2.8.7",
"marked": "^18.0.5",
"mind-elixir": "^5.13.0",
"normalize": "^0.3.1",
"normalize.css": "^8.0.1",
"style-loader": "^4.0.0",
"vue": "^3.5.12",
"vue-router": "^4.4.5"
},
@@ -39,7 +36,6 @@
"@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",
-67
View File
@@ -11,21 +11,12 @@ dependencies:
axios:
specifier: ^1.7.7
version: 1.16.1
css-loader:
specifier: ^7.1.2
version: 7.1.4(webpack@5.107.2)
element-plus:
specifier: ^2.8.7
version: 2.14.0(vue@3.5.34)
normalize:
specifier: ^0.3.1
version: 0.3.1
normalize.css:
specifier: ^8.0.1
version: 8.0.1
style-loader:
specifier: ^4.0.0
version: 4.0.0(webpack@5.107.2)
vue:
specifier: ^3.5.12
version: 3.5.34(typescript@5.6.3)
@@ -58,9 +49,6 @@ devDependencies:
jsdom:
specifier: ^24.1.3
version: 24.1.3
npm-run-all2:
specifier: ^7.0.1
version: 7.0.2
typescript:
specifier: ~5.6.0
version: 5.6.3
@@ -1271,29 +1259,6 @@ packages:
shebang-command: 2.0.0
which: 2.0.2
/css-loader@7.1.4(webpack@5.107.2):
resolution: {integrity: sha512-vv3J9tlOl04WjiMvHQI/9tmIrCxVrj6PFbHemBB1iihpeRbi/I4h033eoFIhwxBBqLhI0KYFS7yvynBFhIZfTw==}
engines: {node: '>= 18.12.0'}
peerDependencies:
'@rspack/core': 0.x || ^1.0.0 || ^2.0.0-0
webpack: ^5.27.0
peerDependenciesMeta:
'@rspack/core':
optional: true
webpack:
optional: true
dependencies:
icss-utils: 5.1.0(postcss@8.5.15)
postcss: 8.5.15
postcss-modules-extract-imports: 3.1.0(postcss@8.5.15)
postcss-modules-local-by-default: 4.2.0(postcss@8.5.15)
postcss-modules-scope: 3.2.1(postcss@8.5.15)
postcss-modules-values: 4.0.0(postcss@8.5.15)
postcss-value-parser: 4.2.0
semver: 7.8.1
webpack: 5.107.2(postcss@8.5.15)
dev: false
/cssesc@3.0.0:
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
@@ -1931,34 +1896,11 @@ packages:
resolution: {integrity: sha512-qizSNPO93t1YUuUhP22btGOo3chcvDFqFaj2TRybP0DMxkHOCTYwp3n34fel4a31ORXy4m1Xq0Gyqpb5m33qIg==}
dev: false
/normalize@0.3.1:
resolution: {integrity: sha512-DfyFcERXw4cjxUBgmATdxnCipRFoRvj0tNo+MWwjhebV9GZz2HYoNkXodEqS565uomk0CxEs90nEwrmj+aI9RQ==}
dependencies:
stylus: 0.64.0
transitivePeerDependencies:
- supports-color
dev: false
/npm-normalize-package-bin@4.0.0:
resolution: {integrity: sha512-TZKxPvItzai9kN9H/TkmCtx/ZN/hvr3vUycjlfmH0ootY9yFBzNOpiXAdIn1Iteqsvk4lQn6B5PTrt+n6h8k/w==}
engines: {node: ^18.17.0 || >=20.5.0}
dev: true
/npm-run-all2@7.0.2:
resolution: {integrity: sha512-7tXR+r9hzRNOPNTvXegM+QzCuMjzUIIq66VDunL6j60O4RrExx32XUhlrS7UK4VcdGw5/Wxzb3kfNcFix9JKDA==}
engines: {node: ^18.17.0 || >=20.5.0, npm: '>= 9'}
hasBin: true
dependencies:
ansi-styles: 6.2.3
cross-spawn: 7.0.6
memorystream: 0.3.1
minimatch: 9.0.9
pidtree: 0.6.0
read-package-json-fast: 4.0.0
shell-quote: 1.8.4
which: 5.0.0
dev: true
/nwsapi@2.2.23:
resolution: {integrity: sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==}
dev: true
@@ -2283,15 +2225,6 @@ packages:
dependencies:
ansi-regex: 6.2.2
/style-loader@4.0.0(webpack@5.107.2):
resolution: {integrity: sha512-1V4WqhhZZgjVAVJyt7TdDPZoPBPNHbekX4fWnCJL1yQukhCeZhJySUL+gL9y6sNdN95uEOS83Y55SqHcP7MzLA==}
engines: {node: '>= 18.12.0'}
peerDependencies:
webpack: ^5.27.0
dependencies:
webpack: 5.107.2(postcss@8.5.15)
dev: false
/stylus@0.64.0:
resolution: {integrity: sha512-ZIdT8eUv8tegmqy1tTIdJv9We2DumkNZFdCF5mz/Kpq3OcTaxSuCAYZge6HKK2CmNC02G1eJig2RV7XTw5hQrA==}
engines: {node: '>=16'}
+64 -85
View File
@@ -1,112 +1,91 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { createRouter, createMemoryHistory } from 'vue-router'
import { reactive, ref } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage } from 'element-plus'
import Login from '@/components/Login.vue'
import router from '@/router'
import { login } from '@/api/login'
// Mock API
vi.mock('@/api/login', () => ({
login: vi.fn(),
logout: vi.fn(),
}))
// Mock Element Plus
vi.mock('element-plus', () => ({
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
import { login } from '@/api/login'
import { ElMessage } from 'element-plus'
function createTestRouter() {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/login', component: { template: '<div/>' } },
{ path: '/welcome', component: { template: '<div/>' } },
],
function mountLogin() {
return mount(Login, {
shallow: true,
global: {
plugins: [ElementPlus, router],
},
})
}
describe('Login.vue logic', () => {
beforeEach(() => {
function createForm(valid = true) {
return {
validate: (callback: (valid: boolean) => void) => callback(valid),
} as any
}
describe('Login.vue', () => {
beforeEach(async () => {
vi.clearAllMocks()
localStorage.clear()
await router.push('/login')
await router.isReady()
})
describe('isNotEmpty validator', () => {
it('calls callback with error message when value is empty', () => {
const callback = vi.fn()
const rule = { message: '请输入账号!' }
// isNotEmpty logic
const value = ''
if (!value) {
callback(rule.message)
} else {
callback()
}
expect(callback).toHaveBeenCalledWith('请输入账号!')
})
it('isNotEmpty validator reports empty value and accepts filled value', () => {
const wrapper = mountLogin()
const callback = vi.fn()
it('calls callback without error when value is present', () => {
const callback = vi.fn()
const rule = { message: '请输入账号!' }
const value = 'admin'
if (!value) {
callback(rule.message)
} else {
callback()
}
expect(callback).toHaveBeenCalledWith()
})
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, '', callback)
expect(callback).toHaveBeenCalledWith('请输入账号!')
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, 'admin', callback)
expect(callback).toHaveBeenCalledWith()
})
describe('submitForm logic', () => {
it('sets localStorage and navigates on successful login', async () => {
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
const router = createTestRouter()
await router.push('/login')
await router.isReady()
it('sets localStorage and navigates on successful login', async () => {
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
const wrapper = mountLogin()
wrapper.vm.registerData.username = 'admin'
wrapper.vm.registerData.password = '123456'
// Simulate submitForm logic
const username = 'admin'
const password = '123456'
const result = await login(username, password)
await wrapper.vm.submitForm(createForm(true))
if (result.code === 200) {
localStorage.setItem('isLoggedIn', 'true')
ElMessage.success(result.message)
await router.push('/welcome')
}
expect(localStorage.getItem('isLoggedIn')).toBe('true')
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
expect(router.currentRoute.value.path).toBe('/welcome')
})
expect(localStorage.getItem('isLoggedIn')).toBe('true')
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('shows error message on failed login', async () => {
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
const wrapper = mountLogin()
wrapper.vm.registerData.username = 'admin'
wrapper.vm.registerData.password = 'wrong'
it('shows error message on failed login', async () => {
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
await wrapper.vm.submitForm(createForm(true))
const result = await login('admin', 'wrong')
if (result.code !== 200) {
ElMessage.error(result.message)
}
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(router.currentRoute.value.path).toBe('/login')
})
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
expect(localStorage.getItem('isLoggedIn')).toBeNull()
})
it('does not submit again while loading', async () => {
let resolveLogin!: (value: any) => void
vi.mocked(login).mockImplementation(
() => new Promise((resolve) => { resolveLogin = resolve }),
)
const wrapper = mountLogin()
it('does not submit when already loading', async () => {
const loading = ref(true)
// Simulate guard: if (!formEl || loading.value) return;
if (loading.value) {
// Early return - no API call
}
expect(login).not.toHaveBeenCalled()
})
const firstSubmit = wrapper.vm.submitForm(createForm(true))
const secondSubmit = wrapper.vm.submitForm(createForm(true))
await Promise.resolve()
expect(login).toHaveBeenCalledTimes(1)
resolveLogin({ code: 200, message: '登录成功' })
await Promise.all([firstSubmit, secondSubmit])
expect(localStorage.getItem('isLoggedIn')).toBe('true')
})
})
+71 -84
View File
@@ -1,106 +1,93 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { computed, ref } from 'vue'
import { mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { ElMessage } from 'element-plus'
import MyHead from '@/components/MyHead.vue'
import router from '@/router'
import { logout } from '@/api/login'
vi.mock('@/api/login', () => ({
login: vi.fn(),
logout: vi.fn().mockResolvedValue({ code: 200 }),
logout: vi.fn(),
}))
vi.mock('element-plus', () => ({
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
async function mountAt(path: string) {
await router.push(path)
await router.isReady()
return mount(MyHead, {
shallow: true,
global: {
plugins: [ElementPlus, router],
},
})
}
import { logout } from '@/api/login'
import { ElMessage } from 'element-plus'
describe('MyHead.vue logic', () => {
beforeEach(() => {
describe('MyHead.vue', () => {
beforeEach(async () => {
vi.clearAllMocks()
localStorage.clear()
await router.push('/login')
await router.isReady()
})
describe('route-based computed properties', () => {
it('isLoginRoute is true when path is /login', () => {
const routePath = ref('/login')
const isLoginRoute = computed(() => routePath.value === '/login')
expect(isLoginRoute.value).toBe(true)
})
it('derives route-based computed properties from real route', async () => {
const loginWrapper = await mountAt('/login')
expect(loginWrapper.vm.isLoginRoute).toBe(true)
expect(loginWrapper.vm.showBackButton).toBe(false)
it('isLoginRoute is false for other paths', () => {
const routePath = ref('/welcome')
const isLoginRoute = computed(() => routePath.value === '/login')
expect(isLoginRoute.value).toBe(false)
})
localStorage.setItem('isLoggedIn', 'true')
const studyWrapper = await mountAt('/study')
expect(studyWrapper.vm.isLoginRoute).toBe(false)
expect(studyWrapper.vm.showBackButton).toBe(true)
expect(studyWrapper.vm.pageTitle).toBe('学习任务')
it('showBackButton is true for non-login, non-welcome routes', () => {
const routePath = ref('/study')
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
expect(showBackButton.value).toBe(true)
})
it('showBackButton is false on welcome route', () => {
const routePath = ref('/welcome')
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
expect(showBackButton.value).toBe(false)
})
it('showBackButton is false on login route', () => {
const routePath = ref('/login')
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
expect(showBackButton.value).toBe(false)
})
it('pageTitle is derived from route meta', () => {
const meta = { title: '学习任务' }
const pageTitle = computed(() => meta?.title as string | undefined)
expect(pageTitle.value).toBe('学习任务')
})
it('pageTitle is undefined when no meta title', () => {
const meta = {}
const pageTitle = computed(() => meta?.title as string | undefined)
expect(pageTitle.value).toBeUndefined()
})
const welcomeWrapper = await mountAt('/welcome')
expect(welcomeWrapper.vm.showBackButton).toBe(false)
expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
})
describe('handleLogout logic', () => {
it('clears login state and navigates to login', async () => {
localStorage.setItem('isLoggedIn', 'true')
it('clears login state and navigates to login on logout', async () => {
vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountAt('/study')
// Simulate handleLogout
try {
await logout()
} catch {
// Backend failure shouldn't block logout
} finally {
localStorage.removeItem('isLoggedIn')
ElMessage.success('已退出登录')
}
await wrapper.vm.handleLogout()
expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
})
expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
expect(router.currentRoute.value.path).toBe('/login')
})
it('clears login state even when API call fails', async () => {
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
localStorage.setItem('isLoggedIn', 'true')
it('clears login state even when logout API fails', async () => {
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountAt('/study')
try {
await logout()
} catch {
// Expected
} finally {
localStorage.removeItem('isLoggedIn')
ElMessage.success('已退出登录')
}
await wrapper.vm.handleLogout()
expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
})
expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
expect(router.currentRoute.value.path).toBe('/login')
})
it('prevents repeated logout while request is pending', async () => {
let resolveLogout!: (value: any) => void
vi.mocked(logout).mockImplementation(
() => new Promise((resolve) => { resolveLogout = resolve }),
)
localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountAt('/study')
const first = wrapper.vm.handleLogout()
const second = wrapper.vm.handleLogout()
await Promise.resolve()
expect(logout).toHaveBeenCalledTimes(1)
expect(wrapper.vm.loggingOut).toBe(true)
resolveLogout({ code: 200 })
await Promise.all([first, second])
expect(wrapper.vm.loggingOut).toBe(false)
})
})
+187 -238
View File
@@ -1,276 +1,225 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref, reactive } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createMemoryHistory, createRouter } from 'vue-router'
import StartTask from '@/components/StartTask.vue'
import router from '@/router'
import {
continueSession,
endSession,
getActiveSession,
getExpectation,
getSessionDetail,
pauseSession,
startOrContinueStudySession,
} from '@/api/studySessions'
import { getFragmentsBySession } from '@/api/reportFragments'
// Mock API
vi.mock('@/api/studySessions', () => ({
continueSession: vi.fn(),
pauseSession: vi.fn(),
endSession: vi.fn(),
startOrContinueStudySession: vi.fn(),
getActiveSession: vi.fn(),
getExpectation: vi.fn(),
getReportDraft: vi.fn(),
getSessionDetail: vi.fn(),
getTaskFragments: vi.fn(),
getTaskReports: vi.fn(),
pauseSession: vi.fn(),
startOrContinueStudySession: vi.fn(),
upsertExpectation: vi.fn(),
}))
vi.mock('@/api/reportFragments', () => ({
createFragments: vi.fn(),
getFragmentsBySession: vi.fn(),
updateFragments: vi.fn(),
}))
import {
continueSession,
pauseSession,
endSession,
startOrContinueStudySession,
} from '@/api/studySessions'
const mockedContinueSession = vi.mocked(continueSession)
const mockedPauseSession = vi.mocked(pauseSession)
const mockedEndSession = vi.mocked(endSession)
const mockedStartOrContinue = vi.mocked(startOrContinueStudySession)
// 模拟 StartTask.vue 中的核心状态和方法
function createSessionSimulator() {
const taskInfo = reactive({
sessionNum: 'SESSION_001',
sessionState: 'ONGOING' as string,
taskName: '测试任务',
taskNum: 'T001',
startTime: '',
endTime: '',
lastStartTime: '',
actualTime: 0,
effectiveTime: 0,
effectivenessRatio: '--',
pointerPosition: 1500000,
systemMessage: '',
})
const timerRunning = ref(true)
const clear = () => {
timerRunning.value = false
}
const runCountdown = (duration: number) => {
timerRunning.value = true
}
// 从 StartTask.vue 提取的 stopTimer 逻辑
const stopTimer = async () => {
const res = await pauseSession(taskInfo.sessionNum)
if (res.code === 200) {
taskInfo.sessionState = 'PAUSED'
}
clear()
}
// 从 StartTask.vue 提取的 startTimer 逻辑
const startTimer = async () => {
if (taskInfo.sessionState === 'PAUSED') {
const res = await continueSession(taskInfo.sessionNum)
if (res.code === 200) {
// ElMessage.success("任务继续")
}
// loadTaskSession 模拟
const sessionRes = await startOrContinueStudySession(taskInfo.taskNum)
Object.assign(taskInfo, sessionRes.data)
}
const duration = taskInfo.pointerPosition || 25 * 60 * 1000
runCountdown(duration)
}
// 从 StartTask.vue 提取的 endTimer 逻辑(简化版,跳过 confirm)
const endTimer = async (content: string) => {
if (!content) return
const res = await endSession(taskInfo.sessionNum, content)
if (res.code === 200) {
if (res.message && res.message !== '请求成功') {
// ElMessage.warning(res.message)
}
}
clear()
}
return { taskInfo, timerRunning, stopTimer, startTimer, endTimer, clear }
const defaultSessionData = {
sessionNum: 'SESSION_001',
sessionState: 'PAUSED',
taskName: '测试任务',
taskNum: 'T001',
taskId: 1,
startTime: '',
endTime: '',
lastStartTime: '',
actualTime: 0,
effectiveTime: 0,
effectivenessRatio: '--',
pointerPosition: 1_500_000,
systemMessage: '',
}
describe('StartTask.vue 暂停/继续逻辑', () => {
beforeEach(() => {
async function mountTask() {
localStorage.setItem('isLoggedIn', 'true')
const testRouter = createRouter({
history: createMemoryHistory(),
routes: [
{
path: '/start-task/:taskNum',
component: StartTask,
meta: { requiresAuth: true, title: '学习会话' },
},
],
})
await testRouter.push('/start-task/T001')
await testRouter.isReady()
const wrapper = mount(StartTask, {
shallow: true,
global: {
plugins: [ElementPlus, testRouter],
},
})
await flushPromises()
return wrapper
}
describe('StartTask.vue', () => {
beforeEach(async () => {
vi.clearAllMocks()
localStorage.clear()
vi.mocked(getActiveSession).mockResolvedValue({ code: 200, data: null } as any)
vi.mocked(startOrContinueStudySession).mockResolvedValue({ code: 200, data: defaultSessionData } as any)
vi.mocked(getExpectation).mockResolvedValue({ code: 200, data: { description: '本次学习预期' } } as any)
vi.mocked(getFragmentsBySession).mockResolvedValue({ code: 200, data: [] } as any)
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
await router.push('/login')
await router.isReady()
})
describe('stopTimer - 暂停', () => {
it('调用 pauseSession API', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
const { stopTimer } = createSessionSimulator()
it('stopTimer pauses real session state and refreshes from detail API', async () => {
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
vi.mocked(getSessionDetail).mockResolvedValue({
code: 200,
data: {
sessionState: 'PAUSED',
actualTime: 10,
effectiveTime: 20,
effectivenessRatio: 0.8,
pointerPosition: 1_200_000,
},
} as any)
const wrapper = await mountTask()
wrapper.vm.taskInfo.sessionState = 'ONGOING'
wrapper.vm.timerRunning = true
await stopTimer()
await wrapper.vm.stopTimer()
expect(mockedPauseSession).toHaveBeenCalledWith('SESSION_001')
})
it('暂停成功后 sessionState 应更新为 PAUSED', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
const { taskInfo, stopTimer } = createSessionSimulator()
expect(taskInfo.sessionState).toBe('ONGOING')
await stopTimer()
expect(taskInfo.sessionState).toBe('PAUSED')
})
it('暂停后 timerRunning 应为 false', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
const { timerRunning, stopTimer } = createSessionSimulator()
expect(timerRunning.value).toBe(true)
await stopTimer()
expect(timerRunning.value).toBe(false)
})
expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
expect(wrapper.vm.taskInfo.actualTime).toBe(10)
expect(wrapper.vm.taskInfo.effectiveTime).toBe(20)
expect(wrapper.vm.timerRunning).toBe(false)
wrapper.unmount()
})
describe('startTimer - 继续', () => {
it('PAUSED 状态下点击开始,应调用 continueSession API', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: {
sessionNum: 'SESSION_001',
sessionState: 'ONGOING',
pointerPosition: 1500000,
},
} as any)
it('startTimer continues a paused session and reloads session data', async () => {
vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
vi.mocked(startOrContinueStudySession).mockResolvedValue({
code: 200,
data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
} as any)
const wrapper = await mountTask()
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
// 挂载时后端返回 PAUSED;手动改为 PAUSED 后,startTimer 应触发 continue
wrapper.vm.taskInfo.sessionState = 'PAUSED'
await wrapper.vm.startTimer()
// 先暂停
await stopTimer()
expect(taskInfo.sessionState).toBe('PAUSED')
// 再开始
await startTimer()
expect(mockedContinueSession).toHaveBeenCalledWith('SESSION_001')
})
it('PAUSED 状态下点击开始,应调用 loadTaskSession 刷新数据', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: {
sessionNum: 'SESSION_001',
sessionState: 'ONGOING',
pointerPosition: 1200000,
},
} as any)
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
await stopTimer()
await startTimer()
expect(mockedStartOrContinue).toHaveBeenCalledWith('T001')
expect(taskInfo.sessionState).toBe('ONGOING')
})
it('ONGOING 状态下点击开始,不应调用 continueSession API', async () => {
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
} as any)
const { taskInfo, startTimer } = createSessionSimulator()
// 直接在 ONGOING 状态调用 startTimer
expect(taskInfo.sessionState).toBe('ONGOING')
await startTimer()
expect(mockedContinueSession).not.toHaveBeenCalled()
})
it('开始后 timerRunning 应为 true', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
} as any)
const { timerRunning, stopTimer, startTimer } = createSessionSimulator()
await stopTimer()
expect(timerRunning.value).toBe(false)
await startTimer()
expect(timerRunning.value).toBe(true)
})
expect(continueSession).toHaveBeenCalledWith('SESSION_001')
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
expect(wrapper.vm.timerRunning).toBe(true)
wrapper.unmount()
})
describe('endTimer - 结束会话', () => {
it('调用 endSession API 并传递 content', async () => {
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
const { endTimer } = createSessionSimulator()
it('startTimer does not call continue API when session is already ongoing', async () => {
const wrapper = await mountTask()
wrapper.vm.taskInfo.sessionState = 'ONGOING'
await endTimer('学习总结内容')
await wrapper.vm.startTimer()
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
})
it('后端返回 warning 消息时,message 应包含提示信息', async () => {
mockedEndSession.mockResolvedValue({
code: 200,
message: '本次有效学习时间不足10分钟,不计入总学习时间',
} as any)
const { endTimer } = createSessionSimulator()
const res = await endSession('SESSION_001', '内容')
expect(res.message).toBe('本次有效学习时间不足10分钟,不计入总学习时间')
expect(res.message).not.toBe('请求成功')
})
it('content 为空时不调用 API', async () => {
const { endTimer } = createSessionSimulator()
await endTimer('')
expect(mockedEndSession).not.toHaveBeenCalled()
})
expect(continueSession).not.toHaveBeenCalled()
expect(wrapper.vm.timerRunning).toBe(true)
wrapper.unmount()
})
describe('完整暂停→继续→暂停流程', () => {
it('多次暂停/继续应正确更新状态和调用 API', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
} as any)
it('redirects to another active task when one exists', async () => {
vi.mocked(getActiveSession).mockResolvedValue({
code: 200,
data: { taskNum: 'T002', taskName: '其他任务', sessionNum: 'S002' },
} as any)
const wrapper = await mountTask()
await flushPromises()
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
expect(startOrContinueStudySession).not.toHaveBeenCalled()
expect(router.currentRoute.value.path).toBe('/start-task/T002')
wrapper.unmount()
})
// 初始状态
expect(taskInfo.sessionState).toBe('ONGOING')
it('endTimer refuses empty content without calling API', async () => {
const wrapper = await mountTask()
// 第一次暂停
await stopTimer()
expect(taskInfo.sessionState).toBe('PAUSED')
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
await wrapper.vm.endTimer('')
// 继续
await startTimer()
expect(taskInfo.sessionState).toBe('ONGOING')
expect(mockedContinueSession).toHaveBeenCalledTimes(1)
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
expect(endSession).not.toHaveBeenCalled()
wrapper.unmount()
})
// 第二次暂停
await stopTimer()
expect(taskInfo.sessionState).toBe('PAUSED')
expect(mockedPauseSession).toHaveBeenCalledTimes(2)
it('endTimer ends session and navigates to study page', async () => {
vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
const wrapper = await mountTask()
// 再次继续
await startTimer()
expect(taskInfo.sessionState).toBe('ONGOING')
expect(mockedContinueSession).toHaveBeenCalledTimes(2)
})
await wrapper.vm.endTimer('学习总结内容')
expect(endSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
expect(ElMessage.success).toHaveBeenCalledWith('任务结束')
expect(localStorage.getItem('activeSession')).toBeNull()
expect(router.currentRoute.value.path).toBe('/study')
wrapper.unmount()
})
it('endTimer shows warning message returned by backend', async () => {
vi.mocked(endSession).mockResolvedValue({
code: 200,
message: '本次有效学习时间不足10分钟,不计入总学习时间',
} as any)
const wrapper = await mountTask()
await wrapper.vm.endTimer('学习总结内容')
expect(ElMessage.warning).toHaveBeenCalledWith('本次有效学习时间不足10分钟,不计入总学习时间')
wrapper.unmount()
})
it('supports a full pause -> continue -> pause flow', async () => {
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
vi.mocked(getSessionDetail).mockResolvedValue({
code: 200,
data: { sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20 },
} as any)
vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
vi.mocked(startOrContinueStudySession).mockResolvedValue({
code: 200,
data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
} as any)
const wrapper = await mountTask()
wrapper.vm.taskInfo.sessionState = 'ONGOING'
wrapper.vm.timerRunning = true
await wrapper.vm.stopTimer()
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
expect(pauseSession).toHaveBeenCalledTimes(1)
await wrapper.vm.startTimer()
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
expect(continueSession).toHaveBeenCalledTimes(1)
await wrapper.vm.stopTimer()
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
expect(pauseSession).toHaveBeenCalledTimes(2)
wrapper.unmount()
})
})
+126 -146
View File
@@ -1,126 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref, reactive } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { ElMessage } from 'element-plus'
import TaskForm from '@/components/TaskForm.vue'
import router from '@/router'
import request from '@/utils/request'
import { getTaskApplications } from '@/api/tasks'
vi.mock('element-plus', () => ({
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
vi.mock('@/utils/request', () => ({
default: {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
},
}))
import { ElMessage } from 'element-plus'
vi.mock('@/api/tasks', () => ({
getTaskApplications: vi.fn(),
createTaskApplication: vi.fn(),
updateTaskApplication: vi.fn(),
deleteTaskApplication: vi.fn(),
}))
describe('TaskForm.vue logic', () => {
beforeEach(() => {
vi.mock('@/utils/fetchTitle', () => ({
getUrlTitle: vi.fn().mockResolvedValue(''),
}))
vi.mock('@/utils/markdown', () => ({
renderMarkdown: vi.fn(() => '<p>preview</p>'),
}))
async function mountAt(path: string) {
localStorage.setItem('isLoggedIn', 'true')
await router.push(path)
await router.isReady()
return mount(TaskForm, {
shallow: true,
global: {
plugins: [ElementPlus, router],
},
})
}
describe('TaskForm.vue', () => {
beforeEach(async () => {
vi.clearAllMocks()
localStorage.clear()
vi.mocked(getTaskApplications).mockResolvedValue({ code: 200, data: [] })
await router.push('/login')
await router.isReady()
})
describe('priorityOptions', () => {
it('contains values 0-5', () => {
const priorityOptions = [0, 1, 2, 3, 4, 5]
expect(priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
expect(priorityOptions.length).toBe(6)
it('uses real priority options and initial state', async () => {
const wrapper = await mountAt('/add-task')
expect(wrapper.vm.priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
expect(wrapper.vm.priority).toEqual({
urgency: 0,
importance: 0,
contentDifficulty: 0,
futureValue: 0,
subjectivePriority: 0,
})
})
describe('priority state management', () => {
it('initializes with all zeros', () => {
const priority = reactive({
urgency: 0,
importance: 0,
contentDifficulty: 0,
futureValue: 0,
subjectivePriority: 0,
})
it('builds create payload from real form state and navigates to study', async () => {
vi.mocked(request.post).mockResolvedValue({ code: 200, message: '创建任务成功' })
const wrapper = await mountAt('/add-task')
wrapper.vm.taskName = '学习递归'
wrapper.vm.taskDescription = '理解递归的基本概念'
wrapper.vm.materialUrl = 'https://example.com/recursion'
wrapper.vm.priority.urgency = 3
wrapper.vm.priority.importance = 4
wrapper.vm.priority.contentDifficulty = 2
wrapper.vm.priority.futureValue = 5
wrapper.vm.priority.subjectivePriority = 3
expect(priority.urgency).toBe(0)
expect(priority.importance).toBe(0)
expect(priority.contentDifficulty).toBe(0)
expect(priority.futureValue).toBe(0)
expect(priority.subjectivePriority).toBe(0)
})
wrapper.vm.createTask()
await flushPromises()
it('updates individual priority fields', () => {
const priority = reactive({
urgency: 0,
importance: 0,
contentDifficulty: 0,
futureValue: 0,
subjectivePriority: 0,
})
priority.urgency = 3
priority.importance = 5
expect(priority.urgency).toBe(3)
expect(priority.importance).toBe(5)
expect(priority.contentDifficulty).toBe(0)
expect(request.post).toHaveBeenCalledWith('/tasks', {
taskName: '学习递归',
taskDescription: '理解递归的基本概念',
materialUrl: 'https://example.com/recursion',
urgency: 3,
importance: 4,
contentDifficulty: 2,
futureValue: 5,
subjectivePriority: 3,
})
expect(ElMessage.success).toHaveBeenCalledWith('创建任务成功')
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
})
describe('task payload construction', () => {
it('builds correct create payload', () => {
const taskName = ref('学习递归')
const taskDescription = ref('理解递归的基本概念')
const materialURL = ref('https://example.com/recursion')
const priority = reactive({
urgency: 3,
importance: 4,
contentDifficulty: 2,
futureValue: 5,
subjectivePriority: 3,
})
const payload = {
taskName: taskName.value,
taskDescription: taskDescription.value,
materialURL: materialURL.value,
...priority,
}
expect(payload).toEqual({
taskName: '学习递归',
taskDescription: '理解递归的基本概念',
materialURL: 'https://example.com/recursion',
urgency: 3,
importance: 4,
contentDifficulty: 2,
futureValue: 5,
subjectivePriority: 3,
})
})
it('builds correct update payload with id', () => {
const taskId = 42
const taskName = ref('更新后的任务')
const taskDescription = ref('')
const materialURL = ref('')
const priority = reactive({
urgency: 1,
importance: 2,
contentDifficulty: 0,
futureValue: 3,
subjectivePriority: 4,
})
const payload = {
id: taskId,
taskName: taskName.value,
taskDescription: taskDescription.value,
materialURL: materialURL.value,
...priority,
}
expect(payload.id).toBe(42)
expect(payload.taskName).toBe('更新后的任务')
})
})
describe('loadTask data mapping', () => {
it('maps API response to form fields correctly', () => {
const apiData = {
it('loads update data from real API and maps it into form state', async () => {
vi.mocked(request.get).mockResolvedValue({
code: 200,
data: {
taskNum: 'T001',
taskName: '学习DP',
taskDescription: '动态规划',
materialUrl: 'https://example.com/dp',
@@ -129,52 +107,54 @@ describe('TaskForm.vue logic', () => {
contentDifficulty: 3,
futureValue: 4,
subjectivePriority: 2,
}
const taskName = ref('')
const taskDescription = ref('')
const materialURL = ref('')
const priority = reactive({
urgency: 0,
importance: 0,
contentDifficulty: 0,
futureValue: 0,
subjectivePriority: 0,
})
// Simulate loadTask mapping
taskName.value = apiData.taskName
taskDescription.value = apiData.taskDescription
materialURL.value = apiData.materialURL || apiData.materialUrl || ''
priority.urgency = apiData.urgency
priority.importance = apiData.importance
priority.contentDifficulty = apiData.contentDifficulty
priority.futureValue = apiData.futureValue
priority.subjectivePriority = apiData.subjectivePriority
expect(taskName.value).toBe('学习DP')
expect(materialURL.value).toBe('https://example.com/dp')
expect(priority.urgency).toBe(4)
expect(priority.importance).toBe(5)
},
})
it('handles materialURL with camelCase variant', () => {
const apiData = { materialURL: 'https://example.com/a', materialUrl: 'https://example.com/b' }
const result = apiData.materialURL || apiData.materialUrl || ''
expect(result).toBe('https://example.com/a')
})
const wrapper = await mountAt('/update-task/42')
await flushPromises()
it('falls back to empty string when no material URL', () => {
const apiData = {} as any
const result = apiData.materialURL || apiData.materialUrl || ''
expect(result).toBe('')
expect(wrapper.vm.isUpdateMode).toBe(true)
expect(wrapper.vm.taskNum).toBe('T001')
expect(wrapper.vm.taskName).toBe('学习DP')
expect(wrapper.vm.taskDescription).toBe('动态规划')
expect(wrapper.vm.materialUrl).toBe('https://example.com/dp')
expect(wrapper.vm.priority).toEqual({
urgency: 4,
importance: 5,
contentDifficulty: 3,
futureValue: 4,
subjectivePriority: 2,
})
})
describe('redirect after successful action', () => {
it('navigates to study page after create/update', () => {
const pushTarget = '/study'
expect(pushTarget).toBe('/study')
it('builds update payload with id and navigates to study', async () => {
vi.mocked(request.get).mockResolvedValue({
code: 200,
data: {
taskNum: 'T001',
taskName: '学习DP',
taskDescription: '动态规划',
materialUrl: '',
urgency: 1,
importance: 2,
contentDifficulty: 0,
futureValue: 3,
subjectivePriority: 4,
},
})
vi.mocked(request.put).mockResolvedValue({ code: 200, message: '更新任务成功' })
const wrapper = await mountAt('/update-task/42')
await flushPromises()
wrapper.vm.taskName = '更新后的任务'
wrapper.vm.updateTask()
await flushPromises()
expect(request.put).toHaveBeenCalledWith('/tasks/42', expect.objectContaining({
id: 42,
taskName: '更新后的任务',
}))
expect(ElMessage.success).toHaveBeenCalledWith('更新任务成功')
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
})
})
+61 -104
View File
@@ -1,155 +1,112 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref } from 'vue'
const mockInfo = vi.fn()
const mockSuccess = vi.fn()
const mockError = vi.fn()
const mockWarning = vi.fn()
const mockConfirm = vi.fn()
vi.mock('element-plus', () => ({
ElMessage: {
success: mockSuccess,
error: mockError,
warning: mockWarning,
info: mockInfo,
},
ElMessageBox: {
confirm: (...args: any[]) => mockConfirm(...args),
},
}))
import { ElMessage, ElMessageBox } from 'element-plus'
import { createFragments } from '@/api/reportFragments'
import { useStudyFragment } from '@/components/composables/fragment'
vi.mock('@/api/reportFragments', () => ({
createFragments: vi.fn(),
}))
import { createFragments } from '@/api/reportFragments'
describe('useStudyFragment composable logic', () => {
describe('useStudyFragment', () => {
beforeEach(() => {
vi.clearAllMocks()
mockConfirm.mockResolvedValue('confirm')
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
})
it('openFragmentDialog resets content and shows dialog', () => {
const fragmentContent = ref('old content')
const fragmentsDialogVisible = ref(false)
const { fragmentsDialogVisible, fragmentContent, openFragmentDialog } = useStudyFragment()
fragmentContent.value = 'old content'
fragmentContent.value = ''
fragmentsDialogVisible.value = true
openFragmentDialog()
expect(fragmentContent.value).toBe('')
expect(fragmentsDialogVisible.value).toBe(true)
})
it('closeFragmentDialog hides dialog on confirm', async () => {
const fragmentsDialogVisible = ref(true)
it('closeFragmentDialog hides dialog after confirm', async () => {
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
fragmentsDialogVisible.value = true
await mockConfirm('确定取消生成吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).then(() => {
fragmentsDialogVisible.value = false
mockInfo('已取消生成')
})
await closeFragmentDialog()
expect(fragmentsDialogVisible.value).toBe(false)
expect(mockInfo).toHaveBeenCalledWith('已取消生成')
expect(ElMessage.info).toHaveBeenCalledWith('已取消生成')
})
it('closeFragmentDialog keeps dialog open on cancel', async () => {
const fragmentsDialogVisible = ref(true)
mockConfirm.mockRejectedValue('cancel')
it('closeFragmentDialog keeps dialog open when user cancels', async () => {
vi.mocked(ElMessageBox.confirm).mockRejectedValue('cancel')
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
fragmentsDialogVisible.value = true
try {
await mockConfirm('确定取消生成吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).then(() => {
fragmentsDialogVisible.value = false
})
} catch {
// User cancelled
}
await closeFragmentDialog()
expect(fragmentsDialogVisible.value).toBe(true)
})
it('confirmGenerateFragment warns if content is empty', async () => {
const fragmentContent = ref(' ')
it('confirmGenerateFragment warns when content is empty', async () => {
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = ' '
if (!fragmentContent.value.trim()) {
mockWarning('请输入学习内容!')
}
const result = await confirmGenerateFragment('S001')
expect(mockWarning).toHaveBeenCalledWith('请输入学习内容!')
expect(result).toBe(false)
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习内容!')
expect(createFragments).not.toHaveBeenCalled()
})
it('confirmGenerateFragment calls API and shows success', async () => {
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
const fragmentContent = ref('学习了递归算法')
const fragmentsDialogVisible = ref(true)
const { fragmentContent, fragmentsDialogVisible, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = '学习了递归算法'
if (fragmentContent.value.trim()) {
await mockConfirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
}).then(async () => {
const res = await createFragments('S001', fragmentContent.value)
if (res.code === 200) {
mockSuccess('学习残片生成成功!')
fragmentsDialogVisible.value = false
}
})
}
const result = await confirmGenerateFragment('S001')
expect(result).toBe(true)
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
expect(mockSuccess).toHaveBeenCalledWith('学习残片生成成功!')
expect(ElMessage.success).toHaveBeenCalledWith('学习残片生成成功!')
expect(fragmentsDialogVisible.value).toBe(false)
})
it('confirmGenerateFragment handles API failure', async () => {
it('confirmGenerateFragment handles business failure', async () => {
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
const fragmentContent = ref('学习内容')
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = '学习内容'
if (fragmentContent.value.trim()) {
await mockConfirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
}).then(async () => {
const res = await createFragments('S001', fragmentContent.value)
if (res.code !== 200) {
mockError(res.message || '生成学习残片失败')
}
})
}
const result = await confirmGenerateFragment('S001')
expect(mockError).toHaveBeenCalledWith('生成失败')
expect(result).toBe(false)
expect(ElMessage.error).toHaveBeenCalledWith('生成失败')
})
it('confirmGenerateFragment handles network error', async () => {
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
const fragmentContent = ref('学习内容')
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = '学习内容'
if (fragmentContent.value.trim()) {
await mockConfirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
}).then(async () => {
try {
await createFragments('S001', fragmentContent.value)
} catch (error: any) {
mockError(error.message || '请求失败')
}
})
}
const result = await confirmGenerateFragment('S001')
expect(mockError).toHaveBeenCalledWith('网络超时')
expect(result).toBe(false)
expect(ElMessage.error).toHaveBeenCalledWith('网络超时')
})
it('prevents duplicate submission while creating fragment', async () => {
let resolveCreate!: (value: any) => void
vi.mocked(createFragments).mockImplementation(
() => new Promise((resolve) => { resolveCreate = resolve }),
)
const { fragmentContent, creatingFragment, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = '学习内容'
const first = confirmGenerateFragment('S001')
const second = confirmGenerateFragment('S001')
await Promise.resolve()
expect(createFragments).toHaveBeenCalledTimes(1)
expect(creatingFragment.value).toBe(true)
resolveCreate({ code: 200 })
await Promise.all([first, second])
expect(creatingFragment.value).toBe(false)
})
})
+35 -67
View File
@@ -1,88 +1,56 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
// We test the timer composable logic directly since it's a pure Vue composable
// Extract the logic to test it in isolation
import { ElMessageBox } from 'element-plus'
import { useTimer } from '@/components/composables/useTimer'
describe('useTimer', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
vi.clearAllMocks()
})
afterEach(() => {
vi.useRealTimers()
})
// Test the core timer logic that the composable uses
it('formatTime converts seconds to HH:MM:SS', () => {
const formatTime = (totalSeconds: number): string => {
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
}
it('syncDisplay writes formatted remaining time', () => {
const { timerMinutes, timerSeconds, timerIsOver, syncDisplay } = useTimer()
expect(formatTime(0)).toBe('00:00:00')
expect(formatTime(61)).toBe('00:01:01')
expect(formatTime(3661)).toBe('01:01:01')
expect(formatTime(59)).toBe('00:00:59')
expect(formatTime(3600)).toBe('01:00:00')
syncDisplay(61_000)
expect(timerMinutes.value).toBe(1)
expect(timerSeconds.value).toBe(1)
expect(timerIsOver.value).toBe(false)
syncDisplay(0)
expect(timerMinutes.value).toBe(0)
expect(timerSeconds.value).toBe(0)
expect(timerIsOver.value).toBe(true)
})
it('formatTime handles large values', () => {
const formatTime = (totalSeconds: number): string => {
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
}
it('runCountdown decreases remaining time and stops at zero', () => {
const { timerMinutes, timerSeconds, timerRunning, timerIsOver, runCountdown, clear } = useTimer()
expect(formatTime(86399)).toBe('23:59:59')
expect(formatTime(100000)).toBe('27:46:40')
runCountdown(3000)
vi.advanceTimersByTime(1000)
expect(timerMinutes.value).toBe(0)
expect(timerSeconds.value).toBe(2)
expect(timerRunning.value).toBe(true)
vi.advanceTimersByTime(2000)
expect(timerSeconds.value).toBe(0)
expect(timerRunning.value).toBe(false)
expect(timerIsOver.value).toBe(true)
clear()
})
it('timer increments elapsedSeconds over time', () => {
let elapsed = 0
const interval = setInterval(() => {
elapsed++
}, 1000)
it('notifies when countdown completes', () => {
const { runCountdown, clear } = useTimer()
vi.advanceTimersByTime(3000)
expect(elapsed).toBe(3)
runCountdown(1000)
vi.advanceTimersByTime(1000)
vi.advanceTimersByTime(2000)
expect(elapsed).toBe(5)
clearInterval(interval)
})
it('timer can be paused and resumed', () => {
let elapsed = 0
let intervalId: ReturnType<typeof setInterval> | null = null
const start = () => {
if (!intervalId) {
intervalId = setInterval(() => { elapsed++ }, 1000)
}
}
const pause = () => {
if (intervalId) {
clearInterval(intervalId)
intervalId = null
}
}
start()
vi.advanceTimersByTime(2000)
expect(elapsed).toBe(2)
pause()
vi.advanceTimersByTime(3000)
expect(elapsed).toBe(2) // Should not change while paused
start()
vi.advanceTimersByTime(2000)
expect(elapsed).toBe(4)
pause()
expect(ElMessageBox.alert).toHaveBeenCalled()
clear()
})
})
+9 -63
View File
@@ -1,90 +1,36 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createRouter, createMemoryHistory } from 'vue-router'
// We test the guard logic by importing the router and simulating navigation
// The router in src/router/index.ts uses createWebHistory which requires DOM,
// so we'll test the guard logic by recreating the key patterns.
import { describe, it, expect, beforeEach } from 'vitest'
import router from '@/router'
describe('route guards', () => {
beforeEach(() => {
beforeEach(async () => {
localStorage.clear()
vi.restoreAllMocks()
await router.push('/login')
await router.isReady()
})
function buildRouter() {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/login', component: { template: '<div/>' }, meta: { requiresAuth: false } },
{ path: '/welcome', component: { template: '<div/>' }, meta: { requiresAuth: true } },
{ path: '/study', component: { template: '<div/>' }, meta: { requiresAuth: true } },
{ path: '/', redirect: '/login' },
],
})
}
it('redirects unauthenticated user from protected route to /login', async () => {
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/welcome')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/login')
})
it('allows authenticated user to access protected route', async () => {
localStorage.setItem('isLoggedIn', 'true')
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/welcome')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('allows unauthenticated access to /login', async () => {
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/login')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/login')
})
it('root path redirects to /login', async () => {
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/login')
})
})
+27 -12
View File
@@ -1,14 +1,29 @@
import { vi } from 'vitest'
// Mock Element Plus components globally
vi.mock('element-plus', () => ({
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
ElMessageBox: {
confirm: vi.fn().mockResolvedValue('confirm'),
},
}))
// 只 mock Element Plus 的服务,组件保持真实实现,方便测试里挂载真实组件
vi.mock('element-plus', async (importOriginal) => {
const actual = await importOriginal<typeof import('element-plus')>()
return {
...actual,
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
ElMessageBox: {
confirm: vi.fn().mockResolvedValue('confirm'),
alert: vi.fn().mockResolvedValue(undefined),
},
}
})
// jsdom 没有 Audio,组件和 useTimer 需要用到
class MockAudio {
loop = false
currentTime = 0
play = vi.fn().mockResolvedValue(undefined)
pause = vi.fn()
}
vi.stubGlobal('Audio', MockAudio)
+1 -10
View File
@@ -22,15 +22,6 @@ vi.mock('axios', () => ({
},
}))
vi.mock('element-plus', () => ({
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
import request from '@/utils/request'
describe('request utility', () => {
@@ -125,7 +116,7 @@ describe('request utility', () => {
})
it('should throw for unsupported method', () => {
expect(() => request.request('patch', '/test', null)).toThrow('请求方法 patch 未实现')
expect(() => request.request('patch', '/test', null)).toThrow('该功能暂不可用,请刷新后重试')
})
})
})
-12
View File
@@ -12,7 +12,6 @@ export interface StandardMindMap {
generator: "BUILTIN" | "AI" | "USER" | "USER_MERGE";
generatorVersion?: string;
sourceReportCount: number;
sourceFragmentCount: number;
generatedTime?: string;
createdTime?: string;
lastModifiedTime?: string;
@@ -32,12 +31,6 @@ export interface RecallRecord {
createdTime: string;
}
export interface FindNodeResult {
path: string;
nodeTitle: string;
score: number;
}
/** 获取/自动生成标准思维导图 */
export const getStandardMindMap = (taskNum: string) => {
return request.get(`/review/standard-mind-map/${taskNum}`);
@@ -69,8 +62,3 @@ export const findNode = (taskNum: string, content: string) => {
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}`);
};
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

Before

Width:  |  Height:  |  Size: 276 B

+64
View File
@@ -35,6 +35,70 @@ a:hover {
box-shadow: var(--shadow-soft);
}
/* 按钮操作区统一规范:窄屏下操作按钮纵向全宽 */
.action-row .el-button,
.edit-actions .el-button,
.fragment-edit-actions .el-button,
.task-actions .el-button {
margin: 0;
}
@media (max-width: 768px) {
.action-row,
.edit-actions,
.fragment-edit-actions,
.task-actions {
flex-direction: column;
}
.action-row .el-button,
.edit-actions .el-button,
.fragment-edit-actions .el-button,
.task-actions .el-button {
width: 100%;
}
}
/* 移动端弹窗适配:覆盖 Element Plus 内联宽度并约束 footer */
@media (max-width: 768px) {
.el-dialog {
--el-dialog-width: calc(100% - 24px) !important;
--el-dialog-margin-top: 5vh;
max-height: calc(100vh - 60px);
}
.el-dialog__body {
max-height: calc(100vh - 200px);
overflow-y: auto;
}
.el-dialog__footer {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.el-dialog__footer .el-button {
flex: 1;
margin-left: 0;
}
.el-message-box {
max-width: calc(100% - 24px);
}
.el-message-box__btns {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.el-message-box__btns .el-button {
flex: 1;
margin-left: 0;
}
}
.fade-up-enter-active,
.fade-up-leave-active {
transition: opacity 0.22s ease, transform 0.22s ease;
-41
View File
@@ -1,41 +0,0 @@
<script setup lang="ts">
defineProps<{
msg: string
}>()
</script>
<template>
<div class="greetings">
<h1 class="green">{{ msg }}</h1>
<h3>
Youve successfully created a project with
<a href="https://vite.dev/" target="_blank" rel="noopener">Vite</a> +
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
</h3>
</div>
</template>
<style scoped>
h1 {
font-weight: 500;
font-size: 2.6rem;
position: relative;
top: -10px;
}
h3 {
font-size: 1.2rem;
}
.greetings h1,
.greetings h3 {
text-align: center;
}
@media (min-width: 1024px) {
.greetings h1,
.greetings h3 {
text-align: left;
}
}
</style>
+2
View File
@@ -50,6 +50,8 @@ const submitForm = async (formEl: FormInstance | undefined) => {
}
});
};
defineExpose({ registerData, loading, submitForm, isNotEmpty });
</script>
<template>
-10
View File
@@ -27,13 +27,9 @@ const props = defineProps<{
height?: string;
/** 节点可选择模式(点击节点触发 node-select 事件) */
selectable?: boolean;
/** 当前选中的节点路径(用于高亮,仅在 selectable 模式下生效) */
selectedPath?: string;
}>();
const emit = defineEmits<{
/** 编辑模式下结构变化时抛出最新大纲文本 */
(e: "change", outline: string): void;
/** 点击带溯源信息的节点 */
(e: "node-click", node: { sourceType: string; sourceId: number }): void;
/** 选择模式下点击节点,返回标题+路径 */
@@ -156,12 +152,6 @@ const render = () => {
});
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
+14 -5
View File
@@ -20,6 +20,7 @@
type="success"
plain
class="logout-btn"
:loading="loggingOut"
@click="handleLogout"
>
退出登录
@@ -28,7 +29,7 @@
</template>
<script setup lang="ts">
import { computed } from "vue";
import { computed, ref } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import router from "@/router";
@@ -38,18 +39,26 @@ const route = useRoute();
const isLoginRoute = computed(() => route.path === "/login");
const showBackButton = computed(() => route.path !== "/login" && route.path !== "/welcome");
const pageTitle = computed(() => route.meta?.title as string | undefined);
const loggingOut = ref(false);
const handleLogout = async () => {
if (loggingOut.value) return;
loggingOut.value = true;
try {
await logout();
} catch {
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
} finally {
try {
await logout();
} catch {
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
}
localStorage.removeItem("isLoggedIn");
ElMessage.success("已退出登录");
await router.push("/login");
} finally {
loggingOut.value = false;
}
};
defineExpose({ isLoginRoute, showBackButton, pageTitle, loggingOut, handleLogout });
</script>
<style scoped>
+78 -54
View File
@@ -1,18 +1,14 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
getReviewTaskStats,
getTaskReview,
type ReviewFeedItem,
type ReviewTaskStats,
} from "@/api/review";
const router = useRouter();
const loading = ref(false);
const openingTaskNum = ref("");
const tasks = ref<ReviewTaskStats[]>([]);
const summary = computed(() => ({
@@ -40,21 +36,9 @@ const loadTasks = async () => {
}
};
const openTaskReview = async (row: ReviewTaskStats) => {
const openTaskReview = (row: ReviewTaskStats) => {
if (!row.taskNum) return;
openingTaskNum.value = row.taskNum;
try {
const res = await getTaskReview(row.taskNum);
const items: ReviewFeedItem[] = res?.data || [];
const first = items[0];
if (!first) {
ElMessage.info("该任务暂无可复习内容");
return;
}
router.push(`/review/detail/${first.sourceType.toLowerCase()}/${first.id}`);
} finally {
openingTaskNum.value = "";
}
router.push(`/review/detail/task/${encodeURIComponent(row.taskNum)}`);
};
onMounted(() => {
@@ -66,7 +50,7 @@ onMounted(() => {
<section class="review-page">
<div class="table-toolbar">
<span class="toolbar-placeholder"></span>
<el-button type="success" plain size="small" :loading="loading" @click="loadTasks">刷新</el-button>
<el-button type="success" plain :loading="loading" @click="loadTasks">刷新</el-button>
</div>
<div class="summary-grid">
@@ -84,37 +68,43 @@ onMounted(() => {
</article>
</div>
<article class="surface-card table-card">
<el-table v-loading="loading" :data="tasks" stripe @row-click="openTaskReview">
<el-table-column prop="taskName" label="任务名" min-width="180" />
<el-table-column prop="effectiveTime" label="累计有效学习时长" min-width="150">
<template #default="{ row }">
{{ formatEffectiveTime(row.effectiveTime) }}
</template>
</el-table-column>
<el-table-column prop="reportCount" label="学习报告数" min-width="120" />
<el-table-column prop="fragmentCount" label="学习残片数" min-width="120" />
<el-table-column label="操作" width="200">
<template #default="{ row }">
<el-button
text
type="success"
:loading="openingTaskNum === row.taskNum"
@click.stop="openTaskReview(row)"
>
查看记录
</el-button>
<el-button
text
type="primary"
@click.stop="router.push(`/review/recall/${row.taskNum}`)"
>
回忆复习
</el-button>
</template>
</el-table-column>
</el-table>
</article>
<div v-if="tasks.length > 0" v-loading="loading" class="task-list">
<article
v-for="row in tasks"
:key="row.taskNum"
class="surface-card task-card"
>
<div class="task-head">
<strong>{{ row.taskName }}</strong>
</div>
<div class="task-meta">
<span>累计有效学习时长{{ formatEffectiveTime(row.effectiveTime) }}</span>
</div>
<div class="task-stats">
<span>学习报告数量{{ row.reportCount || 0 }}</span>
<span>学习残片数量{{ row.fragmentCount || 0 }}</span>
</div>
<div class="task-actions">
<el-button
text
type="success"
size="small"
@click="openTaskReview(row)"
>
查看记录
</el-button>
<el-button
class="recall-button"
type="success"
size="small"
@click="router.push(`/review/recall/${row.taskNum}`)"
>
回忆复习
</el-button>
</div>
</article>
</div>
<el-empty v-if="!loading && tasks.length === 0" description="暂无复习任务" />
</section>
</template>
@@ -153,12 +143,40 @@ onMounted(() => {
color: var(--green-900);
}
.table-card {
padding: 10px;
.task-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.table-card :deep(.el-table__row) {
cursor: pointer;
.task-card {
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 10px;
}
.task-head strong {
display: block;
color: var(--green-900);
font-size: 15px;
overflow-wrap: anywhere;
}
.task-meta,
.task-stats {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
color: var(--text-secondary);
font-size: 13px;
}
.task-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 4px;
}
@media (max-width: 900px) {
@@ -166,4 +184,10 @@ onMounted(() => {
grid-template-columns: 1fr;
}
}
@media (max-width: 768px) {
.task-actions .recall-button {
order: -1;
}
}
</style>
+33 -29
View File
@@ -9,34 +9,29 @@ import {
} from "@/api/review";
import { getSessionDetail } from "@/api/studySessions";
import { updateFragments } from "@/api/reportFragments";
import { findNode } from "@/api/standardMindMap";
import { ElMessage } from "element-plus";
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
const route = useRoute();
const router = useRouter();
/** 调用 findNode API 匹配标准导图中的最近节点,跳转到回忆页 */
const goToRecall = async () => {
if (!content.value || !content.value.trim()) {
router.push(`/review/recall/${taskNum.value}`);
return;
}
try {
const res = await findNode(taskNum.value, content.value.substring(0, 500));
const data = res?.data;
if (data?.path) {
router.push(`/review/recall/${taskNum.value}?focusPath=${encodeURIComponent(data.path)}`);
} else {
router.push(`/review/recall/${taskNum.value}`);
}
} catch {
router.push(`/review/recall/${taskNum.value}`);
/** 直接进入回忆复习页,节点匹配交给目标页加载后处理 */
const goToRecall = () => {
const tn = taskNum.value;
if (!tn) return;
if (content.value && content.value.trim()) {
router.push(`/review/recall/${tn}?focusContent=${encodeURIComponent(content.value.substring(0, 500))}`);
} else {
router.push(`/review/recall/${tn}`);
}
};
const contentType = computed(() => route.params.type as string);
const contentId = computed(() => Number(route.params.id));
const isTaskMode = computed(() => !!route.params.taskNum);
const activeType = ref<string | undefined>(undefined);
const activeId = ref<number | undefined>(undefined);
const contentType = computed(() => isTaskMode.value ? activeType.value : (route.params.type as string));
const contentId = computed(() => isTaskMode.value ? activeId.value ?? 0 : Number(route.params.id));
const taskModeTaskNum = computed(() => route.params.taskNum as string | undefined);
const loading = ref(true);
const content = ref("");
@@ -118,7 +113,19 @@ const loadDetail = async () => {
taskNum.value = "";
sessionInfo.value = null;
taskSessions.value = [];
if (isTaskMode.value) {
activeType.value = undefined;
activeId.value = undefined;
}
try {
if (isTaskMode.value && taskModeTaskNum.value) {
const taskRes = await getTaskReview(taskModeTaskNum.value);
const items: ReviewFeedItem[] = taskRes?.data || [];
const first = items[0];
if (!first) return;
activeType.value = first.sourceType.toLowerCase();
activeId.value = first.id;
}
let res;
if (contentType.value === "report") {
res = await getReportDetail(contentId.value);
@@ -194,8 +201,12 @@ const saveEdit = async () => {
};
watch(
() => [contentType.value, contentId.value],
() => [route.params.type, route.params.id, route.params.taskNum],
() => {
if (!isTaskMode.value) {
activeType.value = undefined;
activeId.value = undefined;
}
loadDetail();
},
{ immediate: true },
@@ -252,8 +263,8 @@ watch(
placeholder="请输入学习内容"
/>
<div class="edit-actions">
<el-button @click="cancelEdit">取消</el-button>
<el-button type="success" :loading="saving" @click="saveEdit">保存</el-button>
<el-button size="small" @click="cancelEdit">取消</el-button>
<el-button type="success" size="small" :loading="saving" @click="saveEdit">保存</el-button>
</div>
</div>
<!-- 只读模式 -->
@@ -480,11 +491,4 @@ watch(
margin-top: 12px;
}
@media (max-width: 900px) {
.form-row {
flex-direction: column;
align-items: stretch;
}
}
</style>
+40 -22
View File
@@ -2,12 +2,12 @@
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
findNode,
getStandardMindMap,
regenerateStandardMindMap,
recallCompare,
updateStandardMindMap,
listRecallRecords,
findNode,
type StandardMindMap,
type RecallRecord,
} from "@/api/standardMindMap";
@@ -32,6 +32,7 @@ const hasCompared = ref(false);
// 起点节点选择
const focusPath = ref((route.query.focusPath as string) || "");
const focusContent = ref((route.query.focusContent as string) || "");
const focusConfirmVisible = ref(false);
const selectedNodeInfo = ref<{ title: string; path: string; childCount: number } | null>(null);
@@ -51,6 +52,7 @@ const editViewer = ref<InstanceType<typeof MindMapViewer> | null>(null);
// 回忆历史
const historyRecords = ref<RecallRecord[]>([]);
const showHistory = ref(false);
const historyLoading = ref(false);
// 解析标准导图 JSON 为树节点
const standardTree = computed<MindMapTreeNode | null>(() => {
@@ -114,6 +116,17 @@ const loadData = async () => {
try {
const res = await getStandardMindMap(taskNum.value);
standard.value = res?.data || null;
if (focusContent.value && standard.value) {
try {
const nodeRes = await findNode(taskNum.value, focusContent.value.substring(0, 500));
const data = nodeRes?.data;
if (data?.path) {
focusPath.value = data.path;
}
} catch {
// 匹配失败时仍可进入回忆页
}
}
} catch (e: any) {
standard.value = null;
} finally {
@@ -250,6 +263,8 @@ const resetComparison = () => {
hasCompared.value = false;
focusPath.value = "";
recallTree.value = buildEmptyRecallTree();
standardExpanded.value = true;
editingStandard.value = false;
};
// 编辑标准导图
@@ -294,12 +309,19 @@ const cancelStandardEdit = () => {
// 查看回忆历史
const loadHistory = async () => {
if (showHistory.value) {
showHistory.value = false;
return;
}
historyLoading.value = true;
try {
const res = await listRecallRecords(taskNum.value);
historyRecords.value = res?.data || [];
showHistory.value = true;
} catch {
ElMessage.error("加载历史记录失败");
} finally {
historyLoading.value = false;
}
};
@@ -311,6 +333,8 @@ const selectHistoryRecord = (record: RecallRecord) => {
const tree = parseOutlineToTree(record.recallContent);
if (tree) recallTree.value = tree;
hasCompared.value = true;
focusPath.value = record.focusPath || "";
standardExpanded.value = true;
} catch {
ElMessage.error("解析对比记录失败");
}
@@ -371,13 +395,12 @@ onMounted(() => {
</script>
<template>
<section class="recall-page">
<section class="recall-page" v-loading="loading">
<!-- 顶部操作栏 -->
<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 :loading="historyLoading" @click="loadHistory">
{{ showHistory ? "收起历史" : "历史记录" }}
</el-button>
</div>
@@ -385,12 +408,12 @@ onMounted(() => {
<div class="review-scope surface-card" v-if="focusPath">
<span class="scope-label">复习起点</span>
<el-tag size="small" type="success" effect="light">{{ focusPath }}</el-tag>
<el-button size="small" text @click="focusPath = ''">重选节点</el-button>
<el-button size="small" text @click="resetComparison">重选节点</el-button>
</div>
<!-- 节点选择确认弹窗 -->
<el-dialog v-model="focusConfirmVisible" title="确认复习起点" width="400px">
<p v-if="selectedNodeInfo">
<p v-if="selectedNodeInfo" class="focus-confirm-text">
<strong>{{ selectedNodeInfo.title }}</strong> 为起点
复习该知识点下的 <strong>{{ selectedNodeInfo.childCount }}</strong> 个子知识点
</p>
@@ -421,9 +444,9 @@ onMounted(() => {
</div>
<!-- 回忆历史 -->
<article class="surface-card" v-if="showHistory && historyRecords.length > 0">
<article class="surface-card" v-if="showHistory">
<h3>回忆历史</h3>
<div class="history-list">
<div v-if="historyRecords.length > 0" class="history-list">
<div
v-for="record in historyRecords"
:key="record.id"
@@ -437,6 +460,7 @@ onMounted(() => {
<span class="history-detail">{{ record.matchedCount }} {{ record.missedCount }} {{ record.extraCount }}</span>
</div>
</div>
<el-empty v-else description="暂无回忆记录" :image-size="48" />
</article>
<!-- 折叠时引导告知用户展开标准导图 -->
@@ -478,18 +502,16 @@ onMounted(() => {
<div class="panel-actions">
<el-button
v-if="hasCompared"
size="small"
type="success"
@click="resetComparison"
>
返回完整导图
</el-button>
<el-button size="small" @click="standardExpanded = !standardExpanded">
<el-button @click="standardExpanded = !standardExpanded">
{{ standardExpanded ? "折叠" : "展开" }}
</el-button>
<el-button
v-if="standardExpanded"
size="small"
type="warning"
:loading="regenerating"
@click="handleRegenerate"
@@ -498,7 +520,6 @@ onMounted(() => {
</el-button>
<el-button
v-if="standardExpanded && !editingStandard"
size="small"
type="primary"
@click="startEditStandard"
>
@@ -533,7 +554,7 @@ onMounted(() => {
<div v-else-if="standardExpanded" class="standard-content">
<div class="standard-meta">
<span>来源{{ standard.generator }}</span>
<span>参考{{ standard.sourceReportCount }} 份报告 + {{ standard.sourceFragmentCount }} 份残片</span>
<span>参考{{ standard.sourceReportCount }} 学习报告</span>
</div>
<p v-if="!focusPath && !hasCompared" class="select-hint">
点击导图节点即可选择复习起点选好后凭记忆在上方补全知识点
@@ -610,11 +631,13 @@ onMounted(() => {
font-size: 18px;
}
.focus-confirm-text {
word-break: break-word;
overflow-wrap: anywhere;
}
.surface-card {
padding: 20px 22px;
background: #fff;
border-radius: 8px;
border: 1px solid var(--border-soft, #e0e0e0);
}
.surface-card h3 {
@@ -855,11 +878,6 @@ onMounted(() => {
white-space: nowrap;
}
.scope-hint {
font-size: 12px;
color: var(--text-secondary, #999);
}
.session-badge {
flex-shrink: 0;
}
+104 -87
View File
@@ -7,6 +7,7 @@ import { useTimer } from "@/components/composables/useTimer";
import {
continueSession,
endSession,
getActiveSession,
getSessionDetail,
pauseSession,
startOrContinueStudySession,
@@ -16,6 +17,7 @@ import { getFragmentsBySession, updateFragments } from "@/api/reportFragments";
import { getExpectation, getReportDraft, getTaskFragments, getTaskReports, upsertExpectation } from "@/api/studySessions";
import router from "@/router";
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
import { renderMarkdown } from "@/utils/markdown";
const {
fragmentsDialogVisible,
@@ -23,8 +25,13 @@ const {
openFragmentDialog,
closeFragmentDialog,
confirmGenerateFragment,
creatingFragment,
} = useStudyFragment();
const pageLoading = ref(true);
const timerActionLoading = ref(false);
const endingSession = ref(false);
const summaryDialogVisible = ref(false);
const summaryContent = ref("");
const summaryPreview = ref(false);
@@ -151,28 +158,7 @@ const taskInfo = ref({
const editingMaterial = ref(false);
const editMaterialContent = ref("");
const savingMaterial = ref(false);
const materialHtml = computed(() => {
const raw = taskInfo.value.materialUrl || "";
if (!raw.trim()) return "";
let html = raw;
const links: string[] = [];
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
const tag = `<a href="${url.replace(/"/g, "&quot;")}" target="_blank" rel="noopener">${text}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
const clean = url.replace(/[.。,;!??)】」』\]]+$/, "");
const tag = `<a href="${clean.replace(/"/g, "&quot;")}" target="_blank" rel="noopener">${clean}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
html = html.replace(/\n/g, "<br>");
for (let i = 0; i < links.length; i++) {
html = html.replace(`__LINK_${i}__`, links[i]);
}
return html;
});
const materialHtml = computed(() => renderMarkdown(taskInfo.value.materialUrl || ""));
function startEditMaterial() {
editMaterialContent.value = taskInfo.value.materialUrl;
@@ -326,39 +312,51 @@ const statusText = computed(() => {
});
const startTimer = async () => {
if (taskInfo.value.sessionState === "PAUSED") {
const res = await continueSession(taskInfo.value.sessionNum);
if (res.code === 200) ElMessage.success("任务继续");
await loadTaskSession();
if (timerActionLoading.value) return;
timerActionLoading.value = true;
try {
if (taskInfo.value.sessionState === "PAUSED") {
const res = await continueSession(taskInfo.value.sessionNum);
if (res.code === 200) ElMessage.success("任务继续");
await loadTaskSession();
}
// 手动开始 → 清除休息状态
localStorage.removeItem(BREAK_END_KEY.value);
isBreak.value = false;
const duration = taskInfo.value.pointerPosition || 25 * 60 * 1000;
runCountdown(duration);
} finally {
timerActionLoading.value = false;
}
// 手动开始 → 清除休息状态
localStorage.removeItem(BREAK_END_KEY.value);
isBreak.value = false;
const duration = taskInfo.value.pointerPosition || 25 * 60 * 1000;
runCountdown(duration);
};
const stopTimer = async () => {
const res = await pauseSession(taskInfo.value.sessionNum);
if (res.code === 200) {
ElMessage.success("任务暂停");
// 重新获取会话数据,同步后端计算后的时间字段
try {
const detail = await getSessionDetail(taskInfo.value.sessionNum);
if (detail?.data) {
const d = detail.data;
taskInfo.value.sessionState = d.sessionState ?? "PAUSED";
taskInfo.value.actualTime = d.actualTime ?? 0;
taskInfo.value.effectiveTime = d.effectiveTime ?? 0;
taskInfo.value.effectivenessRatio = d.effectivenessRatio ?? 0;
taskInfo.value.startTime = d.startTime ?? taskInfo.value.startTime;
taskInfo.value.endTime = d.endTime ?? "";
taskInfo.value.lastStartTime = d.lastStartTime ?? "";
taskInfo.value.pointerPosition = d.pointerPosition ?? 0;
if (timerActionLoading.value) return;
timerActionLoading.value = true;
try {
const res = await pauseSession(taskInfo.value.sessionNum);
if (res.code === 200) {
ElMessage.success("任务暂停");
// 重新获取会话数据,同步后端计算后的时间字段
try {
const detail = await getSessionDetail(taskInfo.value.sessionNum);
if (detail?.data) {
const d = detail.data;
taskInfo.value.sessionState = d.sessionState ?? "PAUSED";
taskInfo.value.actualTime = d.actualTime ?? 0;
taskInfo.value.effectiveTime = d.effectiveTime ?? 0;
taskInfo.value.effectivenessRatio = d.effectivenessRatio ?? 0;
taskInfo.value.startTime = d.startTime ?? taskInfo.value.startTime;
taskInfo.value.endTime = d.endTime ?? "";
taskInfo.value.lastStartTime = d.lastStartTime ?? "";
taskInfo.value.pointerPosition = d.pointerPosition ?? 0;
}
} catch {
taskInfo.value.sessionState = "PAUSED";
}
} catch {
taskInfo.value.sessionState = "PAUSED";
}
} finally {
timerActionLoading.value = false;
}
clear();
clearBreakState();
@@ -384,6 +382,8 @@ const endTimer = async (content: string) => {
// 用户取消结束会话,不做任何操作
return;
}
if (endingSession.value) return;
endingSession.value = true;
try {
const res = await endSession(taskInfo.value.sessionNum, content);
@@ -402,6 +402,8 @@ const endTimer = async (content: string) => {
await router.push("/study");
} catch {
ElMessage.error("结束会话失败,请重试");
} finally {
endingSession.value = false;
}
};
@@ -454,6 +456,27 @@ const restTimer = async () => {
const loadTaskSession = async () => {
try {
const activeRes = await getActiveSession();
const active = activeRes?.data;
if (active?.taskNum && active.taskNum !== taskNum) {
let goToActive = false;
try {
await ElMessageBox.confirm(
`你还有一个未完成的学习任务「${active.taskName}」(${active.sessionNum}),是否前往继续?`,
"有其他任务正在进行",
{ confirmButtonText: "前往继续", cancelButtonText: "取消", type: "warning" },
);
goToActive = true;
} catch {
// 用户取消,不开始当前任务
}
if (goToActive) {
router.push(`/start-task/${encodeURIComponent(active.taskNum)}`);
} else {
ElMessage.warning("请先完成进行中的任务后再开始");
}
return;
}
const res = await startOrContinueStudySession(taskNum);
Object.assign(taskInfo.value, res.data);
await loadExpectation();
@@ -539,12 +562,16 @@ const saveExpectation = async () => {
};
const initPage = async () => {
const hasPermission = await checkAudioPermission();
if (!hasPermission) {
const activated = await requestAudioPermission();
if (!activated) return;
try {
const hasPermission = await checkAudioPermission();
if (!hasPermission) {
const activated = await requestAudioPermission();
if (!activated) return;
}
await loadTaskSession();
} finally {
pageLoading.value = false;
}
await loadTaskSession();
};
// 碎片列表
@@ -614,11 +641,22 @@ onUnmounted(() => {
}
clear();
});
defineExpose({
taskInfo,
timerRunning,
timerIsOver,
startTimer,
stopTimer,
endTimer,
syncDisplay,
clear,
});
</script>
<template>
<div>
<section class="start-page">
<section class="start-page" v-loading="pageLoading">
<el-alert
v-if="showResumeHint"
title="已恢复上次的学习会话,继续学习吧"
@@ -663,6 +701,7 @@ onUnmounted(() => {
<el-button
text
size="small"
type="primary"
@click="expectationContent = expectationSaved; expectationDialogVisible = true"
>
修改
@@ -721,10 +760,10 @@ onUnmounted(() => {
<el-button @click="openFragmentDialog">生成残片</el-button>
</template>
<template v-else>
<el-button type="success" @click="startTimer" :disabled="timerRunning">开始</el-button>
<el-button @click="stopTimer" :disabled="!timerRunning" v-if="!timerIsOver">暂停</el-button>
<el-button type="success" @click="startTimer" :disabled="timerRunning" :loading="timerActionLoading">开始</el-button>
<el-button @click="stopTimer" :disabled="!timerRunning" :loading="timerActionLoading" v-if="!timerIsOver">暂停</el-button>
<el-button @click="openFragmentDialog">生成残片</el-button>
<el-button v-if="timerIsOver" plain type="success" @click="restTimer">休息</el-button>
<el-button v-if="timerIsOver" plain type="success" @click="restTimer" :loading="timerActionLoading">休息</el-button>
</template>
<el-button type="danger" plain @click="openSummaryDialog">结束会话</el-button>
</div>
@@ -749,12 +788,12 @@ onUnmounted(() => {
/>
<div class="fragment-edit-actions">
<el-button size="small" @click="cancelEditFragment">取消</el-button>
<el-button size="small" type="primary" :loading="savingFragment" @click="saveEditFragment(fragment.id)">保存</el-button>
<el-button size="small" type="success" :loading="savingFragment" @click="saveEditFragment(fragment.id)">保存</el-button>
</div>
</template>
<template v-else>
<span class="fragment-content">{{ fragment.content }}</span>
<el-button size="small" @click="startEditFragment(fragment)">编辑</el-button>
<el-button text type="primary" size="small" @click="startEditFragment(fragment)">编辑</el-button>
</template>
</div>
</article>
@@ -807,7 +846,7 @@ onUnmounted(() => {
/>
<template #footer>
<el-button @click="closeFragmentDialog">取消</el-button>
<el-button type="success" @click="confirmGenerateFragment(taskInfo.sessionNum)">确定生成</el-button>
<el-button type="success" :loading="creatingFragment" @click="confirmGenerateFragment(taskInfo.sessionNum)">确定生成</el-button>
</template>
</el-dialog>
@@ -867,7 +906,7 @@ onUnmounted(() => {
</div>
<template #footer>
<el-button @click="closeSummaryDialog">取消</el-button>
<el-button type="success" @click="endTimer(summaryContent)">确认结束</el-button>
<el-button type="success" :loading="endingSession" @click="endTimer(summaryContent)">确认结束</el-button>
</template>
</el-dialog>
</div>
@@ -1104,10 +1143,6 @@ onUnmounted(() => {
gap: 8px;
}
.action-row .el-button {
margin: 0;
}
.fragments-card {
padding: 20px;
}
@@ -1165,20 +1200,12 @@ onUnmounted(() => {
}
@media (max-width: 768px) {
.top-head {
flex-direction: column;
}
.info-grid {
grid-template-columns: 1fr;
}
.action-row {
flex-direction: column;
}
.action-row .el-button {
width: 100%;
.summary-toolbar .el-button {
flex: 1;
}
}
@@ -1271,14 +1298,4 @@ onUnmounted(() => {
text-overflow: ellipsis;
}
.history-content {
flex: 1;
font-size: 14px;
line-height: 1.6;
color: var(--text-primary);
word-break: break-word;
}
.report-item .history-content {
margin: 0;
}</style>
</style>
+41 -67
View File
@@ -4,7 +4,8 @@ import request from "@/utils/request";
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getReviewTaskStatsByTask } from "@/api/review";
import { getActiveSession } from "@/api/studySessions";
import { renderMarkdown } from "@/utils/markdown";
import { applicationStatusOptions } from "@/utils/taskApplication";
import {
getPriorityWeights,
@@ -43,42 +44,14 @@ const pageSize = 20;
const taskApplications = ref<TaskApplication[]>([]);
const applicationsLoading = ref(false);
const appUrlTitles = ref<Record<number, string>>({});
const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
{ label: "待应用", value: "TODO" },
{ label: "进行中", value: "DOING" },
{ label: "已完成", value: "DONE" },
];
const updatingApplicationId = ref<number | null>(null);
const removingTask = ref(false);
const weightsLoading = ref(false);
const selectedTask = computed(() =>
tasks.value.find((item) => item.taskId === selectedTaskId.value) || null
);
const escapeHtml = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const escapeAttr = (s: string) => s.replace(/"/g, "&quot;").replace(/&/g, "&amp;");
function renderMarkdown(raw: string): string {
if (!raw.trim()) return "";
let html = raw;
const links: string[] = [];
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
const clean = url.replace(/[.。,;!!???)]」》]]+$/, "");
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(clean)}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
html = html.replace(/\n/g, "<br>");
for (let i = 0; i < links.length; i++) {
html = html.replace(`__LINK_${i}__`, links[i]);
}
return html;
}
const materialHtml = computed(() => renderMarkdown(selectedTask.value?.materialUrl || ""));
const formatEffectiveTime = (seconds: number): string => {
@@ -134,6 +107,8 @@ async function loadTaskApplications(taskNum: string) {
}
const changeApplicationStatus = async (item: TaskApplication) => {
if (updatingApplicationId.value !== null) return;
updatingApplicationId.value = item.id;
try {
await updateTaskApplication(item.id, {
title: item.title,
@@ -147,6 +122,8 @@ const changeApplicationStatus = async (item: TaskApplication) => {
if (selectedTask.value) {
await loadTaskApplications(selectedTask.value.taskNum);
}
} finally {
updatingApplicationId.value = null;
}
};
@@ -208,30 +185,12 @@ const handlePageChange = (page: number) => {
fetchTasks(page);
};
const startTask = async () => {
const startTask = () => {
if (!selectedTask.value) {
ElMessage.warning("请先选择一个任务");
return;
}
const taskNum = selectedTask.value.taskNum;
try {
const res = await getActiveSession(taskNum);
if (res?.code === 200 && res.data) {
// 有其他任务的活跃会话
const active = res.data;
ElMessageBox.confirm(
`你还有一个未完成的学习任务「${active.taskName}」(${active.sessionNum}),是否前往继续?`,
"有其他任务正在进行",
{ confirmButtonText: "前往继续", cancelButtonText: "取消", type: "warning" }
).then(() => {
router.push(`/start-task/${encodeURIComponent(active.taskNum)}`);
}).catch(() => {});
return;
}
} catch {
// 查询失败不阻塞,直接跳转
}
router.push(`/start-task/${encodeURIComponent(taskNum)}`);
router.push(`/start-task/${encodeURIComponent(selectedTask.value.taskNum)}`);
};
const addTask = () => {
@@ -251,6 +210,8 @@ const removeTask = async () => {
ElMessage.warning("请先选择一个任务");
return;
}
if (removingTask.value) return;
removingTask.value = true;
const target = selectedTask.value;
try {
await ElMessageBox.confirm(`确定删除任务「${target.title}」?关联的学习会话、学习报告、应用场景等数据将被一并删除。`, "确认删除", {
@@ -258,14 +219,16 @@ const removeTask = async () => {
cancelButtonText: "取消",
type: "warning",
});
const res = await request.del(`/tasks/${target.taskId}`, {});
if (res.code === 200) {
ElMessage.success(`任务 ${target.title} 删除成功`);
tasks.value = tasks.value.filter((item) => item.taskId !== target.taskId);
selectedTaskId.value = tasks.value[0]?.taskId ?? null;
}
} catch {
return; // 用户取消
}
const res = await request.del(`/tasks/${target.taskId}`, {});
if (res.code === 200) {
ElMessage.success(`任务 ${target.title} 删除成功`);
tasks.value = tasks.value.filter((item) => item.taskId !== target.taskId);
selectedTaskId.value = tasks.value[0]?.taskId ?? null;
// 用户取消或删除失败,保持页面状态
} finally {
removingTask.value = false;
}
};
@@ -285,6 +248,8 @@ const weightsSum = computed(() =>
);
const openWeightsDialog = async () => {
if (weightsLoading.value) return;
weightsLoading.value = true;
try {
const res = await getPriorityWeights();
const data = res?.data;
@@ -296,8 +261,10 @@ const openWeightsDialog = async () => {
}
} catch {
// 读取失败时保持默认值
} finally {
weightsLoading.value = false;
weightsDialogVisible.value = true;
}
weightsDialogVisible.value = true;
};
const saveWeights = async () => {
@@ -433,6 +400,8 @@ onMounted(() => {
v-model="item.status"
size="small"
class="application-status"
:loading="updatingApplicationId === item.id"
:disabled="updatingApplicationId !== null"
@change="changeApplicationStatus(item)"
>
<el-option
@@ -457,12 +426,12 @@ onMounted(() => {
<aside class="surface-card action-card">
<div class="block-title">常用操作</div>
<el-button size="large" @click="fetchTasks" :loading="loading">刷新列表</el-button>
<el-button @click="fetchTasks" :loading="loading">刷新列表</el-button>
<el-button type="success" size="large" @click="startTask">开始任务</el-button>
<el-button size="large" @click="addTask">添加任务</el-button>
<el-button size="large" @click="changeTask">更新任务</el-button>
<el-button size="large" @click="openWeightsDialog">权重配置</el-button>
<el-button type="danger" size="large" @click="removeTask">删除任务</el-button>
<el-button @click="addTask">添加任务</el-button>
<el-button @click="changeTask">更新任务</el-button>
<el-button :loading="weightsLoading" @click="openWeightsDialog">权重配置</el-button>
<el-button type="danger" :loading="removingTask" @click="removeTask">删除任务</el-button>
</aside>
</main>
</div>
@@ -791,8 +760,13 @@ onMounted(() => {
}
@media (max-width: 768px) {
.page-head {
flex-direction: column;
.weight-row {
gap: 8px;
}
.weight-label {
width: 64px;
font-size: 13px;
}
.action-card {
+119 -114
View File
@@ -11,6 +11,8 @@ import {
type TaskApplication,
} from "@/api/tasks";
import { getUrlTitle } from "@/utils/fetchTitle";
import { renderMarkdown } from "@/utils/markdown";
import { applicationStatusOptions } from "@/utils/taskApplication";
const router = useRouter();
const route = useRoute();
@@ -32,18 +34,17 @@ const priority = ref({
});
const priorityOptions = [0, 1, 2, 3, 4, 5];
const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
{ label: "待应用", value: "TODO" },
{ label: "进行中", value: "DOING" },
{ label: "已完成", value: "DONE" },
];
const applications = ref<TaskApplication[]>([]);
const applicationLoading = ref(false);
const appUrlTitles = ref<Record<number, string>>({});
const applicationDialogVisible = ref(false);
const applicationSaving = ref(false);
const deletingApplicationId = ref<number | null>(null);
const editingApplicationId = ref<number | null>(null);
const pageLoading = ref(false);
const submitting = ref(false);
const previewLoading = ref(false);
const applicationForm = ref<{
title: string;
description: string;
@@ -138,13 +139,19 @@ const editApplication = (item: TaskApplication) => {
};
const removeApplication = async (item: TaskApplication) => {
await deleteTaskApplication(item.id);
ElMessage.success("应用场景已删除");
if (editingApplicationId.value === item.id) {
resetApplicationForm();
}
if (taskNum.value) {
await loadApplications(taskNum.value);
if (deletingApplicationId.value !== null) return;
deletingApplicationId.value = item.id;
try {
await deleteTaskApplication(item.id);
ElMessage.success("应用场景已删除");
if (editingApplicationId.value === item.id) {
resetApplicationForm();
}
if (taskNum.value) {
await loadApplications(taskNum.value);
}
} finally {
deletingApplicationId.value = null;
}
};
@@ -171,71 +178,80 @@ const convertMaterialUrls = async () => {
materialUrl.value = result;
};
const createTask = () => {
convertMaterialUrls().then(() => {
request
.post("/tasks", {
const createTask = async () => {
if (submitting.value) return;
submitting.value = true;
try {
await convertMaterialUrls();
const result = await request.post("/tasks", {
taskName: taskName.value,
taskDescription: taskDescription.value,
materialUrl: materialUrl.value,
...priority.value,
})
.then((result) => {
if (result.code === 200) {
ElMessage.success("创建任务成功");
router.push({ name: "study" });
} else {
ElMessage.error("任务创建失败:" + result.message);
}
});
});
};
const loadTask = () => {
if (taskId !== null) {
request.get(`/tasks/${taskId}`, {}).then((result) => {
if (result.code === 200) {
const data = result.data;
taskNum.value = data.taskNum || "";
taskName.value = data.taskName;
taskDescription.value = data.taskDescription;
materialUrl.value = data.materialUrl || "";
priority.value = {
urgency: data.urgency,
importance: data.importance,
contentDifficulty: data.contentDifficulty,
futureValue: data.futureValue,
subjectivePriority: data.subjectivePriority,
};
if (taskNum.value) {
loadApplications(taskNum.value);
}
} else {
ElMessage.error(`任务加载失败:${result.message}`);
}
});
if (result.code === 200) {
ElMessage.success("创建任务成功");
await router.push({ name: "study" });
} else {
ElMessage.error("任务创建失败:" + result.message);
}
} finally {
submitting.value = false;
}
};
const updateTask = () => {
convertMaterialUrls().then(() => {
request
.put("/tasks/" + taskId, {
const loadTask = async () => {
if (taskId === null) return;
pageLoading.value = true;
try {
const result = await request.get(`/tasks/${taskId}`, {});
if (result.code === 200) {
const data = result.data;
taskNum.value = data.taskNum || "";
taskName.value = data.taskName;
taskDescription.value = data.taskDescription;
materialUrl.value = data.materialUrl || "";
priority.value = {
urgency: data.urgency,
importance: data.importance,
contentDifficulty: data.contentDifficulty,
futureValue: data.futureValue,
subjectivePriority: data.subjectivePriority,
};
if (taskNum.value) {
loadApplications(taskNum.value);
}
} else {
ElMessage.error(`任务加载失败:${result.message}`);
}
} catch (error: any) {
ElMessage.error(error?.message || "任务加载失败,请重试");
} finally {
pageLoading.value = false;
}
};
const updateTask = async () => {
if (submitting.value) return;
submitting.value = true;
try {
await convertMaterialUrls();
const result = await request.put("/tasks/" + taskId, {
id: taskId,
taskName: taskName.value,
taskDescription: taskDescription.value,
materialUrl: materialUrl.value,
...priority.value,
})
.then((result) => {
if (result.code === 200) {
ElMessage.success("更新任务成功");
router.push({ name: "study" });
} else {
ElMessage.error("任务更新失败:" + result.message);
}
});
});
if (result.code === 200) {
ElMessage.success("更新任务成功");
await router.push({ name: "study" });
} else {
ElMessage.error("任务更新失败:" + result.message);
}
} finally {
submitting.value = false;
}
};
const cancelTask = () => {
@@ -243,16 +259,17 @@ const cancelTask = () => {
router.push({ name: "study" });
};
const submitTask = () => {
const submitTask = async () => {
if (submitting.value) return;
switch (route.name) {
case "add-task":
createTask();
await createTask();
break;
case "update-task":
updateTask();
await updateTask();
break;
default:
ElMessage.error("未知操作类型");
ElMessage.error("该功能暂不可用,请刷新后重试");
}
};
@@ -276,44 +293,17 @@ const isMobile = computed(() => screenWidth.value <= 900);
// 学习材料 Markdown 预览
const showPreview = ref(false);
const materialPreview = ref("");
const previewLoading = ref(false);
const escapeHtml = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const escapeAttr = (s: string) => s.replace(/"/g, "&quot;").replace(/&/g, "&amp;");
function renderMarkdown(raw: string, urlTitles: Record<string, string> = {}): string {
if (!raw.trim()) return "";
let html = raw;
// 1) [text](url) → &lt;a&gt; 占位,防止后续裸 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 → &lt;a&gt; 占位
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
const clean = url.replace(/[.。,;!??)】」』\]]+$/, "");
const label = urlTitles[clean] || url;
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(label)}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
// 3) 换行
html = html.replace(/\n/g, "<br>");
// 4) 还原占位
for (let i = 0; i < links.length; i++) {
html = html.replace(`__LINK_${i}__`, links[i]);
}
return html;
}
async function previewMaterial() {
showPreview.value = true;
const raw = materialUrl.value || "";
if (!raw.trim()) { materialPreview.value = ""; return; }
if (previewLoading.value) return;
previewLoading.value = true;
try {
const raw = materialUrl.value || "";
if (!raw.trim()) {
materialPreview.value = "";
showPreview.value = true;
return;
}
const titles: Record<string, string> = {};
const bareUrls = new Set<string>();
raw.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
@@ -323,14 +313,30 @@ async function previewMaterial() {
const results = await Promise.all([...bareUrls].map(async (u) => ({ u, t: await getUrlTitle(u) })));
results.forEach(({ u, t }) => { titles[u] = t; });
materialPreview.value = renderMarkdown(raw, titles);
showPreview.value = true;
} finally {
previewLoading.value = false;
}
}
defineExpose({
priorityOptions,
priority,
taskNum,
taskName,
taskDescription,
materialUrl,
isUpdateMode,
loadTask,
createTask,
updateTask,
submitTask,
convertMaterialUrls,
});
</script>
<template>
<section class="task-form-page">
<section class="task-form-page" v-loading="pageLoading">
<el-form label-position="top" class="surface-card form-shell">
<div class="group">
<h3>基础信息</h3>
@@ -349,6 +355,7 @@ async function previewMaterial() {
text
size="small"
type="primary"
:loading="previewLoading"
@click="previewMaterial()"
>预览</el-button>
<el-button
@@ -410,7 +417,7 @@ async function previewMaterial() {
<div class="group" v-if="isUpdateMode" v-loading="applicationLoading">
<div class="application-header">
<h3>应用场景</h3>
<el-button type="primary" @click="openApplicationDialog()">添加应用场景</el-button>
<el-button type="success" @click="openApplicationDialog()">添加应用场景</el-button>
</div>
<div class="application-list" v-if="applications.length > 0">
<div class="application-item" v-for="item in applications" :key="item.id">
@@ -426,7 +433,14 @@ async function previewMaterial() {
</el-link>
<div class="application-actions">
<el-button text type="primary" size="small" @click="editApplication(item)">编辑</el-button>
<el-button text type="danger" size="small" @click="removeApplication(item)">删除</el-button>
<el-button
text
type="danger"
size="small"
:loading="deletingApplicationId === item.id"
:disabled="deletingApplicationId !== null"
@click="removeApplication(item)"
>删除</el-button>
</div>
</div>
</div>
@@ -459,7 +473,7 @@ async function previewMaterial() {
</el-dialog>
<div class="action-row">
<el-button type="success" size="large" @click="submitTask">{{ buttonName }}</el-button>
<el-button type="success" size="large" :loading="submitting" @click="submitTask">{{ buttonName }}</el-button>
<el-button size="large" @click="cancelTask">取消</el-button>
</div>
</el-form>
@@ -608,15 +622,6 @@ async function previewMaterial() {
padding: 16px;
}
.action-row {
flex-direction: column;
}
.action-row .el-button {
width: 100%;
margin: 0;
}
.application-main {
align-items: flex-start;
flex-direction: column;
+186 -143
View File
@@ -1,65 +1,39 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import router from "@/router";
import { getReviewFeed, type ReviewFeedItem } from "@/api/review";
import { getReviewFeed, getTaskReview, type ReviewFeedItem } from "@/api/review";
const reviewItems = ref<ReviewFeedItem[]>([]);
const isHovering = ref(false);
const contentRef = ref<HTMLElement | null>(null);
const AUTO_SCROLL_DURATION = 150_000;
let autoScroll: Animation | null = null;
interface SessionGroup {
interface FragmentChip {
id: number;
sessionNum: string;
taskName: string;
taskNum: string;
content: string;
hasReport: boolean;
fragmentCount: number;
navigateType: string;
navigateId: number;
}
// 按 sessionNum 分组,一个会话展示为一个 chip
const sessionGroups = computed<SessionGroup[]>(() => {
const map = new Map<string, ReviewFeedItem[]>();
for (const item of reviewItems.value) {
const list = map.get(item.sessionNum) || [];
list.push(item);
map.set(item.sessionNum, list);
}
const truncateContent = (content: string, maxLength = 120) =>
content.length > maxLength ? content.substring(0, maxLength) + "..." : content;
const groups: SessionGroup[] = [];
for (const [sessionNum, items] of map) {
const first = items[0];
const report = items.find(i => i.sourceType === "REPORT");
const fragments = items.filter(i => i.sourceType === "FRAGMENT");
const rawContent = report?.content || fragments.map(f => f.content).join("");
const content = rawContent.length > 120
? rawContent.substring(0, 120) + "..."
: rawContent;
groups.push({
sessionNum,
taskName: first.taskName,
taskNum: first.taskNum,
content,
hasReport: !!report,
fragmentCount: fragments.length,
navigateType: report ? "report" : "fragment",
navigateId: report ? report.id : (fragments[0]?.id ?? 0),
});
}
groups.sort((a, b) => {
const aItem = reviewItems.value.find(i => i.sessionNum === a.sessionNum);
const bItem = reviewItems.value.find(i => i.sessionNum === b.sessionNum);
return (bItem?.createdTime || "").localeCompare(aItem?.createdTime || "");
});
return groups;
});
// 滚动条只展示学习残片,每条残片单独作为 chip
const fragmentChips = computed<FragmentChip[]>(() =>
reviewItems.value
.filter(item => item.sourceType === "FRAGMENT")
.map(item => ({
id: item.id,
sessionNum: item.sessionNum,
taskName: item.taskName,
taskNum: item.taskNum,
content: truncateContent(item.content),
})),
);
// 复制一份实现无缝循环
const duplicatedGroups = computed(() => [...sessionGroups.value, ...sessionGroups.value]);
const duplicatedChips = computed(() => [...fragmentChips.value, ...fragmentChips.value]);
const loadReviewFeed = async () => {
try {
@@ -70,52 +44,72 @@ const loadReviewFeed = async () => {
}
};
// 回忆卡片:点击滚动内容先尝试回忆,再看原文
const recallCard = ref<{ visible: boolean; group: SessionGroup | null; revealed: boolean }>({
// 回忆卡片:点击残片先尝试回忆,再展开该会话的报告和其他残片进行对照
const recallCard = ref<{
visible: boolean;
fragment: FragmentChip | null;
report: ReviewFeedItem | null;
fragments: ReviewFeedItem[];
revealed: boolean;
loadingSession: boolean;
loadError: string;
}>({
visible: false,
group: null,
fragment: null,
report: null,
fragments: [],
revealed: false,
loadingSession: false,
loadError: "",
});
// 当前回忆卡片对应会话的全部记录
const recallSessionItems = computed(() => {
const group = recallCard.value.group;
if (!group) return [];
return reviewItems.value.filter((i) => i.sessionNum === group.sessionNum);
});
const goToReviewDetail = (group: SessionGroup) => {
recallCard.value = { visible: true, group, revealed: false };
const openRecallCard = (fragment: FragmentChip) => {
recallCard.value = {
visible: true,
fragment,
report: null,
fragments: [],
revealed: false,
loadingSession: false,
loadError: "",
};
};
const revealRecallContent = () => {
recallCard.value.revealed = true;
const revealRecallContent = async () => {
const fragment = recallCard.value.fragment;
if (!fragment || recallCard.value.loadingSession || recallCard.value.revealed) return;
if (recallCard.value.report || recallCard.value.fragments.length > 0) {
recallCard.value.revealed = true;
return;
}
recallCard.value.loadingSession = true;
recallCard.value.loadError = "";
try {
const res = await getTaskReview(fragment.taskNum);
const items: ReviewFeedItem[] = (res?.data || []).filter(
(item: ReviewFeedItem) => item.sessionNum === fragment.sessionNum,
);
recallCard.value.report = items.find((item: ReviewFeedItem) => item.sourceType === "REPORT") || null;
recallCard.value.fragments = items.filter((item: ReviewFeedItem) => item.sourceType === "FRAGMENT");
recallCard.value.revealed = true;
} catch {
recallCard.value.loadError = "展开对照内容加载失败,请稍后重试";
} finally {
recallCard.value.loadingSession = false;
}
};
const openRecallDetail = () => {
const group = recallCard.value.group;
if (!group) return;
/** 从回忆卡片跳转到回忆复习页,节点匹配交给目标页加载后处理 */
const goToRecallFromCard = () => {
const fragment = recallCard.value.fragment;
if (!fragment) return;
recallCard.value.visible = false;
router.push(`/review/detail/${group.navigateType}/${group.navigateId}`);
};
/** 从回忆卡片跳转到回忆复习页(先匹配标准导图节点) */
const goToRecallFromCard = async () => {
const group = recallCard.value.group;
if (!group) return;
recallCard.value.visible = false;
const tn = group.taskNum;
const content = group.content || "";
const tn = fragment.taskNum;
const content = fragment.content || "";
if (tn && content) {
try {
const { findNode } = await import("@/api/standardMindMap");
const res = await findNode(tn, content.substring(0, 500));
const data = res?.data;
if (data?.path) {
router.push(`/review/recall/${tn}?focusPath=${encodeURIComponent(data.path)}`);
return;
}
} catch { /* fall through */ }
router.push(`/review/recall/${tn}?focusContent=${encodeURIComponent(content)}`);
} else if (tn) {
router.push(`/review/recall/${tn}`);
} else {
router.push("/review");
@@ -130,8 +124,50 @@ const startReview = () => {
router.push("/review");
};
const handleTrackWheel = (event: WheelEvent) => {
const anim = autoScroll;
const content = contentRef.value;
if (!anim || !content) return;
anim.pause();
const rawDelta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
const delta = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? rawDelta * 16 : rawDelta;
if (!delta) return;
// 一屏内容的宽度对应一轮自动滚动
const loopWidth = content.scrollWidth / 2;
if (!loopWidth) return;
const current = anim.currentTime;
if (typeof current !== "number") return;
anim.currentTime = Math.min(
Math.max(current + (delta / loopWidth) * AUTO_SCROLL_DURATION, 0),
AUTO_SCROLL_DURATION,
);
};
const pauseAutoScroll = () => {
autoScroll?.pause();
};
const resumeAutoScroll = () => {
autoScroll?.play();
};
onMounted(() => {
loadReviewFeed();
autoScroll = contentRef.value?.animate(
[
{ transform: "translateX(0)" },
{ transform: "translateX(-50%)" },
],
{ duration: AUTO_SCROLL_DURATION, iterations: Infinity, easing: "linear" },
) || null;
});
onBeforeUnmount(() => {
autoScroll?.cancel();
});
</script>
@@ -141,26 +177,27 @@ onMounted(() => {
<div class="review-scroll-section surface-card">
<div class="review-scroll-header">
<span class="color-legend">
<span class="dot dot-report"></span> 学习报告
<span class="dot dot-fragment"></span> 学习残片
</span>
</div>
<div class="review-scroll-track">
<div
class="review-scroll-track"
@mouseenter="pauseAutoScroll"
@mouseleave="resumeAutoScroll"
@wheel.prevent="handleTrackWheel"
>
<div
ref="contentRef"
class="review-scroll-content"
:class="{ paused: isHovering }"
@mouseenter="isHovering = true"
@mouseleave="isHovering = false"
>
<span
v-for="(group, index) in duplicatedGroups"
v-for="(chip, index) in duplicatedChips"
:key="index"
class="review-chip"
:class="group.hasReport ? 'has-report' : 'fragments-only'"
@click="goToReviewDetail(group)"
class="review-chip fragment-chip"
@click="openRecallCard(chip)"
>
<strong class="chip-task">{{ group.taskName }}</strong>
<span class="chip-content">{{ group.content }}</span>
<strong class="chip-task">{{ chip.taskName }}</strong>
<span class="chip-content">{{ chip.content }}</span>
</span>
</div>
</div>
@@ -193,35 +230,53 @@ onMounted(() => {
<!-- 回忆卡片先回忆再对照 -->
<el-dialog
v-model="recallCard.visible"
:title="recallCard.group?.taskName || '回忆一下'"
:title="recallCard.fragment?.taskName || '回忆一下'"
width="560px"
class="recall-card-dialog"
>
<template v-if="recallCard.group">
<template v-if="recallCard.fragment">
<p class="recall-question">
这次学习共有 {{ recallSessionItems.length }} 条记录看着下面这个片先试着回忆当时还学了什么
看着下面这个先试着回忆当时还学了什么
</p>
<blockquote class="recall-snippet">{{ recallCard.group.content }}</blockquote>
<blockquote class="recall-snippet">{{ recallCard.fragment.content }}</blockquote>
<p v-if="recallCard.loadError" class="recall-error">{{ recallCard.loadError }}</p>
<div v-if="recallCard.revealed" class="recall-full-list">
<div v-if="recallCard.report" class="recall-full-item">
<span class="recall-item-tag tag-report">报告</span>
<span class="recall-item-content">{{ recallCard.report.content }}</span>
</div>
<div
v-for="item in recallSessionItems"
:key="`${item.sourceType}-${item.id}`"
v-for="item in recallCard.fragments"
:key="item.id"
class="recall-full-item"
:class="{ 'is-clicked': item.id === recallCard.fragment?.id }"
>
<span class="recall-item-tag" :class="item.sourceType === 'REPORT' ? 'tag-report' : 'tag-fragment'">
{{ item.sourceType === "REPORT" ? "报告" : "残片" }}
</span>
<span class="recall-item-tag tag-fragment">残片</span>
<span class="recall-item-content">{{ item.content }}</span>
</div>
<el-empty
v-if="!recallCard.report && recallCard.fragments.length === 0"
description="暂未找到该会话的对照内容"
:image-size="48"
/>
</div>
</template>
<template #footer>
<el-button v-if="!recallCard.revealed" type="success" @click="revealRecallContent">
回忆好了展开对照
<el-button
v-if="!recallCard.revealed"
type="success"
plain
:loading="recallCard.loadingSession"
@click="revealRecallContent"
>
展开对照
</el-button>
<el-button v-else type="success" @click="openRecallDetail">进入详情页</el-button>
<el-button type="success" plain @click="goToRecallFromCard">前往回忆复习</el-button>
<el-button @click="recallCard.visible = false">关闭</el-button>
<el-button v-if="!recallCard.revealed" @click="recallCard.visible = false">关闭</el-button>
<template v-else>
<el-button type="success" @click="goToRecallFromCard">前往回忆复习</el-button>
<el-button @click="recallCard.visible = false">关闭</el-button>
</template>
</template>
</el-dialog>
</div>
@@ -298,10 +353,6 @@ onMounted(() => {
margin-right: 3px;
}
.dot-report {
background: var(--green-600);
}
.dot-fragment {
background: #e6a23c;
}
@@ -316,20 +367,6 @@ onMounted(() => {
display: inline-flex;
gap: 14px;
white-space: nowrap;
animation: review-ticker 150s linear infinite;
}
.review-scroll-content.paused {
animation-play-state: paused;
}
@keyframes review-ticker {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-50%);
}
}
.review-chip {
@@ -339,7 +376,7 @@ onMounted(() => {
padding: 8px 16px;
background: var(--surface-strong);
border: 1px solid var(--border-soft);
border-left: 3px solid transparent;
border-left: 3px solid #e6a23c;
border-radius: 6px;
cursor: pointer;
transition: background 0.2s, box-shadow 0.2s;
@@ -347,23 +384,8 @@ onMounted(() => {
user-select: none;
}
.review-chip.has-report {
border-left-color: var(--green-600);
}
.review-chip.fragments-only {
border-left-color: #e6a23c;
}
.review-chip:hover {
box-shadow: var(--shadow-soft);
}
.review-chip.has-report:hover {
background: #e8f5e9;
}
.review-chip.fragments-only:hover {
background: #fff8e1;
}
@@ -402,6 +424,12 @@ onMounted(() => {
white-space: normal;
}
.recall-error {
margin: 0 0 10px;
color: var(--el-color-danger, #f56c6c);
font-size: 13px;
}
.recall-full-list {
display: flex;
flex-direction: column;
@@ -420,6 +448,11 @@ onMounted(() => {
border-radius: 6px;
}
.recall-full-item.is-clicked {
background: #fff8e1;
border-color: #e6a23c;
}
.recall-item-tag {
flex-shrink: 0;
font-size: 11px;
@@ -456,4 +489,14 @@ onMounted(() => {
grid-template-columns: 1fr;
}
}
@media (max-width: 768px) {
.recall-card-dialog :deep(.el-dialog__footer) {
flex-direction: column;
}
.recall-card-dialog :deep(.el-dialog__footer .el-button) {
width: 100%;
}
}
</style>
+16 -11
View File
@@ -5,6 +5,7 @@ import {createFragments} from '@/api/reportFragments';
export const useStudyFragment = () => {
const fragmentsDialogVisible = ref(false);
const fragmentContent = ref('');
const creatingFragment = ref(false);
const openFragmentDialog = () => {
fragmentContent.value = '';
@@ -26,23 +27,24 @@ export const useStudyFragment = () => {
};
const confirmGenerateFragment = async (sessionNum: string): Promise<boolean> => {
if (creatingFragment.value) return false;
if (!fragmentContent.value.trim()) {
ElMessage.warning('请输入学习内容!');
return false;
}
creatingFragment.value = true;
try {
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
});
} catch {
ElMessage.info('已取消生成');
return false;
}
try {
try {
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
});
} catch {
ElMessage.info('已取消生成');
return false;
}
const res = await createFragments(sessionNum, fragmentContent.value);
if (res.code === 200) {
ElMessage.success('学习残片生成成功!');
@@ -55,12 +57,15 @@ export const useStudyFragment = () => {
} catch (error: any) {
ElMessage.error(error.message || '请求失败');
return false;
} finally {
creatingFragment.value = false;
}
};
return {
fragmentsDialogVisible,
fragmentContent,
creatingFragment,
openFragmentDialog,
closeFragmentDialog,
confirmGenerateFragment,
-6
View File
@@ -8,7 +8,6 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
const remainingTime = ref(25 * 60 * 1000);
const timerRunning = ref(false);
const timerIsOver = ref(false);
const audioActivated = ref(false);
let timerInterval: number;
const audio = new Audio(audioUrl);
@@ -65,10 +64,8 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
await audio.play();
audio.pause();
audio.currentTime = 0;
audioActivated.value = true;
return true;
} catch {
audioActivated.value = false;
return false;
}
};
@@ -82,7 +79,6 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
await audio.play();
audio.pause();
audio.currentTime = 0;
audioActivated.value = true;
resolve(true);
} catch {
resolve(false);
@@ -95,7 +91,6 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
return {
timerMinutes,
timerSeconds,
remainingTime,
timerRunning,
timerIsOver,
runCountdown,
@@ -103,6 +98,5 @@ export function useTimer(audioUrl: string = '/resource/notification.mp3') {
clear,
checkAudioPermission,
requestAudioPermission,
audioActivated,
};
}
-7
View File
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
/>
</svg>
</template>
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
<path
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
/>
</svg>
</template>
-7
View File
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
<path
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
/>
</svg>
</template>
-7
View File
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
/>
</svg>
</template>
-19
View File
@@ -1,19 +0,0 @@
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
aria-hidden="true"
role="img"
class="iconify iconify--mdi"
width="24"
height="24"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 24 24"
>
<path
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
fill="currentColor"
></path>
</svg>
</template>
+5
View File
@@ -27,6 +27,11 @@ const routes: RouteRecordRaw[] = [
component: () => import("@/components/Review.vue"),
meta: { requiresAuth: true, title: "复习总览" },
},
{
path: "/review/detail/task/:taskNum",
component: () => import("@/components/ReviewDetail.vue"),
meta: { requiresAuth: true, title: "复习详情" },
},
{
path: "/review/detail/:type/:id",
component: () => import("@/components/ReviewDetail.vue"),
+27
View File
@@ -0,0 +1,27 @@
export const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
export const escapeAttr = (s: string) => s.replace(/"/g, "&quot;").replace(/&/g, "&amp;");
export function renderMarkdown(raw: string, urlTitles: Record<string, string> = {}): string {
if (!raw.trim()) return "";
let html = raw;
const links: string[] = [];
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m: string, text: string, url: string) => {
const tag = `<a href="${escapeAttr(url)}" target="_blank" rel="noopener">${escapeHtml(text)}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
html = html.replace(/https?:\/\/[^\s)\u3001\uFF09\u300D\u300B<>]+/g, (url) => {
const clean = url.replace(/[.。,;!??)】」』\]]+$/, "");
const label = urlTitles[clean] || clean;
const tag = `<a href="${escapeAttr(clean)}" target="_blank" rel="noopener">${escapeHtml(label)}</a>`;
links.push(tag);
return `__LINK_${links.length - 1}__`;
});
html = html.replace(/\n/g, "<br>");
for (let i = 0; i < links.length; i++) {
html = html.replace(`__LINK_${i}__`, links[i]);
}
return html;
}
+7 -7
View File
@@ -32,14 +32,14 @@ const handleError = (error: any) => {
}
if (error.response) {
const backendMessage = error.response?.data?.message || JSON.stringify(error.response?.data);
ElMessage.error(`请求失败,服务器返回: ${backendMessage}`);
const backendMessage = error.response?.data?.message;
ElMessage.error(backendMessage || "请求失败了,请稍后再试");
} else if (error.request) {
ElMessage.error("请求未收到响应,请检查接口运行状态");
ElMessage.error("请求失败了,请检查网络后重试");
} else {
ElMessage.error(error.message || "请求失败");
ElMessage.error("请求失败了,请稍后再试");
}
throw new Error("网络不通畅,请检查您的网络连接或服务器状态");
throw new Error("请求失败了,请稍后再试");
};
const validateResponse = (res: any) => {
@@ -88,8 +88,8 @@ const del = (url: string, params: Record<string, any> = {}, config: any = {}) =>
};
const requestNotImplemented = (method: string) => {
ElMessage.error(`请求方法 ${method} 未实现`);
throw new Error(`请求方法 ${method} 未实现`);
ElMessage.error("该功能暂不可用,请刷新后重试");
throw new Error("该功能暂不可用,请刷新后重试");
};
const request = (method: string, url: string, paramsOrData: any) => {
+7
View File
@@ -0,0 +1,7 @@
import type { TaskApplication } from "@/api/tasks";
export const applicationStatusOptions: { label: string; value: TaskApplication["status"] }[] = [
{ label: "待应用", value: "TODO" },
{ label: "进行中", value: "DOING" },
{ label: "已完成", value: "DONE" },
];