507 lines
17 KiB
JavaScript
507 lines
17 KiB
JavaScript
const STORAGE_KEY = "speaking-lab-state-v1";
|
|
|
|
const els = {
|
|
searchInput: document.querySelector("#homeSearchInput"),
|
|
userMenu: document.querySelector("#homeUserMenu"),
|
|
userLabel: document.querySelector("#homeUserLabel"),
|
|
logoutBtn: document.querySelector("#homeLogoutBtn"),
|
|
adminLink: document.querySelector("#homeAdminLink"),
|
|
dashboardUser: document.querySelector("#homeDashboardUser"),
|
|
metricFilters: document.querySelector("#homeMetricFilters"),
|
|
categoryFilters: document.querySelector("#homeCategoryFilters"),
|
|
status: document.querySelector("#homeStatus"),
|
|
grid: document.querySelector("#homeGrid"),
|
|
};
|
|
|
|
let state = loadState();
|
|
let videos = [];
|
|
let activeTag = "全部";
|
|
let activeStatus = "all";
|
|
let currentSessionUser = null;
|
|
|
|
bindEvents();
|
|
initializeHome();
|
|
|
|
function bindEvents() {
|
|
els.searchInput.addEventListener("input", renderHome);
|
|
els.logoutBtn.addEventListener("click", () => window.SpeakingAuth.logout());
|
|
}
|
|
|
|
async function initializeHome() {
|
|
currentSessionUser = await window.SpeakingAuth.requireSession();
|
|
if (!currentSessionUser) return;
|
|
ensureLocalUserForSession(currentSessionUser);
|
|
renderAccount();
|
|
els.status.textContent = "正在加载素材...";
|
|
|
|
try {
|
|
videos = await apiRequest("/api/videos");
|
|
renderHome();
|
|
} catch (error) {
|
|
els.status.textContent = error.message || "素材加载失败。";
|
|
els.grid.innerHTML = "";
|
|
}
|
|
}
|
|
|
|
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 renderHome() {
|
|
renderDashboard();
|
|
renderCategories();
|
|
const filtered = getFilteredVideos();
|
|
const emptyMessage = getEmptyMessage(filtered);
|
|
|
|
els.status.textContent = filtered.length ? `${filtered.length} 个素材` : emptyMessage;
|
|
els.grid.innerHTML = "";
|
|
|
|
if (!filtered.length) return;
|
|
|
|
const fragment = document.createDocumentFragment();
|
|
filtered.forEach((video) => {
|
|
fragment.appendChild(createVideoCard(video));
|
|
});
|
|
els.grid.appendChild(fragment);
|
|
}
|
|
|
|
function renderCategories() {
|
|
const tags = ["全部", ...new Set(videos.flatMap((video) => normalizeTags(video.tags)))];
|
|
els.categoryFilters.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;
|
|
renderHome();
|
|
});
|
|
els.categoryFilters.appendChild(button);
|
|
});
|
|
}
|
|
|
|
function renderDashboard() {
|
|
const user = getCurrentUser();
|
|
const metrics = calculateDashboardMetrics(user);
|
|
renderStudyPlan(metrics, user);
|
|
els.metricFilters.innerHTML = "";
|
|
|
|
getMetricItems(metrics).forEach((item) => {
|
|
const button = document.createElement("button");
|
|
button.type = "button";
|
|
button.className = `home-metric tone-${item.tone}${activeStatus === item.key ? " active" : ""}`;
|
|
button.dataset.status = item.key;
|
|
button.innerHTML = `
|
|
<span class="home-metric-icon" aria-hidden="true">${item.icon}</span>
|
|
<span class="home-metric-copy">
|
|
<span class="home-metric-label">${item.label}</span>
|
|
<small>${item.hint}</small>
|
|
</span>
|
|
<strong>${item.value}</strong>
|
|
`;
|
|
button.addEventListener("click", () => {
|
|
activeStatus = item.key;
|
|
renderHome();
|
|
});
|
|
els.metricFilters.appendChild(button);
|
|
});
|
|
}
|
|
|
|
function renderStudyPlan(metrics, user) {
|
|
const practiced = metrics.practicedLines;
|
|
const total = metrics.totalLines;
|
|
const percent = total ? Math.round((practiced / total) * 100) : 0;
|
|
const headline = practiced > 0 ? `已练 ${practiced} 句` : "准备开始";
|
|
const plan = user
|
|
? total > 0
|
|
? `今日计划:精听 10 分钟 · 完成度 ${percent}%`
|
|
: "今日计划:先添加一份素材"
|
|
: "今日计划:登录后记录学习进度";
|
|
|
|
els.dashboardUser.innerHTML = `
|
|
<strong>${headline}</strong>
|
|
<small>${plan}</small>
|
|
`;
|
|
}
|
|
|
|
function getMetricItems(metrics) {
|
|
return [
|
|
{ key: "all", label: "当前素材", value: metrics.total, hint: "持续更新中", icon: "::", tone: "blue" },
|
|
{ key: "studied", label: "已学习", value: metrics.studied, hint: "我的打卡", icon: "✓", tone: "green" },
|
|
{ key: "unstudied", label: "未学习", value: metrics.unstudied, hint: "未完成", icon: "○", tone: "slate" },
|
|
{ key: "favorites", label: "已收藏", value: metrics.favorites, hint: "收藏的视频", icon: "♡", tone: "rose" },
|
|
{ key: "difficult", label: "难句素材", value: metrics.difficult, hint: "重点复习", icon: "!", tone: "amber" },
|
|
];
|
|
}
|
|
|
|
function calculateDashboardMetrics(user) {
|
|
const loadedIds = new Set(videos.map((video) => String(video.id)));
|
|
const studied = videos.filter((video) => hasStudyProgress(user, video.id)).length;
|
|
const favoriteIds = new Set((user?.favorites || []).map(String));
|
|
const favorites = [...favoriteIds].filter((id) => loadedIds.has(id)).length;
|
|
const difficult = videos.filter((video) => getVideoProgress(user, video.id).difficultLineIndexes.length > 0).length;
|
|
const lineSummary = videos.reduce((summary, video) => {
|
|
const totalLines = getDefaultCueCount(video);
|
|
const progress = getVideoProgress(user, video.id);
|
|
const practiced = progress.practicedLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
|
|
return {
|
|
practicedLines: summary.practicedLines + practiced,
|
|
totalLines: summary.totalLines + totalLines,
|
|
};
|
|
}, { practicedLines: 0, totalLines: 0 });
|
|
|
|
return {
|
|
total: videos.length,
|
|
studied,
|
|
unstudied: Math.max(0, videos.length - studied),
|
|
favorites,
|
|
difficult,
|
|
practicedLines: lineSummary.practicedLines,
|
|
totalLines: lineSummary.totalLines,
|
|
};
|
|
}
|
|
|
|
function hasStudyProgress(user, videoId) {
|
|
if (!user) return false;
|
|
const progress = getVideoProgress(user, videoId);
|
|
return progress.currentTime > 1
|
|
|| progress.activeLineIndex > 0
|
|
|| progress.practicedLineIndexes.length > 0;
|
|
}
|
|
|
|
function createVideoCard(video) {
|
|
const card = document.createElement("article");
|
|
const user = getCurrentUser();
|
|
const tags = normalizeTags(video.tags);
|
|
const subtitleLabel = getSubtitleLabel(video);
|
|
const totalLines = getDefaultCueCount(video);
|
|
const progress = getVideoProgress(user, video.id);
|
|
const summary = calculatePracticeSummary(progress, totalLines);
|
|
const progressLabel = formatProgressSummary(progress, totalLines);
|
|
const difficultCount = progress.difficultLineIndexes.filter((index) => index < totalLines || totalLines === 0).length;
|
|
const coverTone = getCoverTone(video.id);
|
|
const isFavorite = Boolean(user?.favorites.map(String).includes(String(video.id)));
|
|
|
|
card.className = "home-card";
|
|
card.innerHTML = `
|
|
<div class="home-cover tone-${coverTone}">
|
|
<img class="home-cover-image" alt="">
|
|
<span class="home-cover-badge"></span>
|
|
<button class="home-favorite" type="button" aria-label="收藏素材"></button>
|
|
<strong></strong>
|
|
</div>
|
|
<a class="home-card-link" href="./study.html?video=${encodeURIComponent(video.id)}">
|
|
<div class="home-card-body">
|
|
<h3></h3>
|
|
<p class="home-card-meta"></p>
|
|
<div class="home-card-tags"></div>
|
|
<dl class="home-card-stats">
|
|
<div>
|
|
<dt>句子</dt>
|
|
<dd></dd>
|
|
</div>
|
|
<div>
|
|
<dt>进度</dt>
|
|
<dd></dd>
|
|
</div>
|
|
<div>
|
|
<dt>难句</dt>
|
|
<dd></dd>
|
|
</div>
|
|
</dl>
|
|
<p class="home-card-subtitles"></p>
|
|
<p class="home-progress" hidden></p>
|
|
</div>
|
|
</a>
|
|
`;
|
|
|
|
card.querySelector(".home-cover-badge").textContent = tags[0] || "素材";
|
|
card.querySelector(".home-cover strong").textContent = getCoverText(video.title);
|
|
const cover = card.querySelector(".home-cover");
|
|
const coverImage = card.querySelector(".home-cover-image");
|
|
const coverUrl = String(video.coverUrl || "").trim();
|
|
if (coverUrl) {
|
|
cover.classList.add("has-image");
|
|
coverImage.src = coverUrl;
|
|
coverImage.alt = `${video.title || "Speaking Lab"} 封面`;
|
|
}
|
|
|
|
card.querySelector("h3").textContent = video.title || "Untitled";
|
|
card.querySelector(".home-card-meta").textContent = video.speaker || "Unknown";
|
|
card.querySelector(".home-card-tags").append(...tags.map(createTagPill));
|
|
card.querySelector(".home-card-subtitles").textContent = subtitleLabel;
|
|
|
|
const statValues = card.querySelectorAll(".home-card-stats dd");
|
|
statValues[0].textContent = totalLines ? `${totalLines}` : "-";
|
|
statValues[1].textContent = totalLines ? `${summary.percent}%` : "未开始";
|
|
statValues[2].textContent = `${difficultCount}`;
|
|
|
|
const favorite = card.querySelector(".home-favorite");
|
|
favorite.textContent = isFavorite ? "♥" : "♡";
|
|
favorite.setAttribute("aria-label", isFavorite ? "取消收藏素材" : "收藏素材");
|
|
favorite.classList.toggle("active", isFavorite);
|
|
favorite.addEventListener("click", (event) => {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
toggleFavorite(video.id);
|
|
});
|
|
|
|
const progressNode = card.querySelector(".home-progress");
|
|
progressNode.textContent = progressLabel || "还未开始";
|
|
progressNode.hidden = false;
|
|
|
|
return card;
|
|
}
|
|
|
|
function createTagPill(tag) {
|
|
const span = document.createElement("span");
|
|
span.textContent = tag;
|
|
return span;
|
|
}
|
|
|
|
function getFilteredVideos() {
|
|
const query = els.searchInput.value.trim().toLowerCase();
|
|
const user = getCurrentUser();
|
|
|
|
return videos.filter((video) => {
|
|
const tags = normalizeTags(video.tags);
|
|
const matchesTag = activeTag === "全部" || tags.includes(activeTag);
|
|
const matchesStatus = matchesStatusFilter(video, user);
|
|
const haystack = [video.title, video.speaker, video.description, tags.join(" ")]
|
|
.join(" ")
|
|
.toLowerCase();
|
|
return matchesTag && matchesStatus && (!query || haystack.includes(query));
|
|
});
|
|
}
|
|
|
|
function matchesStatusFilter(video, user) {
|
|
if (activeStatus === "all") return true;
|
|
if (activeStatus === "studied") return hasStudyProgress(user, video.id);
|
|
if (activeStatus === "unstudied") return !hasStudyProgress(user, video.id);
|
|
if (activeStatus === "favorites") return Boolean(user?.favorites.map(String).includes(String(video.id)));
|
|
if (activeStatus === "difficult") return getVideoProgress(user, video.id).difficultLineIndexes.length > 0;
|
|
return true;
|
|
}
|
|
|
|
function getEmptyMessage(filtered) {
|
|
const user = getCurrentUser();
|
|
const query = els.searchInput.value.trim();
|
|
|
|
if (!videos.length) {
|
|
return "暂无素材。";
|
|
}
|
|
if (!user && ["studied", "favorites", "difficult"].includes(activeStatus)) {
|
|
return "登录后可以查看你的学习记录。";
|
|
}
|
|
if (activeStatus === "favorites") return "还没有收藏素材。";
|
|
if (activeStatus === "difficult") return "还没有标记难句。";
|
|
if (query || activeTag !== "全部") return "没有匹配的素材。";
|
|
return filtered.length ? "" : "没有匹配的素材。";
|
|
}
|
|
|
|
function normalizeTags(tags) {
|
|
return Array.isArray(tags) && tags.length ? tags : ["未分类"];
|
|
}
|
|
|
|
function getSubtitleLabel(video) {
|
|
const codes = Object.keys(video.subtitles || {});
|
|
if (!codes.length) return "无字幕";
|
|
return codes.map((code) => {
|
|
if (code === "en") return "英文";
|
|
if (code === "zh") return "中文";
|
|
return code;
|
|
}).join(" / ");
|
|
}
|
|
|
|
function getDefaultCueCount(video) {
|
|
const subtitles = video.subtitles || {};
|
|
const enContent = subtitles.en?.content || "";
|
|
if (enContent) return parseSubtitleCount(enContent);
|
|
const firstTrack = Object.values(subtitles)[0];
|
|
return parseSubtitleCount(firstTrack?.content || "");
|
|
}
|
|
|
|
function parseSubtitleCount(text) {
|
|
const normalized = text
|
|
.replace(/^\uFEFF/, "")
|
|
.replace(/\r/g, "")
|
|
.replace(/^WEBVTT.*\n+/i, "")
|
|
.trim();
|
|
if (!normalized) return 0;
|
|
return normalized.split(/\n{2,}/).filter((block) => block.includes("-->")).length;
|
|
}
|
|
|
|
function getCoverText(title) {
|
|
const clean = String(title || "Speaking Lab").trim();
|
|
if (/[\u4e00-\u9fa5]/.test(clean)) return clean.slice(0, 6);
|
|
return clean
|
|
.split(/\s+/)
|
|
.filter(Boolean)
|
|
.slice(0, 3)
|
|
.map((word) => word[0])
|
|
.join("")
|
|
.toUpperCase();
|
|
}
|
|
|
|
function getCoverTone(id) {
|
|
const value = String(id || "").split("").reduce((sum, char) => sum + char.charCodeAt(0), 0);
|
|
return (value % 5) + 1;
|
|
}
|
|
|
|
function renderAccount() {
|
|
els.userMenu.hidden = false;
|
|
els.userLabel.textContent = currentSessionUser?.username || "";
|
|
if (els.adminLink) {
|
|
els.adminLink.hidden = currentSessionUser?.role !== "admin";
|
|
}
|
|
}
|
|
|
|
function ensureLocalUserForSession(sessionUser) {
|
|
const email = sessionUser.username;
|
|
let user = state.users.find((item) => item.email === email);
|
|
if (!user) {
|
|
user = {
|
|
id: `server-${sessionUser.id || email}`,
|
|
email,
|
|
role: sessionUser.role || "user",
|
|
favorites: [],
|
|
watchLater: [],
|
|
progress: {},
|
|
};
|
|
state.users.push(user);
|
|
}
|
|
state.currentUserId = user.id;
|
|
saveState();
|
|
}
|
|
|
|
function toggleFavorite(videoId) {
|
|
const user = getCurrentUser();
|
|
if (!user) {
|
|
alert("请先登录。第一版会自动注册新邮箱。");
|
|
return;
|
|
}
|
|
|
|
const key = String(videoId);
|
|
const favorites = new Set((user.favorites || []).map(String));
|
|
if (favorites.has(key)) {
|
|
favorites.delete(key);
|
|
} else {
|
|
favorites.add(key);
|
|
}
|
|
|
|
user.favorites = [...favorites];
|
|
saveState();
|
|
renderHome();
|
|
}
|
|
|
|
function getCurrentUser() {
|
|
return state.users.find((user) => user.id === state.currentUserId) || null;
|
|
}
|
|
|
|
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 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 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 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) || "{}");
|
|
return {
|
|
users: Array.isArray(saved.users) ? saved.users.map(normalizeUser) : [],
|
|
currentUserId: saved.currentUserId || null,
|
|
};
|
|
} catch {
|
|
return { users: [], currentUserId: null };
|
|
}
|
|
}
|
|
|
|
function saveState() {
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
|
|
}
|