const STORAGE_KEY = "speaking-lab-state-v1"; const els = { searchInput: document.querySelector("#homeSearchInput"), loginForm: document.querySelector("#homeLoginForm"), emailInput: document.querySelector("#homeEmailInput"), passwordInput: document.querySelector("#homePasswordInput"), 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"; bindEvents(); initializeHome(); function bindEvents() { els.searchInput.addEventListener("input", renderHome); els.loginForm.addEventListener("submit", (event) => { event.preventDefault(); loginOrRegister(); }); els.logoutBtn.addEventListener("click", () => { state.currentUserId = null; saveState(); renderAccount(); renderHome(); }); } async function initializeHome() { 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); els.dashboardUser.textContent = user ? user.email : "登录后记录进度"; 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 = ` ${item.label} ${item.hint} ${item.value} `; button.addEventListener("click", () => { activeStatus = item.key; renderHome(); }); els.metricFilters.appendChild(button); }); } 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; return { total: videos.length, studied, unstudied: Math.max(0, videos.length - studied), favorites, difficult, }; } 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 = `

句子
进度
难句

`; card.querySelector(".home-cover-badge").textContent = tags[0] || "素材"; card.querySelector(".home-cover strong").textContent = getCoverText(video.title); 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.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 isAdmin(user) ? "还没有素材,去后台添加第一个素材。" : "暂无素材。"; } 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() { const user = getCurrentUser(); els.loginForm.hidden = Boolean(user); els.userMenu.hidden = !user; els.adminLink.hidden = !isAdmin(user); if (user) { els.userLabel.textContent = `${user.email}${isAdmin(user) ? " · 管理员" : ""}`; } } 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: email.includes("admin") ? "admin" : "user", favorites: [], watchLater: [], progress: {}, }; state.users.push(user); } else if (user.password !== password) { alert("密码不匹配。"); return; } state.currentUserId = user.id; saveState(); els.loginForm.reset(); renderAccount(); renderHome(); } 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 isAdmin(user) { const email = String(user?.email || "").toLowerCase(); return user?.role === "admin" || email.includes("admin"); } 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)); }