15 KiB
Speaking Lab Learning Progress v1 Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Add local per-user learning progress, continue learning, and per-line practiced/difficult status to the study page.
Architecture: Keep progress entirely in the existing speaking-lab-state-v1 localStorage state. Add pure progress helper functions to app.js and export them for small Node tests, then wire those helpers into the existing study-page render and event flow. No backend schema or admin-page changes are required.
Tech Stack: Vanilla HTML/CSS/JS, browser localStorage, Node built-in assert for helper tests, existing FastAPI backend unchanged.
File Structure
- Modify
F:\ooo\speaking-practice-local\index.html: add a继续学习button beside existing video actions. - Modify
F:\ooo\speaking-practice-local\app.js: add progress helpers, local state migration, save/restore logic, transcript status controls, and material-list progress summaries. - Modify
F:\ooo\speaking-practice-local\styles.css: style continue action, transcript status controls, and progress labels. - Add
F:\ooo\speaking-practice-local\tests\progress-helpers.test.mjs: Node tests for pure helper behavior. - Keep
F:\ooo\speaking-practice-local\backend\main.pyandbackend\db.pyunchanged except for verification.
Task 1: Add Progress Helper Tests
Files:
-
Add:
F:\ooo\speaking-practice-local\tests\progress-helpers.test.mjs -
Modify:
F:\ooo\speaking-practice-local\app.js -
Step 1: Create failing helper tests
Create tests\progress-helpers.test.mjs:
import assert from "node:assert/strict";
import {
createEmptyProgress,
getVideoProgress,
toggleLineIndex,
calculatePracticeSummary,
formatProgressSummary,
} from "../app.js";
const empty = createEmptyProgress();
assert.deepEqual(empty, {
currentTime: 0,
activeLineIndex: 0,
practicedLineIndexes: [],
difficultLineIndexes: [],
updatedAt: "",
});
const user = { progress: {} };
const progress = getVideoProgress(user, "video-1");
assert.deepEqual(progress.practicedLineIndexes, []);
assert.equal(user.progress["video-1"], progress);
assert.deepEqual(toggleLineIndex([0, 2], 1), [0, 1, 2]);
assert.deepEqual(toggleLineIndex([0, 1, 2], 1), [0, 2]);
assert.deepEqual(toggleLineIndex([2, 2, 0], 1), [0, 1, 2]);
assert.deepEqual(calculatePracticeSummary({
practicedLineIndexes: [0, 2],
}, 5), {
practiced: 2,
total: 5,
percent: 40,
});
assert.equal(formatProgressSummary({
practicedLineIndexes: [0, 2],
currentTime: 124.4,
}, 5), "已练 2/5 · 40%");
assert.equal(formatProgressSummary({
practicedLineIndexes: [],
currentTime: 124.4,
}, 0), "看到 02:04");
assert.equal(formatProgressSummary({
practicedLineIndexes: [],
currentTime: 0,
}, 0), "");
- Step 2: Run test and confirm it fails
Run:
node tests\progress-helpers.test.mjs
Expected: fails because app.js does not export these helpers yet.
- Step 3: Add test-safe exports and pure helpers in
app.js
Add const IS_BROWSER = typeof document !== "undefined"; near the top, guard DOM queries with IS_BROWSER, and only call bindEvents() / initializeApp() in the browser.
Add pure helpers:
function createEmptyProgress() {
return {
currentTime: 0,
activeLineIndex: 0,
practicedLineIndexes: [],
difficultLineIndexes: [],
updatedAt: "",
};
}
function normalizeProgress(progress) {
return {
...createEmptyProgress(),
...(progress || {}),
currentTime: Number(progress?.currentTime) || 0,
activeLineIndex: Number.isInteger(progress?.activeLineIndex) ? progress.activeLineIndex : 0,
practicedLineIndexes: normalizeIndexList(progress?.practicedLineIndexes),
difficultLineIndexes: normalizeIndexList(progress?.difficultLineIndexes),
};
}
function normalizeIndexList(value) {
if (!Array.isArray(value)) return [];
return [...new Set(value.map(Number).filter((index) => Number.isInteger(index) && index >= 0))].sort((a, b) => a - b);
}
function ensureUserProgress(user) {
if (!user) return null;
if (!user.progress || typeof user.progress !== "object") user.progress = {};
Object.keys(user.progress).forEach((videoId) => {
user.progress[videoId] = normalizeProgress(user.progress[videoId]);
});
return user.progress;
}
function getVideoProgress(user, videoId) {
const progressMap = ensureUserProgress(user);
if (!progressMap) return createEmptyProgress();
const key = String(videoId);
progressMap[key] = normalizeProgress(progressMap[key]);
return progressMap[key];
}
function toggleLineIndex(indexes, index) {
const normalized = normalizeIndexList(indexes);
if (normalized.includes(index)) {
return normalized.filter((item) => item !== index);
}
return normalizeIndexList([...normalized, index]);
}
function calculatePracticeSummary(progress, totalLines) {
const total = Math.max(0, Number(totalLines) || 0);
const practiced = normalizeIndexList(progress?.practicedLineIndexes).filter((index) => index < total).length;
const percent = total ? Math.round((practiced / total) * 100) : 0;
return { practiced, total, percent };
}
function formatProgressSummary(progress, totalLines) {
const summary = calculatePracticeSummary(progress, totalLines);
if (summary.total > 0 && summary.practiced > 0) {
return `已练 ${summary.practiced}/${summary.total} · ${summary.percent}%`;
}
const currentTime = Number(progress?.currentTime) || 0;
if (currentTime > 1) return `看到 ${formatTime(currentTime)}`;
return "";
}
At the bottom:
if (typeof module !== "undefined" && module.exports) {
module.exports = {
createEmptyProgress,
getVideoProgress,
toggleLineIndex,
calculatePracticeSummary,
formatProgressSummary,
};
}
- Step 4: Run helper test
Run:
node tests\progress-helpers.test.mjs
Expected: exit code 0.
Task 2: Wire Progress Save And Continue Learning
Files:
-
Modify:
F:\ooo\speaking-practice-local\index.html -
Modify:
F:\ooo\speaking-practice-local\app.js -
Step 1: Add continue button to
index.html
Inside <div class="video-actions">, before favorite/watch-later:
<button id="continueBtn" type="button" hidden>继续学习</button>
- Step 2: Add element and state fields in
app.js
Add continueBtn to els, add:
let lastProgressSaveAt = 0;
let pendingRestoreProgress = null;
- Step 3: Migrate users to include progress
In loadState(), after reading users, normalize each user:
const users = Array.isArray(saved.users) ? saved.users.map(normalizeUser) : [];
Add:
function normalizeUser(user) {
const normalized = {
...user,
favorites: Array.isArray(user.favorites) ? user.favorites : [],
watchLater: Array.isArray(user.watchLater) ? user.watchLater : [],
};
ensureUserProgress(normalized);
return normalized;
}
When creating a new user, include progress: {}.
- Step 4: Save playback progress
Add helpers:
function getActiveProgress() {
const user = getCurrentUser();
if (!user || !activeVideoId) return null;
return getVideoProgress(user, activeVideoId);
}
function saveActiveProgress(partial = {}, immediate = false) {
const progress = getActiveProgress();
if (!progress) return;
Object.assign(progress, partial, { updatedAt: new Date().toISOString() });
const now = Date.now();
if (immediate || now - lastProgressSaveAt > 1500) {
lastProgressSaveAt = now;
saveState();
renderContinueAction();
renderLibrary();
}
}
Update handleTimeUpdate() to call:
saveActiveProgress({ currentTime: els.video.currentTime || 0 });
Update setActiveLine() to call:
saveActiveProgress({ activeLineIndex: index }, true);
Add a beforeunload listener in bindEvents():
window.addEventListener("beforeunload", () => {
if (els.video && activeVideoId) {
saveActiveProgress({ currentTime: els.video.currentTime || 0, activeLineIndex: Math.max(activeLineIndex, 0) }, true);
}
});
- Step 5: Restore and continue
In selectVideo(id), before loadVideoSource(video), set:
pendingRestoreProgress = getActiveProgress();
Add:
function restoreProgressForActiveVideo() {
const progress = pendingRestoreProgress;
pendingRestoreProgress = null;
if (!progress) return;
const cues = getPrimaryCues();
const restoredIndex = cues[progress.activeLineIndex] ? progress.activeLineIndex : 0;
if (cues.length) setActiveLine(restoredIndex, true);
if (progress.currentTime > 1) {
els.video.currentTime = progress.currentTime;
}
}
function continueLearning() {
const progress = getActiveProgress();
if (!progress) return;
if (progress.currentTime > 1) els.video.currentTime = progress.currentTime;
if (progress.activeLineIndex >= 0) jumpToLine(progress.activeLineIndex);
els.video.play().catch(() => {});
}
function renderContinueAction() {
const progress = getActiveProgress();
const hasProgress = Boolean(progress && (progress.currentTime > 1 || progress.activeLineIndex > 0));
els.continueBtn.hidden = !hasProgress;
}
Call restoreProgressForActiveVideo() after renderTranscript() in selectVideo().
Bind continueBtn click to continueLearning().
- Step 6: Run syntax check
Run:
node --check app.js
node tests\progress-helpers.test.mjs
Expected: both pass.
Task 3: Add Per-Line Practiced And Difficult Controls
Files:
-
Modify:
F:\ooo\speaking-practice-local\app.js -
Modify:
F:\ooo\speaking-practice-local\styles.css -
Step 1: Update transcript line markup
In renderTranscript(), add a status area inside each .line-button:
<div class="line-status" aria-label="练习状态">
<button class="line-status-button practiced" type="button" data-status="practiced">已练</button>
<button class="line-status-button difficult" type="button" data-status="difficult">难句</button>
</div>
Use real DOM creation or the existing template, but make sure nested button clicks do not trigger line jump.
- Step 2: Add toggle function
Add:
function toggleLineStatus(index, status, event) {
event.stopPropagation();
const progress = getActiveProgress();
if (!progress) {
alert("请先登录后再记录学习进度。");
return;
}
if (status === "practiced") {
progress.practicedLineIndexes = toggleLineIndex(progress.practicedLineIndexes, index);
}
if (status === "difficult") {
progress.difficultLineIndexes = toggleLineIndex(progress.difficultLineIndexes, index);
}
progress.updatedAt = new Date().toISOString();
saveState();
renderTranscript();
renderLibrary();
}
- Step 3: Apply active classes
When rendering each line:
const progress = getActiveProgress();
const practiced = progress?.practicedLineIndexes.includes(index);
const difficult = progress?.difficultLineIndexes.includes(index);
button.classList.toggle("is-practiced", practiced);
button.classList.toggle("is-difficult", difficult);
Set .active on status buttons when their status applies.
- Step 4: Style controls
Add CSS:
.line-status {
display: flex;
gap: 5px;
justify-content: flex-end;
align-items: center;
}
.line-status-button {
min-height: 26px;
padding: 0 7px;
border-radius: 6px;
font-size: 12px;
white-space: nowrap;
}
.line-status-button.practiced.active {
color: #047857;
border-color: #9bd8c0;
background: #ecfdf5;
}
.line-status-button.difficult.active {
color: #92400e;
border-color: #f5c56f;
background: #fffbeb;
}
.line-button.is-practiced {
border-color: #ccebdd;
}
.line-button.is-difficult {
box-shadow: inset 3px 0 0 var(--gold);
}
- Step 5: Run checks
Run:
node --check app.js
node tests\progress-helpers.test.mjs
Expected: both pass.
Task 4: Show Material List Progress
Files:
-
Modify:
F:\ooo\speaking-practice-local\app.js -
Modify:
F:\ooo\speaking-practice-local\styles.css -
Step 1: Add progress summary to video items
In renderLibrary(), add another <small class="video-progress"></small> inside each .video-item.
Compute:
const progress = getVideoProgress(getCurrentUser(), video.id);
const primaryCueCount = getDefaultCueCount(video);
const summary = formatProgressSummary(progress, primaryCueCount);
Add:
function getDefaultCueCount(video) {
if (video?.subtitles?.en?.cues?.length) return video.subtitles.en.cues.length;
const firstTrack = Object.values(video?.subtitles || {})[0];
return firstTrack?.cues?.length || 0;
}
Only show the progress node when summary is not empty.
- Step 2: Style progress summary
Add:
.video-progress {
color: var(--brand);
font-weight: 700;
}
- Step 3: Run checks
Run:
node --check app.js
node tests\progress-helpers.test.mjs
Expected: both pass.
Task 5: Verify End To End
Files:
-
No new code unless verification reveals a bug.
-
Step 1: Run static checks
Run:
python -m py_compile backend\main.py backend\db.py
node --check app.js
node --check admin.js
node tests\progress-helpers.test.mjs
node tests\admin-file-input.test.mjs
Expected: all exit code 0.
- Step 2: Start or confirm dev server
Run if needed:
python -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 8000
Expected: http://127.0.0.1:8000 responds.
- Step 3: Browser smoke test
Open http://127.0.0.1:8000.
Manual checks:
- Log in as a normal user.
- Open a video with subtitles.
- Mark one line
已练. - Mark another line
难句. - Confirm left material list shows progress.
- Refresh the page.
- Confirm progress and line statuses remain.
- Click
继续学习and confirm it jumps to saved progress. - Log in as another user and confirm progress is separate.
Self-Review
Spec coverage:
- Save last playback time: Task 2.
- Save active subtitle line: Task 2.
- Continue learning action: Task 2.
- Per-line practiced/difficult controls: Task 3.
- Material list progress: Task 4.
- LocalStorage-only persistence: Task 2.
- Tests for helpers: Task 1 and Task 5.
Placeholder scan:
- No placeholder markers remain.
- All implementation steps include exact files and commands.
Type consistency:
- Progress fields consistently use
currentTime,activeLineIndex,practicedLineIndexes,difficultLineIndexes, andupdatedAt. - Video IDs are normalized with
String(videoId).