feat: 回忆对比记录并展示复习耗时

This commit is contained in:
2026-10-09 11:16:30 +08:00
parent 99a1b16196
commit 21af81f48c
11 changed files with 424 additions and 6 deletions
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/utils/request', () => ({
default: {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
del: vi.fn(),
},
}))
import request from '@/utils/request'
import { recallCompare } from '@/api/standardMindMap'
const mockedRequest = vi.mocked(request)
describe('standardMindMap API', () => {
beforeEach(() => {
vi.clearAllMocks()
mockedRequest.post.mockResolvedValue({ code: 200, data: {} })
})
it('recallCompare 不带 timing 时不发送三个耗时字段', async () => {
await recallCompare('T001', '根主题\n- 子节点')
expect(mockedRequest.post).toHaveBeenCalledWith(
'/review/standard-mind-map/T001/recall',
{ recallOutline: '根主题\n- 子节点' },
{ timeout: 300_000 },
)
})
it('recallCompare 带 timing 时映射为后端字段', async () => {
await recallCompare('T001', '根主题', '根主题 / 子节点', {
startedAt: '2026-01-15T09:00:00',
lastInteractionAt: '2026-01-15T09:00:30',
durationSeconds: 30,
})
expect(mockedRequest.post).toHaveBeenCalledWith(
'/review/standard-mind-map/T001/recall',
{
recallOutline: '根主题',
focusPath: '根主题 / 子节点',
reviewStartedAt: '2026-01-15T09:00:00',
reviewLastInteractionAt: '2026-01-15T09:00:30',
reviewDurationSeconds: 30,
},
{ timeout: 300_000 },
)
})
})
@@ -0,0 +1,141 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
IDLE_WINDOW_MS,
useReviewDuration,
} from '@/components/composables/useReviewDuration'
/** 用假定时器把系统时钟拨到指定本地时刻,便于断言本地时间字符串与耗时秒数 */
const at = (hour: number, minute: number, second: number) =>
vi.setSystemTime(new Date(2026, 0, 15, hour, minute, second))
describe('useReviewDuration', () => {
beforeEach(() => {
vi.useFakeTimers()
at(9, 0, 0)
})
afterEach(() => {
vi.useRealTimers()
})
it('start 记录起始时刻,交互与尾部间隔正常累计', () => {
const { start, markInteraction, snapshot } = useReviewDuration()
start()
at(9, 0, 30)
markInteraction()
at(9, 0, 40)
const result = snapshot()
expect(result.startedAt).toBe('2026-01-15T09:00:00')
expect(result.lastInteractionAt).toBe('2026-01-15T09:00:30')
expect(result.durationSeconds).toBe(40)
})
it('中间空闲超过 5 分钟时该段整段丢弃', () => {
const { start, markInteraction, snapshot } = useReviewDuration()
start()
at(9, 0, 30)
markInteraction()
// 空闲 6 分钟后再交互,这 6 分钟不计入
at(9, 6, 30)
markInteraction()
at(9, 6, 40)
const result = snapshot()
expect(result.lastInteractionAt).toBe('2026-01-15T09:06:30')
expect(result.durationSeconds).toBe(40)
})
it('尾部空闲超过 5 分钟时不计入快照', () => {
const { start, markInteraction, snapshot } = useReviewDuration()
start()
at(9, 0, 20)
markInteraction()
// 距最后一次交互已过 6 分钟才提交,尾部空闲丢弃
at(9, 6, 20)
expect(snapshot().durationSeconds).toBe(20)
})
it('空闲窗口内整段(含首次交互前)都计入', () => {
const { start, markInteraction, snapshot } = useReviewDuration()
start()
at(9, 4, 59)
markInteraction()
at(9, 5, 0)
expect(IDLE_WINDOW_MS).toBe(5 * 60 * 1000)
expect(snapshot().durationSeconds).toBe(300)
})
it('未 start 时不累计,start 后 stop 不再响应交互', () => {
const { markInteraction, snapshot, start, stop } = useReviewDuration()
// 未 start:交互不生效,快照耗时为 0
at(9, 0, 5)
markInteraction()
at(9, 0, 10)
expect(snapshot().durationSeconds).toBe(0)
start()
at(9, 1, 10)
markInteraction()
stop()
at(9, 1, 20)
markInteraction()
// stop 后的交互不再更新最后交互时刻
expect(snapshot().lastInteractionAt).toBe('2026-01-15T09:01:10')
})
it('reset 开启新一轮,起始与累计都归零重算', () => {
const { start, markInteraction, snapshot, reset } = useReviewDuration()
start()
at(9, 0, 30)
markInteraction()
expect(snapshot().durationSeconds).toBe(30)
at(9, 1, 0)
reset()
at(9, 1, 5)
markInteraction()
at(9, 1, 8)
const result = snapshot()
expect(result.startedAt).toBe('2026-01-15T09:01:00')
expect(result.lastInteractionAt).toBe('2026-01-15T09:01:05')
expect(result.durationSeconds).toBe(8)
})
it('时间字符串为本地格式,不以 Z 结尾(禁止 toISOString)', () => {
const { start, snapshot } = useReviewDuration()
start()
const result = snapshot()
expect(result.startedAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/)
expect(result.startedAt).not.toContain('Z')
})
it('支持注入时钟,纯状态机下也能累计', () => {
const base = new Date(2026, 0, 15, 9, 0, 0).getTime()
let current = base
const { start, markInteraction, snapshot } = useReviewDuration({ now: () => current })
start()
current = base + 12_000
markInteraction()
current = base + 25_000
const result = snapshot()
expect(result.durationSeconds).toBe(25)
expect(result.lastInteractionAt).toBe('2026-01-15T09:00:12')
})
})
@@ -18,6 +18,7 @@ const tasks = [
reportCount: 3,
fragmentCount: 5,
effectiveTime: 9000,
reviewDurationSeconds: 1200,
},
{
taskNum: 'T002',
@@ -25,6 +26,7 @@ const tasks = [
reportCount: 1,
fragmentCount: 2,
effectiveTime: 4500,
reviewDurationSeconds: 300,
},
]
@@ -106,6 +108,15 @@ describe('Review 交互流程(集成)', () => {
expect(card.attributes('aria-label')).toContain('学习 Vue3 组合式 API')
})
it('卡片并列展示累计有效学习时长与累计复习耗时', async () => {
vi.mocked(getReviewTaskStats).mockResolvedValue({ code: 200, data: tasks })
const { wrapper } = await mountReview()
const text = wrapper.findAll('.task-card')[0].text()
expect(text).toContain('累计有效学习时长:2小时30分钟')
expect(text).toContain('累计复习耗时:20分钟')
})
it('接口失败时提示加载失败并提供重试,而不是显示空列表', async () => {
vi.mocked(getReviewTaskStats).mockRejectedValue({ code: 500, message: '服务异常' })
const { wrapper } = await mountReview()
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus, { ElMessage } from 'element-plus'
import { createMemoryHistory, createRouter } from 'vue-router'
@@ -46,9 +46,13 @@ const MindMapViewerStub = {
*/
describe('ReviewRecall 交互流程(集成)', () => {
beforeEach(() => {
// 只伪造 Date,保留真实定时器,避免 flushPromises 卡住
vi.useFakeTimers({ toFake: ['Date'] })
vi.clearAllMocks()
localStorage.clear()
localStorage.setItem('isLoggedIn', 'true')
// clearAllMocks 不会重置 mockReturnValue,需显式恢复默认大纲
toOutline.mockReturnValue('根主题\n- 子节点')
vi.mocked(getStandardMindMap).mockResolvedValue(ok(standardMap))
vi.mocked(listRecallRecords).mockResolvedValue(
@@ -76,6 +80,10 @@ describe('ReviewRecall 交互流程(集成)', () => {
vi.mocked(recallCompare).mockResolvedValue(ok(standardMap))
})
afterEach(() => {
vi.useRealTimers()
})
const mountPage = async () => {
const router = createRouter({
history: createMemoryHistory(),
@@ -104,8 +112,14 @@ describe('ReviewRecall 交互流程(集成)', () => {
await flushPromises()
await flushPromises()
expect(recallCompare).toHaveBeenCalledWith('T001', '根主题\n- 子节点', undefined)
expect(recallCompare).toHaveBeenCalledWith('T001', '根主题\n- 子节点', undefined, {
startedAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
lastInteractionAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
durationSeconds: expect.any(Number),
})
expect(ElMessage.success).toHaveBeenCalledWith('回忆对比完成')
// 提交后统计卡片展示“本次耗时”
expect(wrapper.text()).toContain('本次耗时')
// 对比完成后出现“清空重写”入口(v-if=hasCompared)
expect(wrapper.findAll('button').some((b) => b.text().trim() === '清空重写')).toBe(true)
wrapper.unmount()
@@ -124,4 +138,28 @@ describe('ReviewRecall 交互流程(集成)', () => {
expect(recallCompare).not.toHaveBeenCalled()
wrapper.unmount()
})
it('提交按钮点击不计入交互,耗时以编辑区最后一次交互为准', async () => {
vi.setSystemTime(new Date(2026, 0, 15, 9, 0, 0))
const { wrapper } = await mountPage()
// 在回忆编辑区交互一次
vi.setSystemTime(new Date(2026, 0, 15, 9, 0, 10))
await wrapper.find('.recall-edit-area').trigger('pointerdown')
// 之后 20 秒无交互,直接点提交按钮
vi.setSystemTime(new Date(2026, 0, 15, 9, 0, 30))
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '提交对比')!
await submit.trigger('click')
await flushPromises()
await flushPromises()
expect(recallCompare).toHaveBeenCalledWith('T001', '根主题\n- 子节点', undefined, {
startedAt: '2026-01-15T09:00:00',
lastInteractionAt: '2026-01-15T09:00:10',
durationSeconds: 30,
})
expect(wrapper.text()).toContain('30秒')
wrapper.unmount()
})
})
+24 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { formatRatio } from '@/utils/format'
import { formatDurationSeconds, formatRatio } from '@/utils/format'
describe('formatRatio', () => {
it('把 0~1 的比率格式化为一位小数的百分比', () => {
@@ -20,3 +20,26 @@ describe('formatRatio', () => {
expect(formatRatio('abc')).toBe('-')
})
})
describe('formatDurationSeconds', () => {
it('不足 1 分钟显示秒', () => {
expect(formatDurationSeconds(30)).toBe('30秒')
expect(formatDurationSeconds('45')).toBe('45秒')
})
it('不足 1 小时显示分钟与秒', () => {
expect(formatDurationSeconds(300)).toBe('5分钟0秒')
expect(formatDurationSeconds(1234)).toBe('20分钟34秒')
})
it('超过 1 小时显示小时与分钟', () => {
expect(formatDurationSeconds(9000)).toBe('2小时30分钟')
})
it('空值、非法值与非正数统一显示 "0秒"', () => {
expect(formatDurationSeconds()).toBe('0秒')
expect(formatDurationSeconds(null)).toBe('0秒')
expect(formatDurationSeconds(0)).toBe('0秒')
expect(formatDurationSeconds('abc')).toBe('0秒')
})
})
+1
View File
@@ -21,6 +21,7 @@ export interface ReviewTaskStats {
weekEffectiveTime: number;
avgEffectiveTime: number;
avgEffectivenessRatio: number;
reviewDurationSeconds: number;
}
export const getReviewFeed = (limit: number = 30, mode: "recent" | "random" | "smart" = "recent") => {
+15 -1
View File
@@ -30,6 +30,14 @@ export interface RecallRecord {
missedCount: number;
extraCount: number;
createdTime: string;
reviewDurationSeconds?: number;
}
/** 回忆对比耗时口径:本地时间字符串(yyyy-MM-ddTHH:mm:ss,无时区)+ 秒数 */
export interface RecallTiming {
startedAt: string;
lastInteractionAt: string;
durationSeconds: number;
}
// AI 聚合类接口耗时较长,统一放宽到 5 分钟(默认全局 30s)
@@ -50,14 +58,20 @@ export const updateStandardMindMap = (taskNum: string, outline: string) => {
return request.put(`/review/standard-mind-map/${taskNum}`, { outline });
};
/** 用户提交回忆大纲,与标准导图对比(可选指定起始节点路径) */
/** 用户提交回忆大纲,与标准导图对比(可选指定起始节点路径与复习耗时口径) */
export const recallCompare = (
taskNum: string,
recallOutline: string,
focusPath?: string,
timing?: RecallTiming,
): Promise<ApiResponse<StandardMindMap>> => {
const body: Record<string, any> = { recallOutline };
if (focusPath) body.focusPath = focusPath;
if (timing) {
body.reviewStartedAt = timing.startedAt;
body.reviewLastInteractionAt = timing.lastInteractionAt;
body.reviewDurationSeconds = timing.durationSeconds;
}
return request.post(`/review/standard-mind-map/${taskNum}/recall`, body, AI_TIMEOUT);
};
+1
View File
@@ -89,6 +89,7 @@ onMounted(() => {
</div>
<div class="task-meta">
<span>累计有效学习时长:{{ formatEffectiveTime(row.effectiveTime) }}</span>
<span>累计复习耗时:{{ formatEffectiveTime(row.reviewDurationSeconds) }}</span>
</div>
<div class="task-stats">
<span>学习报告数量:{{ row.reportCount || 0 }}</span>
+38 -2
View File
@@ -14,6 +14,8 @@ import {
import { ElMessage, ElMessageBox } from "element-plus";
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
import { useElapsedSeconds } from "@/components/composables/useElapsedSeconds";
import { useReviewDuration } from "@/components/composables/useReviewDuration";
import { formatDurationSeconds } from "@/utils/format";
const route = useRoute();
const router = useRouter();
@@ -28,6 +30,15 @@ const {
stop: stopComparingTimer,
} = useElapsedSeconds();
// 复习耗时:从标准导图加载完成开始,记录到提交对比结束(超 5 分钟无交互自动截断)
const {
start: startReviewDuration,
markInteraction: markReviewInteraction,
snapshot: reviewDurationSnapshot,
reset: resetReviewDuration,
} = useReviewDuration();
const currentDurationSeconds = ref(0);
// 重新生成标准导图
const regenerating = ref(false);
@@ -153,6 +164,8 @@ const loadData = async () => {
}
} catch { /* ignore */ }
}
// 标准导图加载完成,开启本轮复习耗时计时
startReviewDuration();
}
};
@@ -232,10 +245,13 @@ const handleRecallCompare = async () => {
}
comparing.value = true;
startComparingTimer();
// 提交按钮本身不计入交互,这里取提交前的耗时快照
const timing = reviewDurationSnapshot();
try {
const res = await recallCompare(taskNum.value, outline, focusPath.value || undefined);
const res = await recallCompare(taskNum.value, outline, focusPath.value || undefined, timing);
standard.value = res?.data || null;
hasCompared.value = true;
currentDurationSeconds.value = timing.durationSeconds;
// 解析对比结果
if (standard.value) {
const recordRes = await listRecallRecords(taskNum.value);
@@ -250,6 +266,8 @@ const handleRecallCompare = async () => {
historyRecords.value = records;
}
}
// 提交成功后开启新一轮计时
resetReviewDuration();
ElMessage.success("回忆对比完成");
} catch (e: any) {
ElMessage.error(e.message || "对比失败");
@@ -340,6 +358,7 @@ const selectHistoryRecord = (record: RecallRecord) => {
const tree = parseOutlineToTree(record.recallContent);
if (tree) recallTree.value = tree;
hasCompared.value = true;
currentDurationSeconds.value = record.reviewDurationSeconds ?? 0;
focusPath.value = record.focusPath || "";
standardExpanded.value = true;
} catch {
@@ -448,6 +467,10 @@ onMounted(() => {
<span class="stat-label">➕ 额外</span>
<strong class="stat-value extra">{{ lastResult.extraCount }}</strong>
</div>
<div class="stat-item">
<span class="stat-label">本次耗时</span>
<strong class="stat-value duration">{{ formatDurationSeconds(currentDurationSeconds) }}</strong>
</div>
</div>
<!-- 回忆历史 -->
@@ -464,6 +487,7 @@ onMounted(() => {
<el-tag v-if="record.focusPath" size="small" type="success" effect="plain" class="session-badge" :title="record.focusPath">节点</el-tag>
<el-tag v-else size="small" type="info" effect="plain" class="session-badge">全部</el-tag>
<span class="history-ratio">覆盖率 {{ (record.recallRatio * 100).toFixed(1) }}%</span>
<span class="history-duration">本次耗时 {{ formatDurationSeconds(record.reviewDurationSeconds) }}</span>
<span class="history-detail">✅{{ record.matchedCount }} ❌{{ record.missedCount }} ➕{{ record.extraCount }}</span>
</div>
</div>
@@ -497,7 +521,14 @@ onMounted(() => {
<p class="panel-hint">
凭记忆在导图上补全该任务的知识点:选中节点后 Tab 加子节点、Enter 加同级节点、双击修改文字。
</p>
<MindMapViewer ref="recallViewer" :tree="recallTree" :editable="true" height="60vh" />
<div
class="recall-edit-area"
@pointerdown="markReviewInteraction"
@keydown="markReviewInteraction"
@input="markReviewInteraction"
>
<MindMapViewer ref="recallViewer" :tree="recallTree" :editable="true" height="60vh" />
</div>
</article>
<!-- 标准导图(含对比着色) -->
@@ -676,6 +707,7 @@ onMounted(() => {
.matched { color: var(--accent-success-strong); }
.missed { color: #c62828; }
.extra { color: #1565c0; }
.duration { color: var(--green-800); }
.panel-header {
display: flex;
@@ -865,6 +897,10 @@ onMounted(() => {
color: var(--text-secondary, #666);
}
.history-duration {
color: var(--text-secondary, #666);
}
/* 复习范围选择器 */
.review-scope {
display: flex;
@@ -0,0 +1,86 @@
// src/components/composables/useReviewDuration.ts
import { getCurrentInstance, onUnmounted } from 'vue';
/** 超过该空闲窗口没有任何交互,就认为用户已离开,这段空闲整段不计入复习耗时 */
export const IDLE_WINDOW_MS = 5 * 60 * 1000;
export interface ReviewDurationSnapshot {
startedAt: string;
lastInteractionAt: string;
durationSeconds: number;
}
/** 允许注入时钟,便于单测用假定时器验证累计与截断规则 */
export interface ReviewDurationOptions {
now?: () => number;
}
/** 本地时间格式化:yyyy-MM-ddTHH:mm:ss(无时区、非 UTC,禁止 toISOString 的 Z 形式) */
const formatLocalDateTime = (timestamp: number): string => {
const d = new Date(timestamp);
const pad = (n: number) => String(n).padStart(2, '0');
return (
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
`T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
);
};
/**
* 「复习耗时」计时:从行为开始累计,期间每次交互都续上耗时。
* - start():归零并记录 startedAt = lastInteractionAt = now
* - markInteraction():仅在 running 时生效,把距上次交互的间隔累加进 accumulatedMs;
* 间隔超过 IDLE_WINDOW_MS 时整段丢弃,只把 lastInteractionAt 推到当前时刻
* - snapshot():返回本地时间字符串与截断后的整数秒数
* - reset():提交成功后开启新一轮(等价于 start())
* - stop():结束计时
* 组件卸载时自动 stop;在组件外部调用仅作纯状态机使用。
*/
export function useReviewDuration(options: ReviewDurationOptions = {}) {
const now = options.now ?? (() => Date.now());
let running = false;
let startedAt = 0;
let lastInteractionAt = 0;
let accumulatedMs = 0;
const start = () => {
accumulatedMs = 0;
startedAt = now();
lastInteractionAt = startedAt;
running = true;
};
const markInteraction = () => {
if (!running) return;
const current = now();
const gap = current - lastInteractionAt;
if (gap <= IDLE_WINDOW_MS) {
accumulatedMs += gap;
}
lastInteractionAt = current;
};
const snapshot = (): ReviewDurationSnapshot => {
const current = now();
const tail = current - lastInteractionAt;
const tailMs = tail <= IDLE_WINDOW_MS ? tail : 0;
return {
startedAt: formatLocalDateTime(startedAt),
lastInteractionAt: formatLocalDateTime(lastInteractionAt),
durationSeconds: Math.floor((accumulatedMs + tailMs) / 1000),
};
};
const reset = () => {
start();
};
const stop = () => {
running = false;
};
if (getCurrentInstance()) {
onUnmounted(stop);
}
return { start, markInteraction, snapshot, reset, stop };
}
+15
View File
@@ -8,3 +8,18 @@ export const formatRatio = (ratio?: number | string | null): string => {
if (Number.isNaN(value)) return "-";
return `${(value * 100).toFixed(1)}%`;
};
/**
* 把秒数格式化为可读时长:不足 1 分钟显示秒,以便单次复习耗时可见。
* 空值、非法值与非正数统一显示 "0秒"。
*/
export const formatDurationSeconds = (seconds?: number | string | null): string => {
const value = Math.floor(Number(seconds));
if (!Number.isFinite(value) || value <= 0) return "0秒";
const hours = Math.floor(value / 3600);
const minutes = Math.floor((value % 3600) / 60);
const secs = value % 60;
if (hours > 0) return `${hours}小时${minutes}分钟`;
if (minutes > 0) return `${minutes}分钟${secs}秒`;
return `${secs}秒`;
};