Files
speaking-practice/app.js
T
TTlaji fa3111ce0b
Deploy Speaking Practice / deploy (push) Failing after 12m14s
chore: add gitea auto deploy workflow
2026-06-05 01:06:13 +08:00

1037 lines
32 KiB
JavaScript

const STORAGE_KEY = "speaking-lab-state-v1";
const IS_BROWSER = typeof document !== "undefined";
const els = {
video: IS_BROWSER ? document.querySelector("#video") : null,
emptyVideo: IS_BROWSER ? document.querySelector("#emptyVideo") : null,
loginForm: IS_BROWSER ? document.querySelector("#loginForm") : null,
emailInput: IS_BROWSER ? document.querySelector("#emailInput") : null,
passwordInput: IS_BROWSER ? document.querySelector("#passwordInput") : null,
userMenu: IS_BROWSER ? document.querySelector("#userMenu") : null,
userLabel: IS_BROWSER ? document.querySelector("#userLabel") : null,
logoutBtn: IS_BROWSER ? document.querySelector("#logoutBtn") : null,
searchInput: IS_BROWSER ? document.querySelector("#searchInput") : null,
tagFilters: IS_BROWSER ? document.querySelector("#tagFilters") : null,
videoList: IS_BROWSER ? document.querySelector("#videoList") : null,
videoCount: IS_BROWSER ? document.querySelector("#videoCount") : null,
videoTitle: IS_BROWSER ? document.querySelector("#videoTitle") : null,
favoriteBtn: IS_BROWSER ? document.querySelector("#favoriteBtn") : null,
previousBtn: IS_BROWSER ? document.querySelector("#previousBtn") : null,
replayBtn: IS_BROWSER ? document.querySelector("#replayBtn") : null,
nextBtn: IS_BROWSER ? document.querySelector("#nextBtn") : null,
loopToggle: IS_BROWSER ? document.querySelector("#loopToggle") : null,
recordBtn: IS_BROWSER ? document.querySelector("#recordBtn") : null,
stopRecordBtn: IS_BROWSER ? document.querySelector("#stopRecordBtn") : null,
playRecordingBtn: IS_BROWSER ? document.querySelector("#playRecordingBtn") : null,
recordingStatus: IS_BROWSER ? document.querySelector("#recordingStatus") : null,
recordingAudio: IS_BROWSER ? document.querySelector("#recordingAudio") : null,
primarySubtitle: IS_BROWSER ? document.querySelector("#primarySubtitle") : null,
secondarySubtitle: IS_BROWSER ? document.querySelector("#secondarySubtitle") : null,
subtitleMeta: IS_BROWSER ? document.querySelector("#subtitleMeta") : null,
transcriptList: IS_BROWSER ? document.querySelector("#transcriptList") : null,
modeTabs: IS_BROWSER ? document.querySelectorAll(".tab[data-mode]") : [],
adminEntryBtn: IS_BROWSER ? document.querySelector("#adminEntryBtn") : null,
savedLists: IS_BROWSER ? document.querySelector("#savedLists") : null,
};
const sampleVideos = [
{
id: "sample-ted",
title: "How I set myself free",
speaker: "Keke Palmer",
description: "A short demo record for TED-style speaking practice.",
tags: ["人文", "演讲", "口语"],
duration: 18,
videoUrl: "",
sourceType: "demo",
subtitles: {
en: {
languageName: "English",
cues: parseSubtitle(`1
00:00:00,000 --> 00:00:04,000
I learned that freedom begins with telling the truth.
2
00:00:04,000 --> 00:00:08,500
Not the polished truth, but the uncomfortable one.
3
00:00:08,500 --> 00:00:13,000
When I stopped performing, I finally started listening.
4
00:00:13,000 --> 00:00:18,000
And that is how I began to set myself free.`),
},
zh: {
languageName: "中文",
cues: parseSubtitle(`1
00:00:00,000 --> 00:00:04,000
我发现,自由始于说出真相。
2
00:00:04,000 --> 00:00:08,500
不是修饰过的真相,而是那个令人不安的真相。
3
00:00:08,500 --> 00:00:13,000
当我停止表演时,我终于开始倾听自己。
4
00:00:13,000 --> 00:00:18,000
这就是我开始让自己自由的方式。`),
},
},
},
{
id: "sample-tech",
title: "The future of useful AI",
speaker: "Demo Speaker",
description: "Technology topic sample with bilingual subtitles.",
tags: ["科技", "AI", "设计"],
duration: 15,
videoUrl: "",
sourceType: "demo",
subtitles: {
en: {
languageName: "English",
cues: parseSubtitle(`1
00:00:00,000 --> 00:00:03,500
Good technology should make people feel more capable.
2
00:00:03,500 --> 00:00:07,500
It should reduce friction without removing human choice.
3
00:00:07,500 --> 00:00:11,500
That is the design challenge in front of us.
4
00:00:11,500 --> 00:00:15,000
Build tools that help people think, not tools that think for them.`),
},
zh: {
languageName: "中文",
cues: parseSubtitle(`1
00:00:00,000 --> 00:00:03,500
好的技术应该让人感觉自己更有能力。
2
00:00:03,500 --> 00:00:07,500
它应该减少阻力,但不拿走人的选择。
3
00:00:07,500 --> 00:00:11,500
这就是摆在我们面前的设计挑战。
4
00:00:11,500 --> 00:00:15,000
要做帮助人思考的工具,而不是替人思考的工具。`),
},
},
},
];
let state = loadState();
let activeVideoId = state.activeVideoId || sampleVideos[0].id;
let activeLineIndex = -1;
let activeTag = "全部";
let subtitleMode = state.subtitleMode === "intensive" ? "english" : state.subtitleMode || "bilingual";
let mediaRecorder = null;
let recordingChunks = [];
let recordingUrl = null;
let hlsInstance = null;
let libraryLoadMessage = "";
let lastProgressSaveAt = 0;
let pendingRestoreProgress = null;
async function apiRequest(path, options = {}) {
const response = await fetch(path, options);
if (!response.ok) {
let message = "请求失败,请重试。";
try {
const payload = await response.json();
message = payload.detail || message;
} catch {
message = response.statusText || message;
}
throw new Error(message);
}
return response.json();
}
function normalizeVideoFromApi(video) {
const subtitles = {};
Object.entries(video.subtitles || {}).forEach(([code, subtitle]) => {
subtitles[code] = {
languageName: subtitle.languageName || code,
format: subtitle.format || "",
filePath: subtitle.filePath || "",
content: subtitle.content || "",
cues: parseSubtitle(subtitle.content || ""),
};
});
return {
id: String(video.id),
title: video.title || "Untitled",
speaker: video.speaker || "Unknown",
description: video.description || "",
tags: Array.isArray(video.tags) && video.tags.length ? video.tags : ["未分类"],
duration: video.duration || 0,
videoUrl: video.videoUrl || "",
sourceType: video.sourceType || "url",
subtitles,
};
}
if (IS_BROWSER) {
bindEvents();
initializeApp();
}
async function initializeApp() {
try {
libraryLoadMessage = "";
const videos = await apiRequest("/api/videos");
state.videos = videos.map(normalizeVideoFromApi);
if (!state.videos.length) {
state.videos = sampleVideos;
}
} catch (error) {
console.error(error);
state.videos = sampleVideos;
libraryLoadMessage = "后端视频库加载失败,当前显示示例素材。";
}
const requestedVideoId = getRequestedVideoId();
if (requestedVideoId && getVideo(requestedVideoId)) {
activeVideoId = requestedVideoId;
}
if (!getVideo(activeVideoId)) {
activeVideoId = state.videos[0]?.id || null;
}
renderAll();
if (activeVideoId) selectVideo(activeVideoId);
}
function bindEvents() {
els.loginForm.addEventListener("submit", (event) => {
event.preventDefault();
loginOrRegister();
});
els.logoutBtn.addEventListener("click", () => {
state.currentUserId = null;
saveState();
renderAccount();
renderSavedLists();
renderVideoMeta();
});
els.searchInput?.addEventListener("input", renderLibrary);
els.modeTabs.forEach((tab) => {
tab.addEventListener("click", () => {
subtitleMode = tab.dataset.mode || "bilingual";
state.subtitleMode = subtitleMode;
saveState();
renderSubtitleModeTabs();
renderTranscript();
syncSubtitles();
});
});
els.video.addEventListener("timeupdate", handleTimeUpdate);
els.previousBtn.addEventListener("click", () => jumpRelative(-1));
els.replayBtn.addEventListener("click", () => jumpToLine(activeLineIndex >= 0 ? activeLineIndex : 0));
els.nextBtn.addEventListener("click", () => jumpRelative(1));
els.favoriteBtn.addEventListener("click", () => toggleSaved("favorites"));
els.recordBtn.addEventListener("click", startRecording);
els.stopRecordBtn.addEventListener("click", stopRecording);
els.playRecordingBtn.addEventListener("click", () => {
els.recordingAudio.hidden = false;
els.recordingAudio.currentTime = 0;
els.recordingAudio.play();
});
els.adminEntryBtn?.addEventListener("click", () => {
window.location.href = "admin.html";
});
window.addEventListener("beforeunload", () => {
if (els.video && activeVideoId) {
saveActiveProgress({
currentTime: els.video.currentTime || 0,
activeLineIndex: Math.max(activeLineIndex, 0),
}, true);
}
});
}
function renderAll() {
renderAccount();
renderLibrary();
renderSavedLists();
}
function renderAccount() {
const user = getCurrentUser();
els.loginForm.hidden = Boolean(user);
els.userMenu.hidden = !user;
if (user) {
els.userLabel.textContent = user.email;
}
renderAdminAccess();
}
function renderAdminAccess() {
if (!els.adminEntryBtn) return;
els.adminEntryBtn.hidden = false;
}
function renderLibrary() {
if (!els.videoCount || !els.tagFilters || !els.videoList) return;
const videos = getFilteredVideos();
const tags = ["全部", ...new Set(state.videos.flatMap((video) => video.tags))];
els.videoCount.textContent = `${videos.length} 个`;
els.tagFilters.innerHTML = "";
tags.forEach((tag) => {
const button = document.createElement("button");
button.type = "button";
button.className = `chip${tag === activeTag ? " active" : ""}`;
button.textContent = tag;
button.addEventListener("click", () => {
activeTag = tag;
renderLibrary();
});
els.tagFilters.appendChild(button);
});
els.videoList.innerHTML = "";
if (libraryLoadMessage) {
els.videoList.insertAdjacentHTML("beforeend", `<div class="empty-state">${libraryLoadMessage}</div>`);
}
if (!videos.length) {
els.videoList.insertAdjacentHTML("beforeend", `<div class="empty-state">没有匹配的视频。</div>`);
return;
}
videos.forEach((video) => {
const button = document.createElement("button");
button.type = "button";
button.className = `video-item${video.id === activeVideoId ? " active" : ""}`;
button.innerHTML = `
<strong></strong>
<span></span>
<small></small>
<small class="video-progress" hidden></small>
`;
const progress = getVideoProgress(getCurrentUser(), video.id);
const progressSummary = formatProgressSummary(progress, getDefaultCueCount(video));
button.querySelector("strong").textContent = video.title;
button.querySelector("span").textContent = video.speaker || "Unknown speaker";
button.querySelector("small").textContent = video.tags.join(" / ");
const progressNode = button.querySelector(".video-progress");
progressNode.textContent = progressSummary;
progressNode.hidden = !progressSummary;
button.addEventListener("click", () => selectVideo(video.id));
els.videoList.appendChild(button);
});
}
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;
}
function getFilteredVideos() {
const query = els.searchInput?.value.trim().toLowerCase() || "";
return state.videos.filter((video) => {
const matchesTag = activeTag === "全部" || video.tags.includes(activeTag);
const haystack = [video.title, video.speaker, video.description, video.tags.join(" ")]
.join(" ")
.toLowerCase();
return matchesTag && (!query || haystack.includes(query));
});
}
function getRequestedVideoId() {
if (!IS_BROWSER) return null;
return new URLSearchParams(window.location.search).get("video");
}
function selectVideo(id) {
const video = getVideo(id) || state.videos[0];
if (!video) return;
if (activeVideoId && els.video) {
saveActiveProgress({
currentTime: els.video.currentTime || 0,
activeLineIndex: Math.max(activeLineIndex, 0),
}, true);
}
activeVideoId = video.id;
activeLineIndex = -1;
state.activeVideoId = activeVideoId;
saveState();
pendingRestoreProgress = getActiveProgress();
loadVideoSource(video);
renderLibrary();
renderSubtitleModeTabs();
renderVideoMeta();
renderTranscript();
restoreProgressForActiveVideo();
syncSubtitles();
updateNavigationState();
}
async function loadVideoSource(video) {
if (hlsInstance) {
hlsInstance.destroy();
hlsInstance = null;
}
els.video.pause();
els.video.removeAttribute("src");
els.video.load();
if (!video.videoUrl) {
els.emptyVideo.hidden = false;
els.emptyVideo.querySelector("strong").textContent = video.sourceType === "local-file"
? "请重新选择这个本地视频文件"
: "选择或上传一个视频";
els.emptyVideo.querySelector("span").textContent = video.sourceType === "local-file"
? "浏览器刷新后不能直接保留本地大视频文件,字幕和信息仍会保留。"
: "第一版支持本地 MP4/WebM 与 HLS 地址。";
return;
}
els.emptyVideo.hidden = true;
const isHls = /\.m3u8($|\?)/i.test(video.videoUrl);
if (isHls && !els.video.canPlayType("application/vnd.apple.mpegurl")) {
const Hls = await ensureHls();
if (Hls?.isSupported()) {
hlsInstance = new Hls();
hlsInstance.loadSource(video.videoUrl);
hlsInstance.attachMedia(els.video);
return;
}
}
els.video.src = video.videoUrl;
els.video.load();
}
function renderVideoMeta() {
const video = getActiveVideo();
if (!video) return;
const user = getCurrentUser();
if (els.videoTitle) els.videoTitle.textContent = video.title;
els.favoriteBtn.textContent = user?.favorites.includes(video.id) ? "已收藏" : "收藏";
}
function renderSubtitleModeTabs() {
els.modeTabs.forEach((tab) => {
tab.classList.toggle("active", tab.dataset.mode === subtitleMode);
});
}
function renderTranscript() {
const primary = getPrimaryCues();
const secondary = getSecondaryCues();
const modeConfig = getActiveSubtitleModeConfig();
const progress = getActiveProgress();
els.transcriptList.innerHTML = "";
if (!primary.length) {
if (els.subtitleMeta) els.subtitleMeta.textContent = modeConfig.message || "当前视频没有可用字幕。";
els.transcriptList.innerHTML = `<div class="empty-state">${modeConfig.message || "请在后台上传 .srt 或 .vtt 字幕。"}</div>`;
return;
}
if (els.subtitleMeta) els.subtitleMeta.textContent = modeConfig.message || `${primary.length} 句 · 点击文字稿跳转到对应片段`;
const fragment = document.createDocumentFragment();
primary.forEach((cue, index) => {
const paired = secondary[index];
const practiced = Boolean(progress?.practicedLineIndexes.includes(index));
const difficult = Boolean(progress?.difficultLineIndexes.includes(index));
const item = document.createElement("div");
item.className = "line-button";
item.classList.toggle("is-practiced", practiced);
item.classList.toggle("is-difficult", difficult);
item.dataset.index = String(index);
item.innerHTML = `
<button class="line-jump" type="button">
<span class="line-time">${formatTime(cue.start)}</span>
<div>
<p class="line-primary"></p>
<p class="line-secondary"></p>
</div>
</button>
<div class="line-status" aria-label="练习状态">
<button class="line-status-button practiced${practiced ? " active" : ""}" type="button" data-status="practiced">已练</button>
<button class="line-status-button difficult${difficult ? " active" : ""}" type="button" data-status="difficult">难句</button>
</div>
`;
item.querySelector(".line-primary").innerHTML = highlightText(cue.text);
item.querySelector(".line-secondary").innerHTML = modeConfig.showSecondary && paired ? highlightText(paired.text) : "";
item.querySelector(".line-jump").addEventListener("click", () => jumpToLine(index));
item.querySelectorAll(".line-status-button").forEach((statusButton) => {
statusButton.addEventListener("click", (event) => {
toggleLineStatus(index, statusButton.dataset.status, event);
});
});
fragment.appendChild(item);
});
els.transcriptList.appendChild(fragment);
const restoredIndex = primary[activeLineIndex]
? activeLineIndex
: primary[progress?.activeLineIndex]
? progress.activeLineIndex
: 0;
setActiveLine(restoredIndex, false);
}
function handleTimeUpdate() {
const primary = getPrimaryCues();
const time = els.video.currentTime || 0;
saveActiveProgress({ currentTime: time });
const index = primary.findIndex((cue) => time >= cue.start && time < cue.end);
if (index >= 0 && index !== activeLineIndex) {
setActiveLine(index, true);
}
if (els.loopToggle.checked && activeLineIndex >= 0 && primary[activeLineIndex]) {
const cue = primary[activeLineIndex];
if (time >= cue.end) {
els.video.currentTime = cue.start;
els.video.play();
}
}
}
function jumpRelative(offset) {
const cues = getPrimaryCues();
if (!cues.length) return;
const base = activeLineIndex >= 0 ? activeLineIndex : 0;
jumpToLine(Math.max(0, Math.min(cues.length - 1, base + offset)));
}
function jumpToLine(index) {
const cue = getPrimaryCues()[index];
if (!cue) return;
els.video.currentTime = cue.start;
els.video.play().catch(() => {});
setActiveLine(index, true);
}
function setActiveLine(index, scrollIntoView) {
const primary = getPrimaryCues();
if (!primary[index]) return;
const previous = els.transcriptList.querySelector(".line-button.active");
if (previous) previous.classList.remove("active");
activeLineIndex = index;
const active = els.transcriptList.querySelector(`[data-index="${index}"]`);
if (active) {
active.classList.add("active");
if (scrollIntoView) active.scrollIntoView({ block: "nearest", behavior: "smooth" });
}
syncSubtitles();
updateNavigationState();
saveActiveProgress({ activeLineIndex: index }, true);
}
function syncSubtitles() {
const primary = getPrimaryCues()[activeLineIndex];
const secondary = getSecondaryCues()[activeLineIndex];
const modeConfig = getActiveSubtitleModeConfig();
if (els.primarySubtitle) els.primarySubtitle.textContent = primary?.text || "";
if (els.secondarySubtitle) els.secondarySubtitle.textContent = modeConfig.showSecondary && secondary ? secondary.text : "";
}
function updateNavigationState() {
const cues = getPrimaryCues();
els.previousBtn.disabled = !cues.length || activeLineIndex <= 0;
els.replayBtn.disabled = !cues.length;
els.nextBtn.disabled = !cues.length || activeLineIndex >= cues.length - 1;
}
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();
renderLibrary();
}
}
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 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();
}
function toggleSaved(field) {
const user = getCurrentUser();
if (!user) {
alert("请先登录。第一版会自动注册新邮箱。");
return;
}
const list = user[field];
if (list.includes(activeVideoId)) {
user[field] = list.filter((id) => id !== activeVideoId);
} else {
user[field] = [...list, activeVideoId];
}
saveState();
renderVideoMeta();
renderSavedLists();
}
function renderSavedLists() {
if (!els.savedLists) return;
const user = getCurrentUser();
if (!user) {
els.savedLists.innerHTML = "登录后可使用收藏。";
return;
}
els.savedLists.innerHTML = `
<div><strong>收藏</strong><br>${renderSavedNames(user.favorites)}</div>
`;
}
function renderSavedNames(ids) {
if (!ids.length) return "暂无";
return ids.map((id) => getVideo(id)?.title).filter(Boolean).join("、");
}
function loginOrRegister() {
const email = els.emailInput.value.trim().toLowerCase();
const password = els.passwordInput.value;
if (!email || !password) return;
let user = state.users.find((item) => item.email === email);
if (!user) {
user = {
id: `user-${Date.now()}`,
email,
password,
role: "user",
favorites: [],
watchLater: [],
progress: {},
};
state.users.push(user);
} else if (user.password !== password) {
alert("密码不匹配。");
return;
}
state.currentUserId = user.id;
saveState();
els.loginForm.reset();
renderAccount();
renderVideoMeta();
renderSavedLists();
}
async function startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recordingChunks = [];
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.addEventListener("dataavailable", (event) => {
if (event.data.size > 0) recordingChunks.push(event.data);
});
mediaRecorder.addEventListener("stop", () => {
stream.getTracks().forEach((track) => track.stop());
const blob = new Blob(recordingChunks, { type: mediaRecorder.mimeType || "audio/webm" });
if (recordingUrl) URL.revokeObjectURL(recordingUrl);
recordingUrl = URL.createObjectURL(blob);
els.recordingAudio.src = recordingUrl;
els.playRecordingBtn.disabled = false;
els.recordingStatus.textContent = "录音完成,可以回放对比原声。";
els.recordingStatus.classList.remove("recording-status-danger");
});
mediaRecorder.start();
els.recordBtn.disabled = true;
els.stopRecordBtn.disabled = false;
els.playRecordingBtn.disabled = true;
els.recordingStatus.textContent = "录音中...";
els.recordingStatus.classList.add("recording-status-danger");
} catch {
els.recordingStatus.textContent = "麦克风权限被拒绝或不可用。";
els.recordingStatus.classList.add("recording-status-danger");
}
}
function stopRecording() {
if (!mediaRecorder || mediaRecorder.state === "inactive") return;
mediaRecorder.stop();
els.recordBtn.disabled = false;
els.stopRecordBtn.disabled = true;
}
function ensureHls() {
if (window.Hls) return Promise.resolve(window.Hls);
return new Promise((resolve) => {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.min.js";
script.onload = () => resolve(window.Hls);
script.onerror = () => {
els.emptyVideo.hidden = false;
els.emptyVideo.querySelector("strong").textContent = "HLS 加载失败";
els.emptyVideo.querySelector("span").textContent = "当前浏览器不能原生播放 m3u8,且 hls.js 未能加载。";
resolve(null);
};
document.head.appendChild(script);
});
}
function getPrimaryCues() {
const video = getActiveVideo();
const config = getActiveSubtitleModeConfig();
return video?.subtitles?.[config.primaryCode]?.cues || [];
}
function getSecondaryCues() {
const config = getActiveSubtitleModeConfig();
if (!config.showSecondary || !config.secondaryCode) return [];
const video = getActiveVideo();
return video?.subtitles?.[config.secondaryCode]?.cues || [];
}
function getActiveSubtitleModeConfig() {
const video = getActiveVideo();
return getSubtitleModeConfig(subtitleMode, video?.subtitles || {});
}
function getSubtitleModeConfig(mode, subtitles = {}) {
const hasEnglish = Boolean(subtitles.en);
const hasChinese = Boolean(subtitles.zh);
const fallbackCode = hasEnglish ? "en" : Object.keys(subtitles)[0] || "";
if (mode === "bilingual") {
return {
primaryCode: hasEnglish ? "en" : fallbackCode,
secondaryCode: hasChinese ? "zh" : "",
showSecondary: hasEnglish && hasChinese,
message: hasChinese ? "" : "当前素材没有中文字幕。",
};
}
if (mode === "chinese") {
return {
primaryCode: hasChinese ? "zh" : fallbackCode,
secondaryCode: "",
showSecondary: false,
message: hasChinese ? "" : "当前素材没有中文字幕。",
};
}
return {
primaryCode: hasEnglish ? "en" : fallbackCode,
secondaryCode: "",
showSecondary: false,
message: "",
};
}
function getActiveVideo() {
return getVideo(activeVideoId);
}
function getVideo(id) {
return state.videos.find((video) => video.id === id);
}
function getCurrentUser() {
return state.users.find((user) => user.id === state.currentUserId) || null;
}
function parseSubtitle(text) {
const normalized = text
.replace(/^\uFEFF/, "")
.replace(/\r/g, "")
.replace(/^WEBVTT.*\n+/i, "")
.trim();
if (!normalized) return [];
const cues = [];
let currentCue = null;
let pendingIdentifier = "";
normalized.split("\n").forEach((line) => {
const row = line.trim();
if (!row) {
addParsedSubtitleCue(cues, currentCue);
currentCue = null;
pendingIdentifier = "";
return;
}
if (isSubtitleTimeRow(row)) {
addParsedSubtitleCue(cues, currentCue);
currentCue = { identifier: pendingIdentifier, timeRange: row, textRows: [] };
pendingIdentifier = "";
return;
}
if (currentCue) {
currentCue.textRows.push(row);
} else {
pendingIdentifier = pendingIdentifier ? `${pendingIdentifier} ${row}` : row;
}
});
addParsedSubtitleCue(cues, currentCue);
return cues.sort((a, b) => a.start - b.start);
}
function highlightText(text) {
const escaped = escapeHtml(text);
const words = [
"freedom",
"truth",
"uncomfortable",
"listening",
"technology",
"capable",
"friction",
"choice",
"design",
"think",
];
return words.reduce((html, word) => {
const pattern = new RegExp(`\\b(${word})\\b`, "gi");
return html.replace(pattern, "<mark>$1</mark>");
}, escaped);
}
function escapeHtml(text) {
return text.replace(/[&<>"']/g, (char) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\"": "&quot;",
"'": "&#039;",
})[char]);
}
function parseSubtitleBlock(block) {
const rows = block.split("\n").map((row) => row.trim()).filter(Boolean);
const timeRowIndex = rows.findIndex((row) => row.includes("-->"));
if (timeRowIndex < 0) return null;
return createSubtitleCue(rows[timeRowIndex], rows.slice(timeRowIndex + 1));
}
function isSubtitleTimeRow(row) {
return /\d{1,2}:\d{2}(?::\d{2})?[\.,]\d{3}\s*-->\s*\d{1,2}:\d{2}(?::\d{2})?[\.,]\d{3}/.test(row);
}
function addParsedSubtitleCue(cues, cue) {
const parsed = cue ? createSubtitleCue(cue.timeRange, cue.textRows) : null;
if (parsed) cues.push(parsed);
}
function createSubtitleCue(timeRange, textRows) {
if (!hasSubtitleText(textRows)) return null;
const [startRaw, endRaw] = timeRange.split("-->").map((part) => part.trim().split(/\s+/)[0]);
const text = textRows.join(" ").trim();
return {
start: parseTimestamp(startRaw),
end: parseTimestamp(endRaw),
text,
};
}
function hasSubtitleText(textRows) {
return textRows
.join("")
.replace(/&nbsp;/gi, "")
.replace(/\u00a0/g, "")
.trim().length > 0;
}
function parseTimestamp(value) {
const clean = value.replace(",", ".");
const parts = clean.split(":").map(Number);
if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
if (parts.length === 2) return parts[0] * 60 + parts[1];
return Number(clean) || 0;
}
function formatTime(seconds) {
const total = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(total / 60);
const rest = total % 60;
return `${String(minutes).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
}
function createEmptyProgress() {
return {
currentTime: 0,
activeLineIndex: 0,
practicedLineIndexes: [],
difficultLineIndexes: [],
updatedAt: "",
};
}
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 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 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 "";
}
function normalizeUser(user) {
const normalized = {
...user,
favorites: Array.isArray(user?.favorites) ? user.favorites : [],
watchLater: Array.isArray(user?.watchLater) ? user.watchLater : [],
};
ensureUserProgress(normalized);
return normalized;
}
function loadState() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
const users = Array.isArray(saved.users) ? saved.users.map(normalizeUser) : [];
return {
users,
currentUserId: saved.currentUserId || null,
videos: [],
activeVideoId: saved.activeVideoId || null,
subtitleMode: saved.subtitleMode || "bilingual",
};
} catch {
return { users: [], currentUserId: null, videos: [], activeVideoId: null };
}
}
function saveState() {
const persistable = {
users: state.users,
currentUserId: state.currentUserId,
activeVideoId: state.activeVideoId,
subtitleMode,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(persistable));
}
if (typeof module !== "undefined" && module.exports) {
module.exports = {
createEmptyProgress,
getVideoProgress,
toggleLineIndex,
calculatePracticeSummary,
formatProgressSummary,
getSubtitleModeConfig,
parseSubtitle,
};
}