Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a36e28f74 | ||
|
|
e82a87d104 | ||
|
|
f408076187 | ||
|
|
7610b34621 | ||
|
|
6595ed0dfc | ||
|
|
f71abdd000 | ||
|
|
9bba684fb2 |
@@ -80,10 +80,10 @@ lpt-fe/src/
|
|||||||
|
|
||||||
- 页面主操作 / 卡片 CTA:`size="large"`,如 Study 开始任务、TaskForm 保存、Welcome 快速入口。
|
- 页面主操作 / 卡片 CTA:`size="large"`,如 Study 开始任务、TaskForm 保存、Welcome 快速入口。
|
||||||
- 区块工具栏 / 页内操作:默认尺寸,如 Review 刷新、ReviewRecall 面板操作、历史记录。
|
- 区块工具栏 / 页内操作:默认尺寸,如 Review 刷新、ReviewRecall 面板操作、历史记录。
|
||||||
- 表格/列表行内操作:`size="small" text`,如 查看记录、回忆复习、编辑、删除。
|
- 表格/列表行内操作:`size="small"`,主操作实底 `type="success"`,次操作 `text`;如 Review 卡片中「回忆复习」为主、「查看记录」为次。
|
||||||
- 弹窗 footer:默认尺寸;确认按钮 `type="success"`,取消按钮默认;危险操作统一 `type="danger"`。
|
- 弹窗 footer:默认尺寸;确认按钮 `type="success"`,取消按钮默认;危险操作统一 `type="danger"`。
|
||||||
- 正向/保存语义统一 `success`,次级编辑语义可用 `primary`,不要在同一功能上混用。
|
- 正向/保存语义统一 `success`,次级编辑语义可用 `primary`,不要在同一功能上混用。
|
||||||
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css` 的 `.action-row / .edit-actions / .fragment-edit-actions`。
|
- 窄屏(`max-width: 768px`)操作区按钮纵向全宽,全局规则位于 `src/assets/main.css` 的 `.action-row / .edit-actions / .fragment-edit-actions / .task-actions`;`.task-actions` 中主操作在上、次操作在下(如 Review 的回忆复习/查看记录)。
|
||||||
|
|
||||||
### 移动端适配
|
### 移动端适配
|
||||||
|
|
||||||
@@ -97,10 +97,17 @@ lpt-fe/src/
|
|||||||
|
|
||||||
- Markdown 渲染统一使用 `src/utils/markdown.ts` 的 `renderMarkdown`,禁止在组件内复制实现。
|
- Markdown 渲染统一使用 `src/utils/markdown.ts` 的 `renderMarkdown`,禁止在组件内复制实现。
|
||||||
- 应用场景状态常量统一使用 `src/utils/taskApplication.ts` 的 `applicationStatusOptions`。
|
- 应用场景状态常量统一使用 `src/utils/taskApplication.ts` 的 `applicationStatusOptions`。
|
||||||
|
- 用户可见错误提示必须口语化、可理解,不要直接展示接口原始 message、JSON、参数名或“服务器返回”等技术信息;技术细节留在日志。
|
||||||
- 不保留无消费者代码:未使用的 import、prop、事件、API 封装、CSS class、组件文件与依赖应及时删除。
|
- 不保留无消费者代码:未使用的 import、prop、事件、API 封装、CSS class、组件文件与依赖应及时删除。
|
||||||
- 组件公开 props/events 只在有实际消费者时保留,例如 MindMapViewer 通过 `toOutline()` 导出编辑内容,不依赖无人监听的 change 事件。
|
- 组件公开 props/events 只在有实际消费者时保留,例如 MindMapViewer 通过 `toOutline()` 导出编辑内容,不依赖无人监听的 change 事件。
|
||||||
- Vite 模板遗留文件(示例组件、icon、logo)不进入业务代码。
|
- Vite 模板遗留文件(示例组件、icon、logo)不进入业务代码。
|
||||||
|
|
||||||
|
### 测试规范
|
||||||
|
|
||||||
|
- 单元测试必须直接测试真实代码:直接调用 composable、挂载真实组件、使用真实路由;禁止把组件或 composable 的逻辑复制到测试里再自测。
|
||||||
|
- 测试中可以 mock 外部依赖(API、Element Plus 服务、Audio 等),但被测逻辑本身必须来自生产模块。
|
||||||
|
- `script setup` 内部状态需要测试访问时,通过 `defineExpose` 暴露,而不是在测试里重写一份相同逻辑。
|
||||||
|
|
||||||
### 提交前检查
|
### 提交前检查
|
||||||
|
|
||||||
- 运行 `npx vue-tsc --noEmit`、`npm run test`、`npm run build`。
|
- 运行 `npx vue-tsc --noEmit`、`npm run test`、`npm run build`。
|
||||||
|
|||||||
@@ -31,4 +31,44 @@ test.describe('Welcome page', () => {
|
|||||||
await page.locator('.quick-card').nth(1).locator('button').click();
|
await page.locator('.quick-card').nth(1).locator('button').click();
|
||||||
await expect(page).toHaveURL(/\/review/);
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,87 +1,57 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
import { mount } from '@vue/test-utils'
|
import { mount } from '@vue/test-utils'
|
||||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
import ElementPlus from 'element-plus'
|
||||||
import { reactive, ref } from 'vue'
|
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', () => ({
|
vi.mock('@/api/login', () => ({
|
||||||
login: vi.fn(),
|
login: vi.fn(),
|
||||||
logout: vi.fn(),
|
logout: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// Mock Element Plus
|
function mountLogin() {
|
||||||
vi.mock('element-plus', () => ({
|
return mount(Login, {
|
||||||
ElMessage: {
|
shallow: true,
|
||||||
success: vi.fn(),
|
global: {
|
||||||
error: vi.fn(),
|
plugins: [ElementPlus, router],
|
||||||
warning: vi.fn(),
|
|
||||||
info: vi.fn(),
|
|
||||||
},
|
},
|
||||||
}))
|
|
||||||
|
|
||||||
import { login } from '@/api/login'
|
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
|
|
||||||
function createTestRouter() {
|
|
||||||
return createRouter({
|
|
||||||
history: createMemoryHistory(),
|
|
||||||
routes: [
|
|
||||||
{ path: '/login', component: { template: '<div/>' } },
|
|
||||||
{ path: '/welcome', component: { template: '<div/>' } },
|
|
||||||
],
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('Login.vue logic', () => {
|
function createForm(valid = true) {
|
||||||
beforeEach(() => {
|
return {
|
||||||
|
validate: (callback: (valid: boolean) => void) => callback(valid),
|
||||||
|
} as any
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Login.vue', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
localStorage.clear()
|
localStorage.clear()
|
||||||
})
|
|
||||||
|
|
||||||
describe('isNotEmpty validator', () => {
|
|
||||||
it('calls callback with error message when value is empty', () => {
|
|
||||||
const callback = vi.fn()
|
|
||||||
const rule = { message: '请输入账号!' }
|
|
||||||
// isNotEmpty logic
|
|
||||||
const value = ''
|
|
||||||
if (!value) {
|
|
||||||
callback(rule.message)
|
|
||||||
} else {
|
|
||||||
callback()
|
|
||||||
}
|
|
||||||
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('calls callback without error when value is present', () => {
|
|
||||||
const callback = vi.fn()
|
|
||||||
const rule = { message: '请输入账号!' }
|
|
||||||
const value = 'admin'
|
|
||||||
if (!value) {
|
|
||||||
callback(rule.message)
|
|
||||||
} else {
|
|
||||||
callback()
|
|
||||||
}
|
|
||||||
expect(callback).toHaveBeenCalledWith()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('submitForm logic', () => {
|
|
||||||
it('sets localStorage and navigates on successful login', async () => {
|
|
||||||
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
|
||||||
const router = createTestRouter()
|
|
||||||
await router.push('/login')
|
await router.push('/login')
|
||||||
await router.isReady()
|
await router.isReady()
|
||||||
|
})
|
||||||
|
|
||||||
// Simulate submitForm logic
|
it('isNotEmpty validator reports empty value and accepts filled value', () => {
|
||||||
const username = 'admin'
|
const wrapper = mountLogin()
|
||||||
const password = '123456'
|
const callback = vi.fn()
|
||||||
const result = await login(username, password)
|
|
||||||
|
|
||||||
if (result.code === 200) {
|
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, '', callback)
|
||||||
localStorage.setItem('isLoggedIn', 'true')
|
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
||||||
ElMessage.success(result.message)
|
|
||||||
await router.push('/welcome')
|
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, 'admin', callback)
|
||||||
}
|
expect(callback).toHaveBeenCalledWith()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sets localStorage and navigates on successful login', async () => {
|
||||||
|
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
||||||
|
const wrapper = mountLogin()
|
||||||
|
wrapper.vm.registerData.username = 'admin'
|
||||||
|
wrapper.vm.registerData.password = '123456'
|
||||||
|
|
||||||
|
await wrapper.vm.submitForm(createForm(true))
|
||||||
|
|
||||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||||
@@ -90,23 +60,32 @@ describe('Login.vue logic', () => {
|
|||||||
|
|
||||||
it('shows error message on failed login', async () => {
|
it('shows error message on failed login', async () => {
|
||||||
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
||||||
|
const wrapper = mountLogin()
|
||||||
|
wrapper.vm.registerData.username = 'admin'
|
||||||
|
wrapper.vm.registerData.password = 'wrong'
|
||||||
|
|
||||||
const result = await login('admin', 'wrong')
|
await wrapper.vm.submitForm(createForm(true))
|
||||||
if (result.code !== 200) {
|
|
||||||
ElMessage.error(result.message)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||||
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('does not submit when already loading', async () => {
|
it('does not submit again while loading', async () => {
|
||||||
const loading = ref(true)
|
let resolveLogin!: (value: any) => void
|
||||||
// Simulate guard: if (!formEl || loading.value) return;
|
vi.mocked(login).mockImplementation(
|
||||||
if (loading.value) {
|
() => new Promise((resolve) => { resolveLogin = resolve }),
|
||||||
// Early return - no API call
|
)
|
||||||
}
|
const wrapper = mountLogin()
|
||||||
expect(login).not.toHaveBeenCalled()
|
|
||||||
})
|
const firstSubmit = wrapper.vm.submitForm(createForm(true))
|
||||||
|
const secondSubmit = wrapper.vm.submitForm(createForm(true))
|
||||||
|
await Promise.resolve()
|
||||||
|
|
||||||
|
expect(login).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
resolveLogin({ code: 200, message: '登录成功' })
|
||||||
|
await Promise.all([firstSubmit, secondSubmit])
|
||||||
|
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,106 +1,72 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
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', () => ({
|
vi.mock('@/api/login', () => ({
|
||||||
login: vi.fn(),
|
login: vi.fn(),
|
||||||
logout: vi.fn().mockResolvedValue({ code: 200 }),
|
logout: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
vi.mock('element-plus', () => ({
|
async function mountAt(path: string) {
|
||||||
ElMessage: {
|
await router.push(path)
|
||||||
success: vi.fn(),
|
await router.isReady()
|
||||||
error: vi.fn(),
|
return mount(MyHead, {
|
||||||
warning: vi.fn(),
|
shallow: true,
|
||||||
info: vi.fn(),
|
global: {
|
||||||
|
plugins: [ElementPlus, router],
|
||||||
},
|
},
|
||||||
}))
|
})
|
||||||
|
}
|
||||||
|
|
||||||
import { logout } from '@/api/login'
|
describe('MyHead.vue', () => {
|
||||||
import { ElMessage } from 'element-plus'
|
beforeEach(async () => {
|
||||||
|
|
||||||
describe('MyHead.vue logic', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
localStorage.clear()
|
localStorage.clear()
|
||||||
|
await router.push('/login')
|
||||||
|
await router.isReady()
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('route-based computed properties', () => {
|
it('derives route-based computed properties from real route', async () => {
|
||||||
it('isLoginRoute is true when path is /login', () => {
|
const loginWrapper = await mountAt('/login')
|
||||||
const routePath = ref('/login')
|
expect(loginWrapper.vm.isLoginRoute).toBe(true)
|
||||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
expect(loginWrapper.vm.showBackButton).toBe(false)
|
||||||
expect(isLoginRoute.value).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('isLoginRoute is false for other paths', () => {
|
|
||||||
const routePath = ref('/welcome')
|
|
||||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
|
||||||
expect(isLoginRoute.value).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('showBackButton is true for non-login, non-welcome routes', () => {
|
|
||||||
const routePath = ref('/study')
|
|
||||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
|
||||||
expect(showBackButton.value).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('showBackButton is false on welcome route', () => {
|
|
||||||
const routePath = ref('/welcome')
|
|
||||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
|
||||||
expect(showBackButton.value).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('showBackButton is false on login route', () => {
|
|
||||||
const routePath = ref('/login')
|
|
||||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
|
||||||
expect(showBackButton.value).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('pageTitle is derived from route meta', () => {
|
|
||||||
const meta = { title: '学习任务' }
|
|
||||||
const pageTitle = computed(() => meta?.title as string | undefined)
|
|
||||||
expect(pageTitle.value).toBe('学习任务')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('pageTitle is undefined when no meta title', () => {
|
|
||||||
const meta = {}
|
|
||||||
const pageTitle = computed(() => meta?.title as string | undefined)
|
|
||||||
expect(pageTitle.value).toBeUndefined()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('handleLogout logic', () => {
|
|
||||||
it('clears login state and navigates to login', async () => {
|
|
||||||
localStorage.setItem('isLoggedIn', 'true')
|
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('学习任务')
|
||||||
|
|
||||||
// Simulate handleLogout
|
const welcomeWrapper = await mountAt('/welcome')
|
||||||
try {
|
expect(welcomeWrapper.vm.showBackButton).toBe(false)
|
||||||
await logout()
|
expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
|
||||||
} catch {
|
})
|
||||||
// Backend failure shouldn't block logout
|
|
||||||
} finally {
|
it('clears login state and navigates to login on logout', async () => {
|
||||||
localStorage.removeItem('isLoggedIn')
|
vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
|
||||||
ElMessage.success('已退出登录')
|
localStorage.setItem('isLoggedIn', 'true')
|
||||||
}
|
const wrapper = await mountAt('/study')
|
||||||
|
|
||||||
|
await wrapper.vm.handleLogout()
|
||||||
|
|
||||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||||
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('clears login state even when API call fails', async () => {
|
it('clears login state even when logout API fails', async () => {
|
||||||
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
||||||
localStorage.setItem('isLoggedIn', 'true')
|
localStorage.setItem('isLoggedIn', 'true')
|
||||||
|
const wrapper = await mountAt('/study')
|
||||||
|
|
||||||
try {
|
await wrapper.vm.handleLogout()
|
||||||
await logout()
|
|
||||||
} catch {
|
|
||||||
// Expected
|
|
||||||
} finally {
|
|
||||||
localStorage.removeItem('isLoggedIn')
|
|
||||||
ElMessage.success('已退出登录')
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||||
})
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,276 +1,209 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
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,
|
||||||
|
getExpectation,
|
||||||
|
getSessionDetail,
|
||||||
|
pauseSession,
|
||||||
|
startOrContinueStudySession,
|
||||||
|
} from '@/api/studySessions'
|
||||||
|
import { getFragmentsBySession } from '@/api/reportFragments'
|
||||||
|
|
||||||
// Mock API
|
|
||||||
vi.mock('@/api/studySessions', () => ({
|
vi.mock('@/api/studySessions', () => ({
|
||||||
continueSession: vi.fn(),
|
continueSession: vi.fn(),
|
||||||
pauseSession: vi.fn(),
|
|
||||||
endSession: vi.fn(),
|
endSession: vi.fn(),
|
||||||
startOrContinueStudySession: vi.fn(),
|
getExpectation: vi.fn(),
|
||||||
|
getReportDraft: vi.fn(),
|
||||||
getSessionDetail: vi.fn(),
|
getSessionDetail: vi.fn(),
|
||||||
|
getTaskFragments: vi.fn(),
|
||||||
|
getTaskReports: vi.fn(),
|
||||||
|
pauseSession: vi.fn(),
|
||||||
|
startOrContinueStudySession: vi.fn(),
|
||||||
|
upsertExpectation: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
vi.mock('@/api/reportFragments', () => ({
|
vi.mock('@/api/reportFragments', () => ({
|
||||||
|
createFragments: vi.fn(),
|
||||||
getFragmentsBySession: vi.fn(),
|
getFragmentsBySession: vi.fn(),
|
||||||
updateFragments: vi.fn(),
|
updateFragments: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
import {
|
const defaultSessionData = {
|
||||||
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',
|
sessionNum: 'SESSION_001',
|
||||||
sessionState: 'ONGOING' as string,
|
sessionState: 'PAUSED',
|
||||||
taskName: '测试任务',
|
taskName: '测试任务',
|
||||||
taskNum: 'T001',
|
taskNum: 'T001',
|
||||||
|
taskId: 1,
|
||||||
startTime: '',
|
startTime: '',
|
||||||
endTime: '',
|
endTime: '',
|
||||||
lastStartTime: '',
|
lastStartTime: '',
|
||||||
actualTime: 0,
|
actualTime: 0,
|
||||||
effectiveTime: 0,
|
effectiveTime: 0,
|
||||||
effectivenessRatio: '--',
|
effectivenessRatio: '--',
|
||||||
pointerPosition: 1500000,
|
pointerPosition: 1_500_000,
|
||||||
systemMessage: '',
|
systemMessage: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountTask() {
|
||||||
|
localStorage.setItem('isLoggedIn', 'true')
|
||||||
|
const testRouter = createRouter({
|
||||||
|
history: createMemoryHistory(),
|
||||||
|
routes: [
|
||||||
|
{
|
||||||
|
path: '/start-task/:taskNum',
|
||||||
|
component: StartTask,
|
||||||
|
meta: { requiresAuth: true, title: '学习会话' },
|
||||||
|
},
|
||||||
|
],
|
||||||
})
|
})
|
||||||
|
await testRouter.push('/start-task/T001')
|
||||||
const timerRunning = ref(true)
|
await testRouter.isReady()
|
||||||
|
const wrapper = mount(StartTask, {
|
||||||
const clear = () => {
|
shallow: true,
|
||||||
timerRunning.value = false
|
global: {
|
||||||
|
plugins: [ElementPlus, testRouter],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
return wrapper
|
||||||
}
|
}
|
||||||
|
|
||||||
const runCountdown = (duration: number) => {
|
describe('StartTask.vue', () => {
|
||||||
timerRunning.value = true
|
beforeEach(async () => {
|
||||||
}
|
|
||||||
|
|
||||||
// 从 StartTask.vue 提取的 stopTimer 逻辑
|
|
||||||
const stopTimer = async () => {
|
|
||||||
const res = await pauseSession(taskInfo.sessionNum)
|
|
||||||
if (res.code === 200) {
|
|
||||||
taskInfo.sessionState = 'PAUSED'
|
|
||||||
}
|
|
||||||
clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 从 StartTask.vue 提取的 startTimer 逻辑
|
|
||||||
const startTimer = async () => {
|
|
||||||
if (taskInfo.sessionState === 'PAUSED') {
|
|
||||||
const res = await continueSession(taskInfo.sessionNum)
|
|
||||||
if (res.code === 200) {
|
|
||||||
// ElMessage.success("任务继续")
|
|
||||||
}
|
|
||||||
// loadTaskSession 模拟
|
|
||||||
const sessionRes = await startOrContinueStudySession(taskInfo.taskNum)
|
|
||||||
Object.assign(taskInfo, sessionRes.data)
|
|
||||||
}
|
|
||||||
const duration = taskInfo.pointerPosition || 25 * 60 * 1000
|
|
||||||
runCountdown(duration)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 从 StartTask.vue 提取的 endTimer 逻辑(简化版,跳过 confirm)
|
|
||||||
const endTimer = async (content: string) => {
|
|
||||||
if (!content) return
|
|
||||||
const res = await endSession(taskInfo.sessionNum, content)
|
|
||||||
if (res.code === 200) {
|
|
||||||
if (res.message && res.message !== '请求成功') {
|
|
||||||
// ElMessage.warning(res.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
return { taskInfo, timerRunning, stopTimer, startTimer, endTimer, clear }
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('StartTask.vue 暂停/继续逻辑', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
localStorage.clear()
|
||||||
|
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('stopTimer pauses real session state and refreshes from detail API', async () => {
|
||||||
it('调用 pauseSession API', async () => {
|
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
vi.mocked(getSessionDetail).mockResolvedValue({
|
||||||
const { stopTimer } = createSessionSimulator()
|
|
||||||
|
|
||||||
await stopTimer()
|
|
||||||
|
|
||||||
expect(mockedPauseSession).toHaveBeenCalledWith('SESSION_001')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('暂停成功后 sessionState 应更新为 PAUSED', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
const { taskInfo, stopTimer } = createSessionSimulator()
|
|
||||||
|
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
|
||||||
await stopTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('暂停后 timerRunning 应为 false', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
const { timerRunning, stopTimer } = createSessionSimulator()
|
|
||||||
|
|
||||||
expect(timerRunning.value).toBe(true)
|
|
||||||
await stopTimer()
|
|
||||||
expect(timerRunning.value).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('startTimer - 继续', () => {
|
|
||||||
it('PAUSED 状态下点击开始,应调用 continueSession API', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: {
|
||||||
sessionNum: 'SESSION_001',
|
sessionState: 'PAUSED',
|
||||||
sessionState: 'ONGOING',
|
actualTime: 10,
|
||||||
pointerPosition: 1500000,
|
effectiveTime: 20,
|
||||||
|
effectivenessRatio: 0.8,
|
||||||
|
pointerPosition: 1_200_000,
|
||||||
},
|
},
|
||||||
} as any)
|
} as any)
|
||||||
|
const wrapper = await mountTask()
|
||||||
|
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||||
|
wrapper.vm.timerRunning = true
|
||||||
|
|
||||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
await wrapper.vm.stopTimer()
|
||||||
|
|
||||||
// 先暂停
|
expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||||
await stopTimer()
|
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
expect(wrapper.vm.taskInfo.actualTime).toBe(10)
|
||||||
|
expect(wrapper.vm.taskInfo.effectiveTime).toBe(20)
|
||||||
// 再开始
|
expect(wrapper.vm.timerRunning).toBe(false)
|
||||||
await startTimer()
|
wrapper.unmount()
|
||||||
|
|
||||||
expect(mockedContinueSession).toHaveBeenCalledWith('SESSION_001')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('PAUSED 状态下点击开始,应调用 loadTaskSession 刷新数据', async () => {
|
it('startTimer continues a paused session and reloads session data', async () => {
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
vi.mocked(startOrContinueStudySession).mockResolvedValue({
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
|
||||||
sessionNum: 'SESSION_001',
|
|
||||||
sessionState: 'ONGOING',
|
|
||||||
pointerPosition: 1200000,
|
|
||||||
},
|
|
||||||
} as any)
|
} 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(continueSession).toHaveBeenCalledWith('SESSION_001')
|
||||||
await startTimer()
|
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
|
||||||
|
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||||
expect(mockedStartOrContinue).toHaveBeenCalledWith('T001')
|
expect(wrapper.vm.timerRunning).toBe(true)
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('ONGOING 状态下点击开始,不应调用 continueSession API', async () => {
|
it('startTimer does not call continue API when session is already ongoing', async () => {
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
const wrapper = await mountTask()
|
||||||
code: 200,
|
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
|
||||||
} as any)
|
|
||||||
|
|
||||||
const { taskInfo, startTimer } = createSessionSimulator()
|
await wrapper.vm.startTimer()
|
||||||
|
|
||||||
// 直接在 ONGOING 状态调用 startTimer
|
expect(continueSession).not.toHaveBeenCalled()
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
expect(wrapper.vm.timerRunning).toBe(true)
|
||||||
await startTimer()
|
wrapper.unmount()
|
||||||
|
|
||||||
expect(mockedContinueSession).not.toHaveBeenCalled()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('开始后 timerRunning 应为 true', async () => {
|
it('endTimer refuses empty content without calling API', async () => {
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
const wrapper = await mountTask()
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
|
||||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
|
||||||
} as any)
|
|
||||||
|
|
||||||
const { timerRunning, stopTimer, startTimer } = createSessionSimulator()
|
await wrapper.vm.endTimer('')
|
||||||
|
|
||||||
await stopTimer()
|
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
|
||||||
expect(timerRunning.value).toBe(false)
|
expect(endSession).not.toHaveBeenCalled()
|
||||||
|
wrapper.unmount()
|
||||||
await startTimer()
|
|
||||||
expect(timerRunning.value).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('endTimer - 结束会话', () => {
|
it('endTimer ends session and navigates to study page', async () => {
|
||||||
it('调用 endSession API 并传递 content', async () => {
|
vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
const wrapper = await mountTask()
|
||||||
const { endTimer } = createSessionSimulator()
|
|
||||||
|
|
||||||
await endTimer('学习总结内容')
|
await wrapper.vm.endTimer('学习总结内容')
|
||||||
|
|
||||||
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
expect(endSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
||||||
|
expect(ElMessage.success).toHaveBeenCalledWith('任务结束')
|
||||||
|
expect(localStorage.getItem('activeSession')).toBeNull()
|
||||||
|
expect(router.currentRoute.value.path).toBe('/study')
|
||||||
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('后端返回 warning 消息时,message 应包含提示信息', async () => {
|
it('endTimer shows warning message returned by backend', async () => {
|
||||||
mockedEndSession.mockResolvedValue({
|
vi.mocked(endSession).mockResolvedValue({
|
||||||
code: 200,
|
code: 200,
|
||||||
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
||||||
} as any)
|
} as any)
|
||||||
|
const wrapper = await mountTask()
|
||||||
|
|
||||||
const { endTimer } = createSessionSimulator()
|
await wrapper.vm.endTimer('学习总结内容')
|
||||||
const res = await endSession('SESSION_001', '内容')
|
|
||||||
|
|
||||||
expect(res.message).toBe('本次有效学习时间不足10分钟,不计入总学习时间')
|
expect(ElMessage.warning).toHaveBeenCalledWith('本次有效学习时间不足10分钟,不计入总学习时间')
|
||||||
expect(res.message).not.toBe('请求成功')
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('content 为空时不调用 API', async () => {
|
it('supports a full pause -> continue -> pause flow', async () => {
|
||||||
const { endTimer } = createSessionSimulator()
|
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
|
vi.mocked(getSessionDetail).mockResolvedValue({
|
||||||
await endTimer('')
|
|
||||||
|
|
||||||
expect(mockedEndSession).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('完整暂停→继续→暂停流程', () => {
|
|
||||||
it('多次暂停/继续应正确更新状态和调用 API', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
code: 200,
|
||||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
data: { sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20 },
|
||||||
} as any)
|
} 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()
|
||||||
|
|
||||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
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(taskInfo.sessionState).toBe('ONGOING')
|
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||||
|
expect(continueSession).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
// 第一次暂停
|
await wrapper.vm.stopTimer()
|
||||||
await stopTimer()
|
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
expect(pauseSession).toHaveBeenCalledTimes(2)
|
||||||
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
|
wrapper.unmount()
|
||||||
|
|
||||||
// 继续
|
|
||||||
await startTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
|
||||||
expect(mockedContinueSession).toHaveBeenCalledTimes(1)
|
|
||||||
|
|
||||||
// 第二次暂停
|
|
||||||
await stopTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
|
||||||
expect(mockedPauseSession).toHaveBeenCalledTimes(2)
|
|
||||||
|
|
||||||
// 再次继续
|
|
||||||
await startTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
|
||||||
expect(mockedContinueSession).toHaveBeenCalledTimes(2)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,126 +1,104 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
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', () => ({
|
vi.mock('@/utils/request', () => ({
|
||||||
ElMessage: {
|
default: {
|
||||||
success: vi.fn(),
|
get: vi.fn(),
|
||||||
error: vi.fn(),
|
post: vi.fn(),
|
||||||
warning: vi.fn(),
|
put: vi.fn(),
|
||||||
info: 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', () => {
|
vi.mock('@/utils/fetchTitle', () => ({
|
||||||
beforeEach(() => {
|
getUrlTitle: vi.fn().mockResolvedValue(''),
|
||||||
vi.clearAllMocks()
|
}))
|
||||||
})
|
|
||||||
|
|
||||||
describe('priorityOptions', () => {
|
vi.mock('@/utils/markdown', () => ({
|
||||||
it('contains values 0-5', () => {
|
renderMarkdown: vi.fn(() => '<p>preview</p>'),
|
||||||
const priorityOptions = [0, 1, 2, 3, 4, 5]
|
}))
|
||||||
expect(priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
|
|
||||||
expect(priorityOptions.length).toBe(6)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('priority state management', () => {
|
async function mountAt(path: string) {
|
||||||
it('initializes with all zeros', () => {
|
localStorage.setItem('isLoggedIn', 'true')
|
||||||
const priority = reactive({
|
await router.push(path)
|
||||||
urgency: 0,
|
await router.isReady()
|
||||||
importance: 0,
|
return mount(TaskForm, {
|
||||||
contentDifficulty: 0,
|
shallow: true,
|
||||||
futureValue: 0,
|
global: {
|
||||||
subjectivePriority: 0,
|
plugins: [ElementPlus, router],
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(priority.urgency).toBe(0)
|
|
||||||
expect(priority.importance).toBe(0)
|
|
||||||
expect(priority.contentDifficulty).toBe(0)
|
|
||||||
expect(priority.futureValue).toBe(0)
|
|
||||||
expect(priority.subjectivePriority).toBe(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('updates individual priority fields', () => {
|
|
||||||
const priority = reactive({
|
|
||||||
urgency: 0,
|
|
||||||
importance: 0,
|
|
||||||
contentDifficulty: 0,
|
|
||||||
futureValue: 0,
|
|
||||||
subjectivePriority: 0,
|
|
||||||
})
|
|
||||||
|
|
||||||
priority.urgency = 3
|
|
||||||
priority.importance = 5
|
|
||||||
|
|
||||||
expect(priority.urgency).toBe(3)
|
|
||||||
expect(priority.importance).toBe(5)
|
|
||||||
expect(priority.contentDifficulty).toBe(0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('task payload construction', () => {
|
|
||||||
it('builds correct create payload', () => {
|
|
||||||
const taskName = ref('学习递归')
|
|
||||||
const taskDescription = ref('理解递归的基本概念')
|
|
||||||
const materialURL = ref('https://example.com/recursion')
|
|
||||||
const priority = reactive({
|
|
||||||
urgency: 3,
|
|
||||||
importance: 4,
|
|
||||||
contentDifficulty: 2,
|
|
||||||
futureValue: 5,
|
|
||||||
subjectivePriority: 3,
|
|
||||||
})
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
taskName: taskName.value,
|
|
||||||
taskDescription: taskDescription.value,
|
|
||||||
materialURL: materialURL.value,
|
|
||||||
...priority,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
expect(payload).toEqual({
|
describe('TaskForm.vue', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
localStorage.clear()
|
||||||
|
vi.mocked(getTaskApplications).mockResolvedValue({ code: 200, data: [] })
|
||||||
|
await router.push('/login')
|
||||||
|
await router.isReady()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses real priority options and initial state', async () => {
|
||||||
|
const wrapper = await mountAt('/add-task')
|
||||||
|
|
||||||
|
expect(wrapper.vm.priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
|
||||||
|
expect(wrapper.vm.priority).toEqual({
|
||||||
|
urgency: 0,
|
||||||
|
importance: 0,
|
||||||
|
contentDifficulty: 0,
|
||||||
|
futureValue: 0,
|
||||||
|
subjectivePriority: 0,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('builds create payload from real form state and navigates to study', async () => {
|
||||||
|
vi.mocked(request.post).mockResolvedValue({ code: 200, message: '创建任务成功' })
|
||||||
|
const wrapper = await mountAt('/add-task')
|
||||||
|
wrapper.vm.taskName = '学习递归'
|
||||||
|
wrapper.vm.taskDescription = '理解递归的基本概念'
|
||||||
|
wrapper.vm.materialUrl = 'https://example.com/recursion'
|
||||||
|
wrapper.vm.priority.urgency = 3
|
||||||
|
wrapper.vm.priority.importance = 4
|
||||||
|
wrapper.vm.priority.contentDifficulty = 2
|
||||||
|
wrapper.vm.priority.futureValue = 5
|
||||||
|
wrapper.vm.priority.subjectivePriority = 3
|
||||||
|
|
||||||
|
wrapper.vm.createTask()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(request.post).toHaveBeenCalledWith('/tasks', {
|
||||||
taskName: '学习递归',
|
taskName: '学习递归',
|
||||||
taskDescription: '理解递归的基本概念',
|
taskDescription: '理解递归的基本概念',
|
||||||
materialURL: 'https://example.com/recursion',
|
materialUrl: 'https://example.com/recursion',
|
||||||
urgency: 3,
|
urgency: 3,
|
||||||
importance: 4,
|
importance: 4,
|
||||||
contentDifficulty: 2,
|
contentDifficulty: 2,
|
||||||
futureValue: 5,
|
futureValue: 5,
|
||||||
subjectivePriority: 3,
|
subjectivePriority: 3,
|
||||||
})
|
})
|
||||||
|
expect(ElMessage.success).toHaveBeenCalledWith('创建任务成功')
|
||||||
|
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('builds correct update payload with id', () => {
|
it('loads update data from real API and maps it into form state', async () => {
|
||||||
const taskId = 42
|
vi.mocked(request.get).mockResolvedValue({
|
||||||
const taskName = ref('更新后的任务')
|
code: 200,
|
||||||
const taskDescription = ref('')
|
data: {
|
||||||
const materialURL = ref('')
|
taskNum: 'T001',
|
||||||
const priority = reactive({
|
|
||||||
urgency: 1,
|
|
||||||
importance: 2,
|
|
||||||
contentDifficulty: 0,
|
|
||||||
futureValue: 3,
|
|
||||||
subjectivePriority: 4,
|
|
||||||
})
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
id: taskId,
|
|
||||||
taskName: taskName.value,
|
|
||||||
taskDescription: taskDescription.value,
|
|
||||||
materialURL: materialURL.value,
|
|
||||||
...priority,
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(payload.id).toBe(42)
|
|
||||||
expect(payload.taskName).toBe('更新后的任务')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('loadTask data mapping', () => {
|
|
||||||
it('maps API response to form fields correctly', () => {
|
|
||||||
const apiData = {
|
|
||||||
taskName: '学习DP',
|
taskName: '学习DP',
|
||||||
taskDescription: '动态规划',
|
taskDescription: '动态规划',
|
||||||
materialUrl: 'https://example.com/dp',
|
materialUrl: 'https://example.com/dp',
|
||||||
@@ -129,52 +107,54 @@ describe('TaskForm.vue logic', () => {
|
|||||||
contentDifficulty: 3,
|
contentDifficulty: 3,
|
||||||
futureValue: 4,
|
futureValue: 4,
|
||||||
subjectivePriority: 2,
|
subjectivePriority: 2,
|
||||||
}
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const taskName = ref('')
|
const wrapper = await mountAt('/update-task/42')
|
||||||
const taskDescription = ref('')
|
await flushPromises()
|
||||||
const materialURL = ref('')
|
|
||||||
const priority = reactive({
|
expect(wrapper.vm.isUpdateMode).toBe(true)
|
||||||
urgency: 0,
|
expect(wrapper.vm.taskNum).toBe('T001')
|
||||||
importance: 0,
|
expect(wrapper.vm.taskName).toBe('学习DP')
|
||||||
|
expect(wrapper.vm.taskDescription).toBe('动态规划')
|
||||||
|
expect(wrapper.vm.materialUrl).toBe('https://example.com/dp')
|
||||||
|
expect(wrapper.vm.priority).toEqual({
|
||||||
|
urgency: 4,
|
||||||
|
importance: 5,
|
||||||
|
contentDifficulty: 3,
|
||||||
|
futureValue: 4,
|
||||||
|
subjectivePriority: 2,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('builds update payload with id and navigates to study', async () => {
|
||||||
|
vi.mocked(request.get).mockResolvedValue({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
taskNum: 'T001',
|
||||||
|
taskName: '学习DP',
|
||||||
|
taskDescription: '动态规划',
|
||||||
|
materialUrl: '',
|
||||||
|
urgency: 1,
|
||||||
|
importance: 2,
|
||||||
contentDifficulty: 0,
|
contentDifficulty: 0,
|
||||||
futureValue: 0,
|
futureValue: 3,
|
||||||
subjectivePriority: 0,
|
subjectivePriority: 4,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
vi.mocked(request.put).mockResolvedValue({ code: 200, message: '更新任务成功' })
|
||||||
|
|
||||||
// Simulate loadTask mapping
|
const wrapper = await mountAt('/update-task/42')
|
||||||
taskName.value = apiData.taskName
|
await flushPromises()
|
||||||
taskDescription.value = apiData.taskDescription
|
wrapper.vm.taskName = '更新后的任务'
|
||||||
materialURL.value = apiData.materialURL || apiData.materialUrl || ''
|
wrapper.vm.updateTask()
|
||||||
priority.urgency = apiData.urgency
|
await flushPromises()
|
||||||
priority.importance = apiData.importance
|
|
||||||
priority.contentDifficulty = apiData.contentDifficulty
|
|
||||||
priority.futureValue = apiData.futureValue
|
|
||||||
priority.subjectivePriority = apiData.subjectivePriority
|
|
||||||
|
|
||||||
expect(taskName.value).toBe('学习DP')
|
expect(request.put).toHaveBeenCalledWith('/tasks/42', expect.objectContaining({
|
||||||
expect(materialURL.value).toBe('https://example.com/dp')
|
id: 42,
|
||||||
expect(priority.urgency).toBe(4)
|
taskName: '更新后的任务',
|
||||||
expect(priority.importance).toBe(5)
|
}))
|
||||||
})
|
expect(ElMessage.success).toHaveBeenCalledWith('更新任务成功')
|
||||||
|
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
|
||||||
it('handles materialURL with camelCase variant', () => {
|
|
||||||
const apiData = { materialURL: 'https://example.com/a', materialUrl: 'https://example.com/b' }
|
|
||||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
|
||||||
expect(result).toBe('https://example.com/a')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('falls back to empty string when no material URL', () => {
|
|
||||||
const apiData = {} as any
|
|
||||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
|
||||||
expect(result).toBe('')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('redirect after successful action', () => {
|
|
||||||
it('navigates to study page after create/update', () => {
|
|
||||||
const pushTarget = '/study'
|
|
||||||
expect(pushTarget).toBe('/study')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,155 +1,91 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
import { ref } from 'vue'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { createFragments } from '@/api/reportFragments'
|
||||||
const mockInfo = vi.fn()
|
import { useStudyFragment } from '@/components/composables/fragment'
|
||||||
const mockSuccess = vi.fn()
|
|
||||||
const mockError = vi.fn()
|
|
||||||
const mockWarning = vi.fn()
|
|
||||||
const mockConfirm = vi.fn()
|
|
||||||
|
|
||||||
vi.mock('element-plus', () => ({
|
|
||||||
ElMessage: {
|
|
||||||
success: mockSuccess,
|
|
||||||
error: mockError,
|
|
||||||
warning: mockWarning,
|
|
||||||
info: mockInfo,
|
|
||||||
},
|
|
||||||
ElMessageBox: {
|
|
||||||
confirm: (...args: any[]) => mockConfirm(...args),
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
vi.mock('@/api/reportFragments', () => ({
|
vi.mock('@/api/reportFragments', () => ({
|
||||||
createFragments: vi.fn(),
|
createFragments: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
import { createFragments } from '@/api/reportFragments'
|
describe('useStudyFragment', () => {
|
||||||
|
|
||||||
describe('useStudyFragment composable logic', () => {
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
mockConfirm.mockResolvedValue('confirm')
|
vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('openFragmentDialog resets content and shows dialog', () => {
|
it('openFragmentDialog resets content and shows dialog', () => {
|
||||||
const fragmentContent = ref('old content')
|
const { fragmentsDialogVisible, fragmentContent, openFragmentDialog } = useStudyFragment()
|
||||||
const fragmentsDialogVisible = ref(false)
|
fragmentContent.value = 'old content'
|
||||||
|
|
||||||
fragmentContent.value = ''
|
openFragmentDialog()
|
||||||
fragmentsDialogVisible.value = true
|
|
||||||
|
|
||||||
expect(fragmentContent.value).toBe('')
|
expect(fragmentContent.value).toBe('')
|
||||||
expect(fragmentsDialogVisible.value).toBe(true)
|
expect(fragmentsDialogVisible.value).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('closeFragmentDialog hides dialog on confirm', async () => {
|
it('closeFragmentDialog hides dialog after confirm', async () => {
|
||||||
const fragmentsDialogVisible = ref(true)
|
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
|
||||||
|
fragmentsDialogVisible.value = true
|
||||||
|
|
||||||
await mockConfirm('确定取消生成吗?', '提示', {
|
await closeFragmentDialog()
|
||||||
confirmButtonText: '确定',
|
|
||||||
cancelButtonText: '取消',
|
|
||||||
type: 'warning',
|
|
||||||
}).then(() => {
|
|
||||||
fragmentsDialogVisible.value = false
|
|
||||||
mockInfo('已取消生成')
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(fragmentsDialogVisible.value).toBe(false)
|
expect(fragmentsDialogVisible.value).toBe(false)
|
||||||
expect(mockInfo).toHaveBeenCalledWith('已取消生成')
|
expect(ElMessage.info).toHaveBeenCalledWith('已取消生成')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('closeFragmentDialog keeps dialog open on cancel', async () => {
|
it('closeFragmentDialog keeps dialog open when user cancels', async () => {
|
||||||
const fragmentsDialogVisible = ref(true)
|
vi.mocked(ElMessageBox.confirm).mockRejectedValue('cancel')
|
||||||
mockConfirm.mockRejectedValue('cancel')
|
const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
|
||||||
|
fragmentsDialogVisible.value = true
|
||||||
|
|
||||||
try {
|
await closeFragmentDialog()
|
||||||
await mockConfirm('确定取消生成吗?', '提示', {
|
|
||||||
confirmButtonText: '确定',
|
|
||||||
cancelButtonText: '取消',
|
|
||||||
type: 'warning',
|
|
||||||
}).then(() => {
|
|
||||||
fragmentsDialogVisible.value = false
|
|
||||||
})
|
|
||||||
} catch {
|
|
||||||
// User cancelled
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(fragmentsDialogVisible.value).toBe(true)
|
expect(fragmentsDialogVisible.value).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('confirmGenerateFragment warns if content is empty', async () => {
|
it('confirmGenerateFragment warns when content is empty', async () => {
|
||||||
const fragmentContent = ref(' ')
|
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||||
|
fragmentContent.value = ' '
|
||||||
|
|
||||||
if (!fragmentContent.value.trim()) {
|
const result = await confirmGenerateFragment('S001')
|
||||||
mockWarning('请输入学习内容!')
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(mockWarning).toHaveBeenCalledWith('请输入学习内容!')
|
expect(result).toBe(false)
|
||||||
|
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习内容!')
|
||||||
expect(createFragments).not.toHaveBeenCalled()
|
expect(createFragments).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('confirmGenerateFragment calls API and shows success', async () => {
|
it('confirmGenerateFragment calls API and shows success', async () => {
|
||||||
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
|
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
|
||||||
const fragmentContent = ref('学习了递归算法')
|
const { fragmentContent, fragmentsDialogVisible, confirmGenerateFragment } = useStudyFragment()
|
||||||
const fragmentsDialogVisible = ref(true)
|
fragmentContent.value = '学习了递归算法'
|
||||||
|
|
||||||
if (fragmentContent.value.trim()) {
|
const result = await confirmGenerateFragment('S001')
|
||||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
|
||||||
confirmButtonText: '确定',
|
|
||||||
cancelButtonText: '取消',
|
|
||||||
type: 'info',
|
|
||||||
}).then(async () => {
|
|
||||||
const res = await createFragments('S001', fragmentContent.value)
|
|
||||||
if (res.code === 200) {
|
|
||||||
mockSuccess('学习残片生成成功!')
|
|
||||||
fragmentsDialogVisible.value = false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
expect(result).toBe(true)
|
||||||
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
|
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
|
||||||
expect(mockSuccess).toHaveBeenCalledWith('学习残片生成成功!')
|
expect(ElMessage.success).toHaveBeenCalledWith('学习残片生成成功!')
|
||||||
expect(fragmentsDialogVisible.value).toBe(false)
|
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)
|
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
|
||||||
const fragmentContent = ref('学习内容')
|
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||||
|
fragmentContent.value = '学习内容'
|
||||||
|
|
||||||
if (fragmentContent.value.trim()) {
|
const result = await confirmGenerateFragment('S001')
|
||||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
|
||||||
confirmButtonText: '确定',
|
|
||||||
cancelButtonText: '取消',
|
|
||||||
type: 'info',
|
|
||||||
}).then(async () => {
|
|
||||||
const res = await createFragments('S001', fragmentContent.value)
|
|
||||||
if (res.code !== 200) {
|
|
||||||
mockError(res.message || '生成学习残片失败')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(mockError).toHaveBeenCalledWith('生成失败')
|
expect(result).toBe(false)
|
||||||
|
expect(ElMessage.error).toHaveBeenCalledWith('生成失败')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('confirmGenerateFragment handles network error', async () => {
|
it('confirmGenerateFragment handles network error', async () => {
|
||||||
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
|
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
|
||||||
const fragmentContent = ref('学习内容')
|
const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
|
||||||
|
fragmentContent.value = '学习内容'
|
||||||
|
|
||||||
if (fragmentContent.value.trim()) {
|
const result = await confirmGenerateFragment('S001')
|
||||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
|
||||||
confirmButtonText: '确定',
|
|
||||||
cancelButtonText: '取消',
|
|
||||||
type: 'info',
|
|
||||||
}).then(async () => {
|
|
||||||
try {
|
|
||||||
await createFragments('S001', fragmentContent.value)
|
|
||||||
} catch (error: any) {
|
|
||||||
mockError(error.message || '请求失败')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(mockError).toHaveBeenCalledWith('网络超时')
|
expect(result).toBe(false)
|
||||||
|
expect(ElMessage.error).toHaveBeenCalledWith('网络超时')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,88 +1,56 @@
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { ElMessageBox } from 'element-plus'
|
||||||
// We test the timer composable logic directly since it's a pure Vue composable
|
import { useTimer } from '@/components/composables/useTimer'
|
||||||
// Extract the logic to test it in isolation
|
|
||||||
|
|
||||||
describe('useTimer', () => {
|
describe('useTimer', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.useFakeTimers()
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
|
||||||
|
vi.clearAllMocks()
|
||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.useRealTimers()
|
vi.useRealTimers()
|
||||||
})
|
})
|
||||||
|
|
||||||
// Test the core timer logic that the composable uses
|
it('syncDisplay writes formatted remaining time', () => {
|
||||||
it('formatTime converts seconds to HH:MM:SS', () => {
|
const { timerMinutes, timerSeconds, timerIsOver, syncDisplay } = useTimer()
|
||||||
const formatTime = (totalSeconds: number): string => {
|
|
||||||
const hours = Math.floor(totalSeconds / 3600)
|
|
||||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
|
||||||
const seconds = totalSeconds % 60
|
|
||||||
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(formatTime(0)).toBe('00:00:00')
|
syncDisplay(61_000)
|
||||||
expect(formatTime(61)).toBe('00:01:01')
|
expect(timerMinutes.value).toBe(1)
|
||||||
expect(formatTime(3661)).toBe('01:01:01')
|
expect(timerSeconds.value).toBe(1)
|
||||||
expect(formatTime(59)).toBe('00:00:59')
|
expect(timerIsOver.value).toBe(false)
|
||||||
expect(formatTime(3600)).toBe('01:00:00')
|
|
||||||
|
syncDisplay(0)
|
||||||
|
expect(timerMinutes.value).toBe(0)
|
||||||
|
expect(timerSeconds.value).toBe(0)
|
||||||
|
expect(timerIsOver.value).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('formatTime handles large values', () => {
|
it('runCountdown decreases remaining time and stops at zero', () => {
|
||||||
const formatTime = (totalSeconds: number): string => {
|
const { timerMinutes, timerSeconds, timerRunning, timerIsOver, runCountdown, clear } = useTimer()
|
||||||
const hours = Math.floor(totalSeconds / 3600)
|
|
||||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
|
||||||
const seconds = totalSeconds % 60
|
|
||||||
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(formatTime(86399)).toBe('23:59:59')
|
runCountdown(3000)
|
||||||
expect(formatTime(100000)).toBe('27:46:40')
|
vi.advanceTimersByTime(1000)
|
||||||
})
|
expect(timerMinutes.value).toBe(0)
|
||||||
|
expect(timerSeconds.value).toBe(2)
|
||||||
it('timer increments elapsedSeconds over time', () => {
|
expect(timerRunning.value).toBe(true)
|
||||||
let elapsed = 0
|
|
||||||
const interval = setInterval(() => {
|
|
||||||
elapsed++
|
|
||||||
}, 1000)
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(3000)
|
|
||||||
expect(elapsed).toBe(3)
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(2000)
|
vi.advanceTimersByTime(2000)
|
||||||
expect(elapsed).toBe(5)
|
expect(timerSeconds.value).toBe(0)
|
||||||
|
expect(timerRunning.value).toBe(false)
|
||||||
|
expect(timerIsOver.value).toBe(true)
|
||||||
|
|
||||||
clearInterval(interval)
|
clear()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('timer can be paused and resumed', () => {
|
it('notifies when countdown completes', () => {
|
||||||
let elapsed = 0
|
const { runCountdown, clear } = useTimer()
|
||||||
let intervalId: ReturnType<typeof setInterval> | null = null
|
|
||||||
|
|
||||||
const start = () => {
|
runCountdown(1000)
|
||||||
if (!intervalId) {
|
vi.advanceTimersByTime(1000)
|
||||||
intervalId = setInterval(() => { elapsed++ }, 1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const pause = () => {
|
|
||||||
if (intervalId) {
|
|
||||||
clearInterval(intervalId)
|
|
||||||
intervalId = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
start()
|
expect(ElMessageBox.alert).toHaveBeenCalled()
|
||||||
vi.advanceTimersByTime(2000)
|
clear()
|
||||||
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()
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,90 +1,36 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
import { describe, it, expect, beforeEach } from 'vitest'
|
||||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
import router from '@/router'
|
||||||
|
|
||||||
// We test the guard logic by importing the router and simulating navigation
|
|
||||||
// The router in src/router/index.ts uses createWebHistory which requires DOM,
|
|
||||||
// so we'll test the guard logic by recreating the key patterns.
|
|
||||||
|
|
||||||
describe('route guards', () => {
|
describe('route guards', () => {
|
||||||
beforeEach(() => {
|
beforeEach(async () => {
|
||||||
localStorage.clear()
|
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 () => {
|
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.push('/welcome')
|
||||||
await router.isReady()
|
|
||||||
expect(router.currentRoute.value.path).toBe('/login')
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('allows authenticated user to access protected route', async () => {
|
it('allows authenticated user to access protected route', async () => {
|
||||||
localStorage.setItem('isLoggedIn', 'true')
|
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.push('/welcome')
|
||||||
await router.isReady()
|
|
||||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('allows unauthenticated access to /login', async () => {
|
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.push('/login')
|
||||||
await router.isReady()
|
|
||||||
expect(router.currentRoute.value.path).toBe('/login')
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('root path redirects to /login', async () => {
|
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.push('/')
|
||||||
await router.isReady()
|
|
||||||
expect(router.currentRoute.value.path).toBe('/login')
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+18
-3
@@ -1,7 +1,10 @@
|
|||||||
import { vi } from 'vitest'
|
import { vi } from 'vitest'
|
||||||
|
|
||||||
// Mock Element Plus components globally
|
// 只 mock Element Plus 的服务,组件保持真实实现,方便测试里挂载真实组件
|
||||||
vi.mock('element-plus', () => ({
|
vi.mock('element-plus', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('element-plus')>()
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
ElMessage: {
|
ElMessage: {
|
||||||
success: vi.fn(),
|
success: vi.fn(),
|
||||||
error: vi.fn(),
|
error: vi.fn(),
|
||||||
@@ -10,5 +13,17 @@ vi.mock('element-plus', () => ({
|
|||||||
},
|
},
|
||||||
ElMessageBox: {
|
ElMessageBox: {
|
||||||
confirm: vi.fn().mockResolvedValue('confirm'),
|
confirm: vi.fn().mockResolvedValue('confirm'),
|
||||||
|
alert: vi.fn().mockResolvedValue(undefined),
|
||||||
},
|
},
|
||||||
}))
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// jsdom 没有 Audio,组件和 useTimer 需要用到
|
||||||
|
class MockAudio {
|
||||||
|
loop = false
|
||||||
|
currentTime = 0
|
||||||
|
play = vi.fn().mockResolvedValue(undefined)
|
||||||
|
pause = vi.fn()
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.stubGlobal('Audio', MockAudio)
|
||||||
|
|||||||
@@ -22,15 +22,6 @@ vi.mock('axios', () => ({
|
|||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
vi.mock('element-plus', () => ({
|
|
||||||
ElMessage: {
|
|
||||||
success: vi.fn(),
|
|
||||||
error: vi.fn(),
|
|
||||||
warning: vi.fn(),
|
|
||||||
info: vi.fn(),
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
import request from '@/utils/request'
|
import request from '@/utils/request'
|
||||||
|
|
||||||
describe('request utility', () => {
|
describe('request utility', () => {
|
||||||
@@ -125,7 +116,7 @@ describe('request utility', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should throw for unsupported method', () => {
|
it('should throw for unsupported method', () => {
|
||||||
expect(() => request.request('patch', '/test', null)).toThrow('请求方法 patch 未实现')
|
expect(() => request.request('patch', '/test', null)).toThrow('该功能暂不可用,请刷新后重试')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ export interface StandardMindMap {
|
|||||||
generator: "BUILTIN" | "AI" | "USER" | "USER_MERGE";
|
generator: "BUILTIN" | "AI" | "USER" | "USER_MERGE";
|
||||||
generatorVersion?: string;
|
generatorVersion?: string;
|
||||||
sourceReportCount: number;
|
sourceReportCount: number;
|
||||||
sourceFragmentCount: number;
|
|
||||||
generatedTime?: string;
|
generatedTime?: string;
|
||||||
createdTime?: string;
|
createdTime?: string;
|
||||||
lastModifiedTime?: string;
|
lastModifiedTime?: string;
|
||||||
|
|||||||
+6
-3
@@ -38,20 +38,23 @@ a:hover {
|
|||||||
/* 按钮操作区统一规范:窄屏下操作按钮纵向全宽 */
|
/* 按钮操作区统一规范:窄屏下操作按钮纵向全宽 */
|
||||||
.action-row .el-button,
|
.action-row .el-button,
|
||||||
.edit-actions .el-button,
|
.edit-actions .el-button,
|
||||||
.fragment-edit-actions .el-button {
|
.fragment-edit-actions .el-button,
|
||||||
|
.task-actions .el-button {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.action-row,
|
.action-row,
|
||||||
.edit-actions,
|
.edit-actions,
|
||||||
.fragment-edit-actions {
|
.fragment-edit-actions,
|
||||||
|
.task-actions {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
.action-row .el-button,
|
.action-row .el-button,
|
||||||
.edit-actions .el-button,
|
.edit-actions .el-button,
|
||||||
.fragment-edit-actions .el-button {
|
.fragment-edit-actions .el-button,
|
||||||
|
.task-actions .el-button {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ const submitForm = async (formEl: FormInstance | undefined) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
defineExpose({ registerData, loading, submitForm, isNotEmpty });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ const handleLogout = async () => {
|
|||||||
await router.push("/login");
|
await router.push("/login");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
defineExpose({ isLoginRoute, showBackButton, pageTitle, handleLogout });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -89,7 +89,6 @@ onMounted(() => {
|
|||||||
v-for="row in tasks"
|
v-for="row in tasks"
|
||||||
:key="row.taskNum"
|
:key="row.taskNum"
|
||||||
class="surface-card task-card"
|
class="surface-card task-card"
|
||||||
@click="openTaskReview(row)"
|
|
||||||
>
|
>
|
||||||
<div class="task-head">
|
<div class="task-head">
|
||||||
<strong>{{ row.taskName }}</strong>
|
<strong>{{ row.taskName }}</strong>
|
||||||
@@ -107,15 +106,15 @@ onMounted(() => {
|
|||||||
type="success"
|
type="success"
|
||||||
size="small"
|
size="small"
|
||||||
:loading="openingTaskNum === row.taskNum"
|
:loading="openingTaskNum === row.taskNum"
|
||||||
@click.stop="openTaskReview(row)"
|
@click="openTaskReview(row)"
|
||||||
>
|
>
|
||||||
查看记录
|
查看记录
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
text
|
class="recall-button"
|
||||||
type="success"
|
type="success"
|
||||||
size="small"
|
size="small"
|
||||||
@click.stop="router.push(`/review/recall/${row.taskNum}`)"
|
@click="router.push(`/review/recall/${row.taskNum}`)"
|
||||||
>
|
>
|
||||||
回忆复习
|
回忆复习
|
||||||
</el-button>
|
</el-button>
|
||||||
@@ -172,7 +171,6 @@ onMounted(() => {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
cursor: pointer;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.task-head strong {
|
.task-head strong {
|
||||||
@@ -193,6 +191,8 @@ onMounted(() => {
|
|||||||
|
|
||||||
.task-actions {
|
.task-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,4 +201,10 @@ onMounted(() => {
|
|||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.task-actions .recall-button {
|
||||||
|
order: -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -541,7 +541,7 @@ onMounted(() => {
|
|||||||
<div v-else-if="standardExpanded" class="standard-content">
|
<div v-else-if="standardExpanded" class="standard-content">
|
||||||
<div class="standard-meta">
|
<div class="standard-meta">
|
||||||
<span>来源:{{ standard.generator }}</span>
|
<span>来源:{{ standard.generator }}</span>
|
||||||
<span>参考:{{ standard.sourceReportCount }} 份报告 + {{ standard.sourceFragmentCount }} 份残片</span>
|
<span>参考:{{ standard.sourceReportCount }} 份学习报告</span>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="!focusPath && !hasCompared" class="select-hint">
|
<p v-if="!focusPath && !hasCompared" class="select-hint">
|
||||||
点击导图节点即可选择复习起点,选好后凭记忆在上方补全知识点。
|
点击导图节点即可选择复习起点,选好后凭记忆在上方补全知识点。
|
||||||
|
|||||||
@@ -594,6 +594,17 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
clear();
|
clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
defineExpose({
|
||||||
|
taskInfo,
|
||||||
|
timerRunning,
|
||||||
|
timerIsOver,
|
||||||
|
startTimer,
|
||||||
|
stopTimer,
|
||||||
|
endTimer,
|
||||||
|
syncDisplay,
|
||||||
|
clear,
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
@@ -249,7 +249,7 @@ const submitTask = () => {
|
|||||||
updateTask();
|
updateTask();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
ElMessage.error("未知操作类型");
|
ElMessage.error("该功能暂不可用,请刷新后重试");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -288,6 +288,21 @@ async function previewMaterial() {
|
|||||||
results.forEach(({ u, t }) => { titles[u] = t; });
|
results.forEach(({ u, t }) => { titles[u] = t; });
|
||||||
materialPreview.value = renderMarkdown(raw, titles);
|
materialPreview.value = renderMarkdown(raw, titles);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
defineExpose({
|
||||||
|
priorityOptions,
|
||||||
|
priority,
|
||||||
|
taskNum,
|
||||||
|
taskName,
|
||||||
|
taskDescription,
|
||||||
|
materialUrl,
|
||||||
|
isUpdateMode,
|
||||||
|
loadTask,
|
||||||
|
createTask,
|
||||||
|
updateTask,
|
||||||
|
submitTask,
|
||||||
|
convertMaterialUrls,
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
+165
-126
@@ -1,63 +1,39 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from "vue";
|
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||||
import router from "@/router";
|
import router from "@/router";
|
||||||
import { getReviewFeed, type ReviewFeedItem } from "@/api/review";
|
import { getReviewFeed, getTaskReview, type ReviewFeedItem } from "@/api/review";
|
||||||
|
|
||||||
const reviewItems = ref<ReviewFeedItem[]>([]);
|
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;
|
sessionNum: string;
|
||||||
taskName: string;
|
taskName: string;
|
||||||
taskNum: string;
|
taskNum: string;
|
||||||
content: string;
|
content: string;
|
||||||
hasReport: boolean;
|
|
||||||
navigateType: string;
|
|
||||||
navigateId: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按 sessionNum 分组,一个会话展示为一个 chip
|
const truncateContent = (content: string, maxLength = 120) =>
|
||||||
const sessionGroups = computed<SessionGroup[]>(() => {
|
content.length > maxLength ? content.substring(0, maxLength) + "..." : content;
|
||||||
const map = new Map<string, ReviewFeedItem[]>();
|
|
||||||
for (const item of reviewItems.value) {
|
|
||||||
const list = map.get(item.sessionNum) || [];
|
|
||||||
list.push(item);
|
|
||||||
map.set(item.sessionNum, list);
|
|
||||||
}
|
|
||||||
|
|
||||||
const groups: SessionGroup[] = [];
|
// 滚动条只展示学习残片,每条残片单独作为 chip
|
||||||
for (const [sessionNum, items] of map) {
|
const fragmentChips = computed<FragmentChip[]>(() =>
|
||||||
const first = items[0];
|
reviewItems.value
|
||||||
const report = items.find(i => i.sourceType === "REPORT");
|
.filter(item => item.sourceType === "FRAGMENT")
|
||||||
const fragments = items.filter(i => i.sourceType === "FRAGMENT");
|
.map(item => ({
|
||||||
|
id: item.id,
|
||||||
const rawContent = report?.content || fragments.map(f => f.content).join(";");
|
sessionNum: item.sessionNum,
|
||||||
const content = rawContent.length > 120
|
taskName: item.taskName,
|
||||||
? rawContent.substring(0, 120) + "..."
|
taskNum: item.taskNum,
|
||||||
: rawContent;
|
content: truncateContent(item.content),
|
||||||
|
})),
|
||||||
groups.push({
|
);
|
||||||
sessionNum,
|
|
||||||
taskName: first.taskName,
|
|
||||||
taskNum: first.taskNum,
|
|
||||||
content,
|
|
||||||
hasReport: !!report,
|
|
||||||
navigateType: report ? "report" : "fragment",
|
|
||||||
navigateId: report ? report.id : (fragments[0]?.id ?? 0),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
groups.sort((a, b) => {
|
|
||||||
const aItem = reviewItems.value.find(i => i.sessionNum === a.sessionNum);
|
|
||||||
const bItem = reviewItems.value.find(i => i.sessionNum === b.sessionNum);
|
|
||||||
return (bItem?.createdTime || "").localeCompare(aItem?.createdTime || "");
|
|
||||||
});
|
|
||||||
|
|
||||||
return groups;
|
|
||||||
});
|
|
||||||
|
|
||||||
// 复制一份实现无缝循环
|
// 复制一份实现无缝循环
|
||||||
const duplicatedGroups = computed(() => [...sessionGroups.value, ...sessionGroups.value]);
|
const duplicatedChips = computed(() => [...fragmentChips.value, ...fragmentChips.value]);
|
||||||
|
|
||||||
const loadReviewFeed = async () => {
|
const loadReviewFeed = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -68,42 +44,67 @@ 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,
|
visible: false,
|
||||||
group: null,
|
fragment: null,
|
||||||
|
report: null,
|
||||||
|
fragments: [],
|
||||||
revealed: false,
|
revealed: false,
|
||||||
|
loadingSession: false,
|
||||||
|
loadError: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
// 当前回忆卡片对应会话的全部记录
|
const openRecallCard = (fragment: FragmentChip) => {
|
||||||
const recallSessionItems = computed(() => {
|
recallCard.value = {
|
||||||
const group = recallCard.value.group;
|
visible: true,
|
||||||
if (!group) return [];
|
fragment,
|
||||||
return reviewItems.value.filter((i) => i.sessionNum === group.sessionNum);
|
report: null,
|
||||||
});
|
fragments: [],
|
||||||
|
revealed: false,
|
||||||
const goToReviewDetail = (group: SessionGroup) => {
|
loadingSession: false,
|
||||||
recallCard.value = { visible: true, group, revealed: false };
|
loadError: "",
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const revealRecallContent = () => {
|
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;
|
recallCard.value.revealed = true;
|
||||||
};
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const openRecallDetail = () => {
|
recallCard.value.loadingSession = true;
|
||||||
const group = recallCard.value.group;
|
recallCard.value.loadError = "";
|
||||||
if (!group) return;
|
try {
|
||||||
recallCard.value.visible = false;
|
const res = await getTaskReview(fragment.taskNum);
|
||||||
router.push(`/review/detail/${group.navigateType}/${group.navigateId}`);
|
const items = (res?.data || []).filter(item => item.sessionNum === fragment.sessionNum);
|
||||||
|
recallCard.value.report = items.find(item => item.sourceType === "REPORT") || null;
|
||||||
|
recallCard.value.fragments = items.filter(item => item.sourceType === "FRAGMENT");
|
||||||
|
recallCard.value.revealed = true;
|
||||||
|
} catch {
|
||||||
|
recallCard.value.loadError = "展开对照内容加载失败,请稍后重试";
|
||||||
|
} finally {
|
||||||
|
recallCard.value.loadingSession = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 从回忆卡片跳转到回忆复习页(先匹配标准导图节点) */
|
/** 从回忆卡片跳转到回忆复习页(先匹配标准导图节点) */
|
||||||
const goToRecallFromCard = async () => {
|
const goToRecallFromCard = async () => {
|
||||||
const group = recallCard.value.group;
|
const fragment = recallCard.value.fragment;
|
||||||
if (!group) return;
|
if (!fragment) return;
|
||||||
recallCard.value.visible = false;
|
recallCard.value.visible = false;
|
||||||
const tn = group.taskNum;
|
const tn = fragment.taskNum;
|
||||||
const content = group.content || "";
|
const content = fragment.content || "";
|
||||||
if (tn && content) {
|
if (tn && content) {
|
||||||
try {
|
try {
|
||||||
const { findNode } = await import("@/api/standardMindMap");
|
const { findNode } = await import("@/api/standardMindMap");
|
||||||
@@ -128,8 +129,50 @@ const startReview = () => {
|
|||||||
router.push("/review");
|
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(() => {
|
onMounted(() => {
|
||||||
loadReviewFeed();
|
loadReviewFeed();
|
||||||
|
autoScroll = contentRef.value?.animate(
|
||||||
|
[
|
||||||
|
{ transform: "translateX(0)" },
|
||||||
|
{ transform: "translateX(-50%)" },
|
||||||
|
],
|
||||||
|
{ duration: AUTO_SCROLL_DURATION, iterations: Infinity, easing: "linear" },
|
||||||
|
) || null;
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
autoScroll?.cancel();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -139,26 +182,27 @@ onMounted(() => {
|
|||||||
<div class="review-scroll-section surface-card">
|
<div class="review-scroll-section surface-card">
|
||||||
<div class="review-scroll-header">
|
<div class="review-scroll-header">
|
||||||
<span class="color-legend">
|
<span class="color-legend">
|
||||||
<span class="dot dot-report"></span> 学习报告
|
|
||||||
<span class="dot dot-fragment"></span> 学习残片
|
<span class="dot dot-fragment"></span> 学习残片
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="review-scroll-track">
|
|
||||||
<div
|
<div
|
||||||
|
class="review-scroll-track"
|
||||||
|
@mouseenter="pauseAutoScroll"
|
||||||
|
@mouseleave="resumeAutoScroll"
|
||||||
|
@wheel.prevent="handleTrackWheel"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
ref="contentRef"
|
||||||
class="review-scroll-content"
|
class="review-scroll-content"
|
||||||
:class="{ paused: isHovering }"
|
|
||||||
@mouseenter="isHovering = true"
|
|
||||||
@mouseleave="isHovering = false"
|
|
||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
v-for="(group, index) in duplicatedGroups"
|
v-for="(chip, index) in duplicatedChips"
|
||||||
:key="index"
|
:key="index"
|
||||||
class="review-chip"
|
class="review-chip fragment-chip"
|
||||||
:class="group.hasReport ? 'has-report' : 'fragments-only'"
|
@click="openRecallCard(chip)"
|
||||||
@click="goToReviewDetail(group)"
|
|
||||||
>
|
>
|
||||||
<strong class="chip-task">{{ group.taskName }}</strong>
|
<strong class="chip-task">{{ chip.taskName }}</strong>
|
||||||
<span class="chip-content">{{ group.content }}</span>
|
<span class="chip-content">{{ chip.content }}</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -191,37 +235,54 @@ onMounted(() => {
|
|||||||
<!-- 回忆卡片:先回忆,再对照 -->
|
<!-- 回忆卡片:先回忆,再对照 -->
|
||||||
<el-dialog
|
<el-dialog
|
||||||
v-model="recallCard.visible"
|
v-model="recallCard.visible"
|
||||||
:title="recallCard.group?.taskName || '回忆一下'"
|
:title="recallCard.fragment?.taskName || '回忆一下'"
|
||||||
width="560px"
|
width="560px"
|
||||||
class="recall-card-dialog"
|
class="recall-card-dialog"
|
||||||
>
|
>
|
||||||
<template v-if="recallCard.group">
|
<template v-if="recallCard.fragment">
|
||||||
<p class="recall-question">
|
<p class="recall-question">
|
||||||
这次学习共有 {{ recallSessionItems.length }} 条记录。看着下面这个片段,先试着回忆:当时还学了什么?
|
看着下面这个残片,先试着回忆:当时还学了什么?
|
||||||
</p>
|
</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.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
|
<div
|
||||||
v-for="item in recallSessionItems"
|
v-for="item in recallCard.fragments"
|
||||||
:key="`${item.sourceType}-${item.id}`"
|
:key="item.id"
|
||||||
class="recall-full-item"
|
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'">
|
<span class="recall-item-tag tag-fragment">残片</span>
|
||||||
{{ item.sourceType === "REPORT" ? "报告" : "残片" }}
|
|
||||||
</span>
|
|
||||||
<span class="recall-item-content">{{ item.content }}</span>
|
<span class="recall-item-content">{{ item.content }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<el-empty
|
||||||
|
v-if="!recallCard.report && recallCard.fragments.length === 0"
|
||||||
|
description="暂未找到该会话的对照内容"
|
||||||
|
:image-size="48"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<el-button v-if="!recallCard.revealed" type="success" plain @click="revealRecallContent">
|
<el-button
|
||||||
回忆好了,展开对照
|
v-if="!recallCard.revealed"
|
||||||
|
type="success"
|
||||||
|
plain
|
||||||
|
:loading="recallCard.loadingSession"
|
||||||
|
@click="revealRecallContent"
|
||||||
|
>
|
||||||
|
展开对照
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-button v-else type="success" plain @click="openRecallDetail">进入详情页</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 type="success" @click="goToRecallFromCard">前往回忆复习</el-button>
|
||||||
<el-button @click="recallCard.visible = false">关闭</el-button>
|
<el-button @click="recallCard.visible = false">关闭</el-button>
|
||||||
</template>
|
</template>
|
||||||
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -297,10 +358,6 @@ onMounted(() => {
|
|||||||
margin-right: 3px;
|
margin-right: 3px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dot-report {
|
|
||||||
background: var(--green-600);
|
|
||||||
}
|
|
||||||
|
|
||||||
.dot-fragment {
|
.dot-fragment {
|
||||||
background: #e6a23c;
|
background: #e6a23c;
|
||||||
}
|
}
|
||||||
@@ -315,20 +372,6 @@ onMounted(() => {
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
gap: 14px;
|
gap: 14px;
|
||||||
white-space: nowrap;
|
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 {
|
.review-chip {
|
||||||
@@ -338,7 +381,7 @@ onMounted(() => {
|
|||||||
padding: 8px 16px;
|
padding: 8px 16px;
|
||||||
background: var(--surface-strong);
|
background: var(--surface-strong);
|
||||||
border: 1px solid var(--border-soft);
|
border: 1px solid var(--border-soft);
|
||||||
border-left: 3px solid transparent;
|
border-left: 3px solid #e6a23c;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: background 0.2s, box-shadow 0.2s;
|
transition: background 0.2s, box-shadow 0.2s;
|
||||||
@@ -346,23 +389,8 @@ onMounted(() => {
|
|||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.review-chip.has-report {
|
|
||||||
border-left-color: var(--green-600);
|
|
||||||
}
|
|
||||||
|
|
||||||
.review-chip.fragments-only {
|
|
||||||
border-left-color: #e6a23c;
|
|
||||||
}
|
|
||||||
|
|
||||||
.review-chip:hover {
|
.review-chip:hover {
|
||||||
box-shadow: var(--shadow-soft);
|
box-shadow: var(--shadow-soft);
|
||||||
}
|
|
||||||
|
|
||||||
.review-chip.has-report:hover {
|
|
||||||
background: #e8f5e9;
|
|
||||||
}
|
|
||||||
|
|
||||||
.review-chip.fragments-only:hover {
|
|
||||||
background: #fff8e1;
|
background: #fff8e1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -401,6 +429,12 @@ onMounted(() => {
|
|||||||
white-space: normal;
|
white-space: normal;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.recall-error {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
color: var(--el-color-danger, #f56c6c);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
.recall-full-list {
|
.recall-full-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -419,6 +453,11 @@ onMounted(() => {
|
|||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.recall-full-item.is-clicked {
|
||||||
|
background: #fff8e1;
|
||||||
|
border-color: #e6a23c;
|
||||||
|
}
|
||||||
|
|
||||||
.recall-item-tag {
|
.recall-item-tag {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
|
|||||||
@@ -32,14 +32,14 @@ const handleError = (error: any) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (error.response) {
|
if (error.response) {
|
||||||
const backendMessage = error.response?.data?.message || JSON.stringify(error.response?.data);
|
const backendMessage = error.response?.data?.message;
|
||||||
ElMessage.error(`请求失败,服务器返回: ${backendMessage}`);
|
ElMessage.error(backendMessage || "请求失败了,请稍后再试");
|
||||||
} else if (error.request) {
|
} else if (error.request) {
|
||||||
ElMessage.error("请求未收到响应,请检查接口运行状态");
|
ElMessage.error("请求失败了,请检查网络后重试");
|
||||||
} else {
|
} else {
|
||||||
ElMessage.error(error.message || "请求失败");
|
ElMessage.error("请求失败了,请稍后再试");
|
||||||
}
|
}
|
||||||
throw new Error("网络不通畅,请检查您的网络连接或服务器状态");
|
throw new Error("请求失败了,请稍后再试");
|
||||||
};
|
};
|
||||||
|
|
||||||
const validateResponse = (res: any) => {
|
const validateResponse = (res: any) => {
|
||||||
@@ -88,8 +88,8 @@ const del = (url: string, params: Record<string, any> = {}, config: any = {}) =>
|
|||||||
};
|
};
|
||||||
|
|
||||||
const requestNotImplemented = (method: string) => {
|
const requestNotImplemented = (method: string) => {
|
||||||
ElMessage.error(`请求方法 ${method} 未实现`);
|
ElMessage.error("该功能暂不可用,请刷新后重试");
|
||||||
throw new Error(`请求方法 ${method} 未实现`);
|
throw new Error("该功能暂不可用,请刷新后重试");
|
||||||
};
|
};
|
||||||
|
|
||||||
const request = (method: string, url: string, paramsOrData: any) => {
|
const request = (method: string, url: string, paramsOrData: any) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user