Ship the Synology/Mac deployable player with curriculum mapping, stats, and resource library. Co-authored-by: Cursor <cursoragent@cursor.com>
1100 lines
43 KiB
JavaScript
1100 lines
43 KiB
JavaScript
const CHILD_MODE_STORAGE_KEY = "sss-child-mode";
|
||
|
||
const appState = {
|
||
deviceId: getDeviceId(),
|
||
childMode: getChildMode(),
|
||
data: null,
|
||
studyDate: null,
|
||
viewWeek: null,
|
||
cardModes: {},
|
||
playRecords: {},
|
||
playback: {
|
||
mode: null,
|
||
mediaType: null,
|
||
songId: null,
|
||
playlistIndex: 0,
|
||
expected: null,
|
||
},
|
||
fetchedAt: Date.now(),
|
||
};
|
||
|
||
const elements = {
|
||
identityButton: document.querySelector("#identity-button"),
|
||
bottomSettingsButton: document.querySelector("#bottom-settings-button"),
|
||
identityEmoji: document.querySelector("#identity-emoji"),
|
||
identityLabel: document.querySelector("#identity-label"),
|
||
weekKind: document.querySelector("#week-kind"),
|
||
weekTitle: document.querySelector("#week-title"),
|
||
weekCategory: document.querySelector("#week-category"),
|
||
studyDateLabel: document.querySelector("#study-date-label"),
|
||
previousWeek: document.querySelector("#previous-week"),
|
||
nextWeek: document.querySelector("#next-week"),
|
||
currentWeek: document.querySelector("#current-week"),
|
||
todayCheckins: document.querySelector("#today-checkins"),
|
||
todayPlays: document.querySelector("#today-plays"),
|
||
dayFlowerLabel: document.querySelector("#day-flower-label"),
|
||
dayPlayLabel: document.querySelector("#day-play-label"),
|
||
achievementCount: document.querySelector("#achievement-count"),
|
||
progressWeekdays: document.querySelector("#progress-weekdays"),
|
||
progressGrid: document.querySelector("#progress-grid"),
|
||
playlistLoopButton: document.querySelector("#playlist-loop-button"),
|
||
playlistLoopStatus: document.querySelector("#playlist-loop-status"),
|
||
weeklyLoopPlayer: document.querySelector("#weekly-loop-player"),
|
||
playerHeading: document.querySelector("#player-heading"),
|
||
songCards: document.querySelector("#song-cards"),
|
||
roundCheckin: document.querySelector("#round-checkin"),
|
||
roundFlowers: document.querySelector("#round-flowers"),
|
||
roundHint: document.querySelector("#round-hint"),
|
||
weekGrid: document.querySelector("#week-grid"),
|
||
planSummary: document.querySelector("#plan-summary"),
|
||
assetStatus: document.querySelector("#asset-status"),
|
||
identityDialog: document.querySelector("#identity-dialog"),
|
||
identityOptions: document.querySelector("#identity-options"),
|
||
settingsDialog: document.querySelector("#settings-dialog"),
|
||
settingsForm: document.querySelector("#settings-form"),
|
||
closeSettings: document.querySelector("#close-settings"),
|
||
startDate: document.querySelector("#start-date"),
|
||
checkinWindow: document.querySelector("#checkin-window"),
|
||
childMode: document.querySelector("#child-mode"),
|
||
toast: document.querySelector("#toast"),
|
||
celebration: document.querySelector("#celebration"),
|
||
celebrationTitle: document.querySelector("#celebration-title"),
|
||
celebrationCopy: document.querySelector("#celebration-copy"),
|
||
startupStatus: document.querySelector("#startup-status"),
|
||
};
|
||
|
||
function getDeviceId() {
|
||
let id = localStorage.getItem("sss-device-id");
|
||
if (!id) {
|
||
const browserCrypto = window.crypto;
|
||
id = browserCrypto && browserCrypto.randomUUID
|
||
? browserCrypto.randomUUID()
|
||
: `device-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||
localStorage.setItem("sss-device-id", id);
|
||
}
|
||
return id;
|
||
}
|
||
|
||
function isIPhone5sOnIOS10() {
|
||
const userAgent = navigator.userAgent || "";
|
||
const screenWidth = Math.min(window.screen.width, window.screen.height);
|
||
const screenHeight = Math.max(window.screen.width, window.screen.height);
|
||
// Safari does not expose an iPhone model in its UA. 320 × 568 @ iOS 10
|
||
// identifies the 5s-sized device family, which is the intended target.
|
||
return /iPhone/.test(userAgent)
|
||
&& /OS 10[_\.]/.test(userAgent)
|
||
&& screenWidth === 320
|
||
&& screenHeight === 568;
|
||
}
|
||
|
||
function getChildMode() {
|
||
const stored = localStorage.getItem(CHILD_MODE_STORAGE_KEY);
|
||
if (stored === "1") return true;
|
||
if (stored === "0") return false;
|
||
return isIPhone5sOnIOS10();
|
||
}
|
||
|
||
function setChildMode(enabled) {
|
||
const next = Boolean(enabled);
|
||
if (appState.childMode !== next) {
|
||
pauseAll();
|
||
resetPlaybackMode();
|
||
appState.cardModes = {};
|
||
}
|
||
appState.childMode = next;
|
||
localStorage.setItem(CHILD_MODE_STORAGE_KEY, next ? "1" : "0");
|
||
}
|
||
|
||
function applyChildMode() {
|
||
document.body.classList.toggle("child-mode", appState.childMode);
|
||
elements.childMode.checked = appState.childMode;
|
||
}
|
||
|
||
function escapeHtml(value) {
|
||
return String(value == null ? "" : value)
|
||
.replace(/&/g, "&")
|
||
.replace(/</g, "<")
|
||
.replace(/>/g, ">")
|
||
.replace(/"/g, """)
|
||
.replace(/'/g, "'");
|
||
}
|
||
|
||
function forEachNode(nodes, callback) {
|
||
for (let index = 0; index < nodes.length; index += 1) {
|
||
callback(nodes[index], index);
|
||
}
|
||
}
|
||
|
||
function isModalOpen(modal) {
|
||
return modal && !modal.hasAttribute("hidden");
|
||
}
|
||
|
||
function showModal(modal) {
|
||
if (!modal) return;
|
||
modal.removeAttribute("hidden");
|
||
modal.style.display = "flex";
|
||
document.body.classList.add("modal-open");
|
||
}
|
||
|
||
function hideModal(modal) {
|
||
if (!modal) return;
|
||
modal.setAttribute("hidden", "hidden");
|
||
modal.style.display = "none";
|
||
if (!isModalOpen(elements.identityDialog) && !isModalOpen(elements.settingsDialog)) {
|
||
document.body.classList.remove("modal-open");
|
||
}
|
||
}
|
||
|
||
function localDate(value) {
|
||
return new Date(`${value}T12:00:00`);
|
||
}
|
||
|
||
function dateString(value) {
|
||
const year = value.getFullYear();
|
||
const month = String(value.getMonth() + 1).padStart(2, "0");
|
||
const day = String(value.getDate()).padStart(2, "0");
|
||
return `${year}-${month}-${day}`;
|
||
}
|
||
|
||
function shiftDate(value, days) {
|
||
const next = localDate(value);
|
||
next.setDate(next.getDate() + days);
|
||
return dateString(next);
|
||
}
|
||
|
||
function formatStudyDate(value) {
|
||
return new Intl.DateTimeFormat("zh-CN", {
|
||
month: "long",
|
||
day: "numeric",
|
||
weekday: "short",
|
||
}).format(localDate(value));
|
||
}
|
||
|
||
async function request(path, options = {}) {
|
||
const requestOptions = {};
|
||
Object.keys(options).forEach((key) => {
|
||
requestOptions[key] = options[key];
|
||
});
|
||
requestOptions.headers = { "Content-Type": "application/json" };
|
||
Object.keys(options.headers || {}).forEach((key) => {
|
||
requestOptions.headers[key] = options.headers[key];
|
||
});
|
||
const response = await fetch(path, requestOptions);
|
||
const payload = await response.json();
|
||
if (!response.ok) throw new Error(payload.error || "请求失败");
|
||
return payload;
|
||
}
|
||
|
||
function stateQuery(recover) {
|
||
const pairs = [
|
||
["device_id", appState.deviceId],
|
||
["recover", recover ? "1" : "0"],
|
||
];
|
||
if (appState.studyDate) pairs.push(["study_date", appState.studyDate]);
|
||
if (appState.viewWeek) pairs.push(["week", appState.viewWeek]);
|
||
return pairs
|
||
.map((pair) => `${encodeURIComponent(pair[0])}=${encodeURIComponent(pair[1])}`)
|
||
.join("&");
|
||
}
|
||
|
||
async function loadState({ recover = true, celebrateRecovered = true } = {}) {
|
||
const requestQuery = stateQuery(recover);
|
||
try {
|
||
appState.data = await request(`/api/state?${requestQuery}`);
|
||
appState.studyDate = appState.data.study_date;
|
||
appState.viewWeek = appState.data.week.number;
|
||
appState.fetchedAt = Date.now();
|
||
render();
|
||
elements.startupStatus.hidden = true;
|
||
if (celebrateRecovered && !appState.childMode && appState.data.recovered_awards.length) {
|
||
const awards = appState.data.recovered_awards;
|
||
const round = awards.some((award) => award.kind === "round");
|
||
window.setTimeout(() => {
|
||
celebrate(
|
||
round ? "整轮小红花补上啦!" : `欢迎回来,补上 ${awards.length} 朵小红花!`,
|
||
"上次已经认真听完,系统没有让努力漏掉。",
|
||
);
|
||
}, 220);
|
||
}
|
||
} catch (error) {
|
||
elements.startupStatus.hidden = false;
|
||
elements.startupStatus.textContent = "暂时无法连接学习记录,请检查家庭 Wi-Fi 后刷新页面。";
|
||
showToast(error.message);
|
||
}
|
||
}
|
||
|
||
function render() {
|
||
const { device, settings, week, day, weeks, actors } = appState.data;
|
||
applyChildMode();
|
||
elements.identityEmoji.textContent = device.actor_emoji || "●";
|
||
elements.identityLabel.textContent = device.actor || "选择身份";
|
||
elements.weekKind.textContent = appState.data.viewing_future
|
||
? "提前试听"
|
||
: appState.data.is_today
|
||
? "今日学习"
|
||
: "补学习";
|
||
elements.weekTitle.textContent = `第 ${week.number} 周`;
|
||
elements.weekCategory.textContent = (week.category || "综合复习").replace(/\n/g, " · ");
|
||
elements.studyDateLabel.textContent = appState.data.viewing_future
|
||
? `开课时间 · ${formatStudyDate(week.scheduled_start)}`
|
||
: `${appState.data.is_today ? "今天" : "补学日"} · ${formatStudyDate(appState.data.study_date)}`;
|
||
elements.playerHeading.textContent = week.kind === "review" ? `复习第 ${week.review_from}–${week.review_to} 周` : "本周歌单";
|
||
elements.previousWeek.disabled = week.number <= 1;
|
||
elements.nextWeek.disabled = week.number >= 50;
|
||
elements.currentWeek.hidden = appState.data.is_today;
|
||
elements.todayCheckins.textContent = day.flowers;
|
||
elements.todayPlays.textContent = day.video_plays + day.audio_plays;
|
||
elements.dayFlowerLabel.textContent = appState.data.viewing_future
|
||
? "暂不可领"
|
||
: appState.data.is_today
|
||
? "今日红花"
|
||
: "当日红花";
|
||
elements.dayPlayLabel.textContent = appState.data.viewing_future
|
||
? "预习播放"
|
||
: appState.data.is_today
|
||
? "今日播放"
|
||
: "当日播放";
|
||
elements.startDate.value = settings.start_date;
|
||
elements.startDate.max = appState.data.today_date;
|
||
setSelectValue(elements.checkinWindow, settings.checkin_window_minutes);
|
||
|
||
renderIdentityOptions(actors, device.actor);
|
||
if (!appState.childMode) renderProgress();
|
||
renderSongCards();
|
||
renderPlaylistControl();
|
||
if (!appState.childMode) {
|
||
renderRoundAward();
|
||
renderWeeks(weeks);
|
||
}
|
||
|
||
const assetsReady = week.songs.every((song) => appState.childMode
|
||
? song.audio_available
|
||
: song.video_available && song.audio_available && song.lyrics_available,
|
||
);
|
||
elements.assetStatus.textContent = assetsReady
|
||
? appState.childMode ? "音频已连接" : "视频、音频和歌词已连接"
|
||
: "有课程资源未连接";
|
||
if (device.needs_identity && !isModalOpen(elements.identityDialog)) {
|
||
showModal(elements.identityDialog);
|
||
}
|
||
}
|
||
|
||
function setSelectValue(select, value) {
|
||
const stringValue = String(value);
|
||
const hasValue = Array.prototype.some.call(select.options, (option) => option.value === stringValue);
|
||
if (!hasValue) {
|
||
const option = document.createElement("option");
|
||
option.value = stringValue;
|
||
option.textContent = `${stringValue} 分钟后可再领`;
|
||
select.append(option);
|
||
}
|
||
select.value = stringValue;
|
||
}
|
||
|
||
function formatWindow(minutes) {
|
||
if (minutes === 60) return "1 小时";
|
||
if (minutes === 120) return "2 小时";
|
||
return `${minutes} 分钟`;
|
||
}
|
||
|
||
function renderIdentityOptions(actors, currentActor) {
|
||
const html = actors
|
||
.map(
|
||
(actor) => `
|
||
<button type="button" class="identity-option ${actor.name === currentActor ? "selected" : ""}" data-actor="${escapeHtml(actor.name)}">
|
||
<span aria-hidden="true">${escapeHtml(actor.emoji)}</span>
|
||
${escapeHtml(actor.name)}
|
||
</button>`,
|
||
)
|
||
.join("");
|
||
elements.identityOptions.innerHTML = html;
|
||
forEachNode(elements.identityOptions.querySelectorAll("[data-actor]"), (button) => {
|
||
button.addEventListener("click", () => chooseIdentity(button.dataset.actor, true));
|
||
});
|
||
}
|
||
|
||
async function chooseIdentity(actor, closeFirstUse) {
|
||
if (closeFirstUse) hideModal(elements.identityDialog);
|
||
try {
|
||
const result = await request("/api/device/identity", {
|
||
method: "POST",
|
||
body: JSON.stringify({ device_id: appState.deviceId, actor }),
|
||
});
|
||
appState.data.device.actor = result.actor;
|
||
appState.data.device.actor_emoji = result.emoji;
|
||
appState.data.device.needs_identity = false;
|
||
showToast(`这台设备已设为${actor}`);
|
||
await loadState({ celebrateRecovered: false });
|
||
} catch (error) {
|
||
if (closeFirstUse) showModal(elements.identityDialog);
|
||
showToast(error.message);
|
||
}
|
||
}
|
||
|
||
function renderProgress() {
|
||
const days = appState.data.progress_14d;
|
||
elements.achievementCount.textContent = days.reduce((sum, day) => sum + day.flowers, 0);
|
||
elements.progressWeekdays.innerHTML = days
|
||
.slice(0, 7)
|
||
.map((day) => `<span>${day.weekday}</span>`)
|
||
.join("");
|
||
elements.progressGrid.innerHTML = days
|
||
.map((day) => {
|
||
let marker = "";
|
||
let detail = "";
|
||
if (day.status === "complete") {
|
||
marker = "🌸";
|
||
detail = `${day.flowers} 朵`;
|
||
} else if (day.status === "progress") {
|
||
marker = "🌱";
|
||
detail = `${day.completed_songs}/${day.total_songs} 首`;
|
||
} else if (day.status === "missed") {
|
||
marker = "○";
|
||
detail = "待补";
|
||
} else if (day.status === "today") {
|
||
marker = "+";
|
||
detail = "今天";
|
||
}
|
||
const selected = day.date === appState.studyDate ? "selected" : "";
|
||
const label = `${day.date},第 ${day.week || "—"} 周,${detail || (day.status === "future" ? "未来日期" : "课程未开始")}`;
|
||
return `
|
||
<button type="button" class="progress-day ${day.status} ${day.is_today ? "is-today" : ""} ${selected}"
|
||
data-study-date="${day.date}" ${day.clickable ? "" : "disabled"} aria-label="${escapeHtml(label)}">
|
||
<strong>${day.day}</strong>
|
||
<span class="day-flower" aria-hidden="true">${marker}</span>
|
||
<small>${escapeHtml(detail)}</small>
|
||
</button>`;
|
||
})
|
||
.join("");
|
||
forEachNode(elements.progressGrid.querySelectorAll("[data-study-date]:not(:disabled)"), (button) => {
|
||
button.addEventListener("click", () => changeStudyDate(button.dataset.studyDate, true));
|
||
});
|
||
}
|
||
|
||
function currentCooldown(song) {
|
||
const elapsed = Math.floor((Date.now() - appState.fetchedAt) / 1000);
|
||
return Math.max(0, song.cooldown_seconds - elapsed);
|
||
}
|
||
|
||
function songFlowerFeedback(song, slot) {
|
||
if (!appState.data.can_checkin) {
|
||
return appState.data.viewing_future
|
||
? "这是未来课程,可以先听歌;到开课后才能领取小红花"
|
||
: "请先选择这周对应的补学日期,再领取小红花";
|
||
}
|
||
if (slot < song.checkin_count) return "这朵小红花已经领过啦";
|
||
if (slot > song.checkin_count) return "先领取前面的小红花,再来点这一朵";
|
||
const remaining = currentCooldown(song);
|
||
if (song.ready_count > 0 && remaining > 0) {
|
||
return `同一首歌 ${formatWindow(appState.data.settings.checkin_window_minutes)}只能领一次,还要等待 ${Math.ceil(remaining / 60)} 分钟`;
|
||
}
|
||
if (song.ready_count <= 0) return `先把 ${song.title} 完整听完一次,就能领取这朵小红花`;
|
||
return "可以领取";
|
||
}
|
||
|
||
function songRewardMarkup(song) {
|
||
const timeLabels = ["上午领取", "下午领取", "晚上领取"];
|
||
const remaining = currentCooldown(song);
|
||
const canCheckin = appState.data.can_checkin && song.checkin_count < 3 && song.ready_count > 0 && remaining === 0;
|
||
const flowers = [0, 1, 2]
|
||
.map((slot) => {
|
||
const filled = slot < song.checkin_count;
|
||
const ready = slot === song.checkin_count && canCheckin;
|
||
const state = filled ? "filled" : ready ? "ready" : "empty";
|
||
const label = filled
|
||
? `${song.title} 第 ${slot + 1} 朵小红花已领取`
|
||
: ready
|
||
? `领取 ${song.title} 第 ${slot + 1} 朵小红花`
|
||
: `${song.title} 第 ${slot + 1} 朵小红花尚未解锁`;
|
||
const action = ready
|
||
? `data-checkin-song="${song.id}"`
|
||
: `data-feedback="${escapeHtml(songFlowerFeedback(song, slot))}" aria-disabled="true"`;
|
||
return `
|
||
<span class="flower-time-slot">
|
||
<button type="button" class="flower-slot ${state}" ${action} aria-label="${escapeHtml(label)}">${filled || ready ? "🌸" : "✿"}</button>
|
||
<small>${timeLabels[slot]}</small>
|
||
</span>`;
|
||
})
|
||
.join("");
|
||
return flowers;
|
||
}
|
||
|
||
function cardMode(songId) {
|
||
return appState.childMode ? "audio" : appState.cardModes[songId] || "video";
|
||
}
|
||
|
||
function childSongCardMarkup(song, index) {
|
||
return `
|
||
<article class="song-media-card child-song-card" data-song-card="${song.id}">
|
||
<header class="song-card-heading">
|
||
<div>
|
||
<p>歌曲 ${index + 1}</p>
|
||
<h3>${escapeHtml(song.title)}</h3>
|
||
</div>
|
||
<span class="play-status" data-card-status hidden></span>
|
||
</header>
|
||
<div class="song-media-panel song-audio-panel child-audio-panel" data-card-panel="audio">
|
||
<button class="audio-toggle" type="button" data-audio-toggle aria-label="播放 ${escapeHtml(song.title)} 音频">
|
||
<span class="audio-disc" aria-hidden="true">♫</span>
|
||
<strong>播放这首歌</strong>
|
||
<small>${escapeHtml(song.title)}</small>
|
||
</button>
|
||
<div class="audio-timeline">
|
||
<span data-audio-current>0:00</span>
|
||
<input type="range" min="0" max="0" value="0" step="0.1" data-audio-progress aria-label="${escapeHtml(song.title)} 音频进度" />
|
||
<span data-audio-duration>--:--</span>
|
||
</div>
|
||
<audio preload="none" data-audio-player data-audio-url="${song.audio_url}"></audio>
|
||
</div>
|
||
</article>`;
|
||
}
|
||
|
||
function renderSongCards() {
|
||
elements.songCards.innerHTML = appState.data.week.songs
|
||
.map((song, index) => {
|
||
if (appState.childMode) return childSongCardMarkup(song, index);
|
||
const mode = cardMode(song.id);
|
||
return `
|
||
<article class="song-media-card" data-song-card="${song.id}">
|
||
<header class="song-card-heading">
|
||
<div>
|
||
<p>本周歌曲 ${index + 1}</p>
|
||
<h3>${escapeHtml(song.title)}</h3>
|
||
</div>
|
||
<span class="play-status" data-card-status hidden></span>
|
||
</header>
|
||
|
||
<div class="mode-tabs" role="tablist" aria-label="${escapeHtml(song.title)} 内容形式">
|
||
<button class="mode-tab ${mode === "video" ? "selected" : ""}" type="button" data-card-mode="video" role="tab" aria-label="视频" aria-selected="${mode === "video"}">
|
||
<span aria-hidden="true">▶</span>
|
||
</button>
|
||
<button class="mode-tab ${mode === "audio" ? "selected" : ""}" type="button" data-card-mode="audio" role="tab" aria-label="音频" aria-selected="${mode === "audio"}">
|
||
<span aria-hidden="true">♫</span>
|
||
</button>
|
||
<button class="mode-tab ${mode === "lyrics" ? "selected" : ""}" type="button" data-card-mode="lyrics" role="tab" aria-label="歌词" aria-selected="${mode === "lyrics"}">
|
||
<span aria-hidden="true">▤</span>
|
||
</button>
|
||
</div>
|
||
|
||
<div class="song-media-shell">
|
||
<div class="song-media-panel song-video-panel" data-card-panel="video" ${mode === "video" ? "" : "hidden"}>
|
||
<video controls playsinline webkit-playsinline preload="none" data-video-player data-video-url="${song.video_url}" aria-label="${escapeHtml(song.title)} 视频"></video>
|
||
<button class="center-play" type="button" data-video-toggle>播放本首视频</button>
|
||
</div>
|
||
|
||
<div class="song-media-panel song-audio-panel" data-card-panel="audio" ${mode === "audio" ? "" : "hidden"}>
|
||
<img data-audio-art data-src="${song.lyrics_url}" alt="" />
|
||
<button class="audio-toggle" type="button" data-audio-toggle aria-label="播放 ${escapeHtml(song.title)} 音频">
|
||
<span class="audio-disc" aria-hidden="true">♫</span>
|
||
<strong>播放本首音频</strong>
|
||
<small>${escapeHtml(song.title)}</small>
|
||
</button>
|
||
<div class="audio-timeline">
|
||
<span data-audio-current>0:00</span>
|
||
<input type="range" min="0" max="0" value="0" step="0.1" data-audio-progress aria-label="${escapeHtml(song.title)} 音频进度" />
|
||
<span data-audio-duration>--:--</span>
|
||
</div>
|
||
<audio preload="none" data-audio-player data-audio-url="${song.audio_url}"></audio>
|
||
</div>
|
||
|
||
<div class="song-lyrics-panel" data-card-panel="lyrics" ${mode === "lyrics" ? "" : "hidden"}>
|
||
<img data-lyrics-image data-src="${song.lyrics_url}" alt="${escapeHtml(song.title)} 歌词" />
|
||
</div>
|
||
</div>
|
||
|
||
<footer class="song-card-reward">
|
||
<div class="flower-strip" data-song-reward="${song.id}">${songRewardMarkup(song)}</div>
|
||
</footer>
|
||
</article>`;
|
||
})
|
||
.join("");
|
||
bindSongCards();
|
||
}
|
||
|
||
function bindRewardButtons(container) {
|
||
forEachNode(container.querySelectorAll("[data-checkin-song]"), (button) => {
|
||
button.addEventListener("click", () => claimFlower(button.dataset.checkinSong));
|
||
});
|
||
forEachNode(container.querySelectorAll("[data-feedback]"), (button) => {
|
||
button.addEventListener("click", () => showToast(button.dataset.feedback));
|
||
});
|
||
}
|
||
|
||
function bindSongCards() {
|
||
forEachNode(elements.songCards.querySelectorAll("[data-song-card]"), (card) => {
|
||
const songId = card.dataset.songCard;
|
||
const song = appState.data.week.songs.find((item) => item.id === songId);
|
||
forEachNode(card.querySelectorAll("[data-card-mode]"), (button) => {
|
||
button.addEventListener("click", () => activateCardMode(card, songId, button.dataset.cardMode));
|
||
});
|
||
const video = card.querySelector("[data-video-player]");
|
||
const audio = card.querySelector("[data-audio-player]");
|
||
const videoToggle = card.querySelector("[data-video-toggle]");
|
||
if (video && videoToggle) {
|
||
videoToggle.addEventListener("click", () => toggleVideo(card, song));
|
||
video.addEventListener("play", () => onMediaPlay(card, song, "video", video));
|
||
video.addEventListener("pause", () => {
|
||
updateVideoButton(card, video);
|
||
updatePausedStatus(card, video);
|
||
renderPlaylistControl();
|
||
});
|
||
video.addEventListener("ended", () => completePlayback(song, "video", video));
|
||
}
|
||
const audioToggle = card.querySelector("[data-audio-toggle]");
|
||
const audioPanel = card.querySelector("[data-card-panel='audio']");
|
||
const progress = card.querySelector("[data-audio-progress]");
|
||
if (audio && audioToggle && audioPanel && progress) {
|
||
audioToggle.addEventListener("click", () => toggleAudio(card, song));
|
||
audioPanel.addEventListener("click", (event) => {
|
||
if (event.target.closest("[data-audio-toggle], .audio-timeline")) return;
|
||
toggleAudio(card, song);
|
||
});
|
||
audio.addEventListener("play", () => onMediaPlay(card, song, "audio", audio));
|
||
audio.addEventListener("pause", () => {
|
||
updateAudioControls(card, audio);
|
||
updatePausedStatus(card, audio);
|
||
renderPlaylistControl();
|
||
});
|
||
audio.addEventListener("timeupdate", () => updateAudioControls(card, audio));
|
||
audio.addEventListener("loadedmetadata", () => updateAudioControls(card, audio));
|
||
audio.addEventListener("ended", () => completePlayback(song, "audio", audio));
|
||
progress.addEventListener("input", () => {
|
||
if (Number.isFinite(audio.duration)) audio.currentTime = Number(progress.value);
|
||
});
|
||
}
|
||
bindRewardButtons(card);
|
||
activateCardMode(card, songId, cardMode(songId), false);
|
||
});
|
||
}
|
||
|
||
function renderRoundAward() {
|
||
const round = appState.data.round_award;
|
||
const elapsed = Math.floor((Date.now() - appState.fetchedAt) / 1000);
|
||
const remaining = Math.max(0, round.cooldown_seconds - elapsed);
|
||
const canCheckin = appState.data.can_checkin && round.checkin_count < 3 && round.ready_count > 0 && remaining === 0;
|
||
elements.roundHint.textContent = appState.data.viewing_future
|
||
? "可以提前听歌,等这周正式开始后再来领取大红花哦"
|
||
: `${round.total_songs} 首歌都听完,才能领取一朵大红花哦`;
|
||
elements.roundFlowers.innerHTML = [0, 1, 2]
|
||
.map((slot) => {
|
||
const filled = slot < round.checkin_count;
|
||
const ready = slot === round.checkin_count && canCheckin;
|
||
let feedback = "";
|
||
if (!appState.data.can_checkin) {
|
||
feedback = appState.data.viewing_future
|
||
? "这是未来课程,可以先听歌;到开课后才能领取大红花"
|
||
: "请先选择这周对应的补学日期,再领取大红花";
|
||
} else if (filled) {
|
||
feedback = "这朵整轮小红花已经领过啦";
|
||
} else if (slot > round.checkin_count) {
|
||
feedback = "先完成并领取前一轮的小红花";
|
||
} else if (round.ready_count > 0 && remaining > 0) {
|
||
feedback = `整轮小红花 ${formatWindow(appState.data.settings.checkin_window_minutes)}只能领一次,还要等待 ${Math.ceil(remaining / 60)} 分钟`;
|
||
} else {
|
||
const missing = Math.max(0, round.total_songs - round.completed_songs);
|
||
feedback = `这一轮还差 ${missing} 首歌没有完整听完`;
|
||
}
|
||
const action = ready
|
||
? "data-checkin-round"
|
||
: `data-feedback="${escapeHtml(feedback)}" aria-disabled="true"`;
|
||
const label = filled
|
||
? `第 ${slot + 1} 朵整轮小红花已领取`
|
||
: ready
|
||
? `领取第 ${slot + 1} 朵整轮小红花`
|
||
: `第 ${slot + 1} 朵整轮小红花尚未解锁`;
|
||
return `<button type="button" class="round-flower-button ${filled ? "filled" : ready ? "ready" : "empty"}" ${action} aria-label="${label}">${filled || ready ? "🌸" : "✿"}</button>`;
|
||
})
|
||
.join("");
|
||
forEachNode(elements.roundFlowers.querySelectorAll("[data-checkin-round]"), (button) => {
|
||
button.addEventListener("click", claimRoundFlower);
|
||
});
|
||
forEachNode(elements.roundFlowers.querySelectorAll("[data-feedback]"), (button) => {
|
||
button.addEventListener("click", () => showToast(button.dataset.feedback));
|
||
});
|
||
}
|
||
|
||
function renderWeeks(weeks) {
|
||
const studied = weeks.filter((week) => week.studied).length;
|
||
elements.planSummary.textContent = `${studied}/50 周有记录`;
|
||
elements.weekGrid.innerHTML = weeks
|
||
.map((week) => {
|
||
const classes = ["week-cell", week.kind];
|
||
if (week.studied) classes.push("studied");
|
||
if (week.number === appState.data.week.number) classes.push("selected");
|
||
const details = week.kind === "review" ? `第 ${week.number} 周,复习周` : `第 ${week.number} 周`;
|
||
if (!week.checkin_open) classes.push("preview");
|
||
return `<button type="button" class="${classes.join(" ")}" data-week-number="${week.number}" aria-label="${details}${week.checkin_open ? "" : ",可提前试听"}">${week.number}</button>`;
|
||
})
|
||
.join("");
|
||
forEachNode(elements.weekGrid.querySelectorAll("[data-week-number]"), (button) => {
|
||
button.addEventListener("click", () => changeWeek(Number(button.dataset.weekNumber), true));
|
||
});
|
||
}
|
||
|
||
function activateCardMode(card, songId, mode, persist = true) {
|
||
if (!["video", "audio", "lyrics"].includes(mode)) return;
|
||
if (persist) appState.cardModes[songId] = mode;
|
||
forEachNode(card.querySelectorAll("[data-card-mode]"), (button) => {
|
||
const selected = button.dataset.cardMode === mode;
|
||
button.classList.toggle("selected", selected);
|
||
button.setAttribute("aria-selected", String(selected));
|
||
});
|
||
forEachNode(card.querySelectorAll("[data-card-panel]"), (panel) => {
|
||
panel.hidden = panel.dataset.cardPanel !== mode;
|
||
});
|
||
if (mode === "audio") {
|
||
const art = card.querySelector("[data-audio-art]");
|
||
if (art && !art.getAttribute("src")) art.src = art.dataset.src;
|
||
}
|
||
if (mode === "lyrics") {
|
||
const image = card.querySelector("[data-lyrics-image]");
|
||
if (!image.getAttribute("src")) image.src = image.dataset.src;
|
||
}
|
||
}
|
||
|
||
function pauseAll(except = null) {
|
||
forEachNode(elements.songCards.querySelectorAll("video, audio"), (player) => {
|
||
if (player !== except) player.pause();
|
||
});
|
||
if (elements.weeklyLoopPlayer && elements.weeklyLoopPlayer !== except) {
|
||
elements.weeklyLoopPlayer.pause();
|
||
}
|
||
}
|
||
|
||
function currentPlaybackPlayer() {
|
||
if (appState.playback.mode === "weekly-loop") return elements.weeklyLoopPlayer;
|
||
const { songId, mediaType } = appState.playback;
|
||
if (!songId || !mediaType) return null;
|
||
const card = elements.songCards.querySelector(`[data-song-card="${songId}"]`);
|
||
return card ? card.querySelector(mediaType === "audio" ? "[data-audio-player]" : "[data-video-player]") : null;
|
||
}
|
||
|
||
function renderPlaylistControl() {
|
||
const playback = appState.playback;
|
||
const player = currentPlaybackPlayer();
|
||
const isWeeklyLoop = playback.mode === "weekly-loop";
|
||
const isPlaylist = playback.mode === "playlist";
|
||
const isPlaying = (isWeeklyLoop || isPlaylist) && player && !player.paused && !player.ended;
|
||
const icon = elements.playlistLoopButton.querySelector("span");
|
||
const label = elements.playlistLoopButton.querySelector("strong");
|
||
elements.playlistLoopButton.classList.toggle("playing", Boolean(isPlaying));
|
||
elements.playlistLoopButton.setAttribute("aria-pressed", String(Boolean(isPlaying)));
|
||
icon.textContent = isPlaying ? "Ⅱ" : "▶";
|
||
label.textContent = isPlaying ? "暂停播放" : (isWeeklyLoop || isPlaylist) ? "继续播放" : "一键播放";
|
||
|
||
const week = appState.data && appState.data.week;
|
||
const song = week ? week.songs.find((item) => item.id === playback.songId) : null;
|
||
if (isWeeklyLoop && week) {
|
||
elements.playlistLoopStatus.textContent = `${isPlaying ? "正在播放" : "已暂停"} · 第 ${week.number} 周连续循环`;
|
||
} else if (isPlaylist && song) {
|
||
elements.playlistLoopStatus.textContent = `${isPlaying ? "正在循环" : "已暂停"} · ${playback.playlistIndex + 1}/${appState.data.week.songs.length} ${song.title}`;
|
||
} else if (playback.mode === "single" && song) {
|
||
elements.playlistLoopStatus.textContent = `单曲循环 · ${song.title}(${playback.mediaType === "video" ? "视频" : "音频"})`;
|
||
} else {
|
||
elements.playlistLoopStatus.textContent = "等待播放";
|
||
}
|
||
}
|
||
|
||
function resetPlaybackMode() {
|
||
appState.playback = {
|
||
mode: null,
|
||
mediaType: null,
|
||
songId: null,
|
||
playlistIndex: 0,
|
||
expected: null,
|
||
};
|
||
renderPlaylistControl();
|
||
}
|
||
|
||
async function playCardMedia(songId, mediaType, mode, playlistIndex = 0) {
|
||
const song = appState.data.week.songs.find((item) => item.id === songId);
|
||
const card = elements.songCards.querySelector(`[data-song-card="${songId}"]`);
|
||
if (!song || !card) throw new Error("没有找到要播放的歌曲");
|
||
requireIdentity();
|
||
activateCardMode(card, songId, mediaType);
|
||
const player = card.querySelector(mediaType === "audio" ? "[data-audio-player]" : "[data-video-player]");
|
||
const urlKey = mediaType === "audio" ? "audioUrl" : "videoUrl";
|
||
if (!player.getAttribute("src")) {
|
||
player.src = player.dataset[urlKey];
|
||
player.load();
|
||
}
|
||
if (player.ended) player.currentTime = 0;
|
||
pauseAll(player);
|
||
appState.playback = {
|
||
mode,
|
||
mediaType,
|
||
songId,
|
||
playlistIndex,
|
||
expected: { mode, mediaType, songId },
|
||
};
|
||
renderPlaylistControl();
|
||
await player.play();
|
||
}
|
||
|
||
async function startPlaylistAt(index) {
|
||
const songs = appState.data.week.songs;
|
||
if (!songs.length) return;
|
||
const normalized = ((index % songs.length) + songs.length) % songs.length;
|
||
await playCardMedia(songs[normalized].id, "audio", "playlist", normalized);
|
||
const card = elements.songCards.querySelector(`[data-song-card="${songs[normalized].id}"]`);
|
||
if (card && card.scrollIntoView) card.scrollIntoView({ behavior: "smooth", block: "center" });
|
||
}
|
||
|
||
async function togglePlaylistLoop() {
|
||
try {
|
||
requireIdentity();
|
||
const player = elements.weeklyLoopPlayer;
|
||
if (appState.playback.mode === "weekly-loop" && !player.paused) {
|
||
player.pause();
|
||
renderPlaylistControl();
|
||
return;
|
||
}
|
||
const weekNumber = appState.data.week.number;
|
||
if (player.dataset.weekNumber !== String(weekNumber)) {
|
||
player.src = `/api/week-audio/${weekNumber}`;
|
||
player.dataset.weekNumber = String(weekNumber);
|
||
player.load();
|
||
}
|
||
pauseAll(player);
|
||
appState.playback = {
|
||
mode: "weekly-loop",
|
||
mediaType: "audio",
|
||
songId: null,
|
||
playlistIndex: 0,
|
||
expected: null,
|
||
};
|
||
await player.play();
|
||
renderPlaylistControl();
|
||
} catch (error) {
|
||
showToast(error.message || "音频正在准备,请再点一次播放");
|
||
}
|
||
}
|
||
|
||
function requireIdentity() {
|
||
if (appState.data.device.needs_identity) {
|
||
pauseAll();
|
||
if (!isModalOpen(elements.identityDialog)) showModal(elements.identityDialog);
|
||
throw new Error("请先选择这台设备的身份");
|
||
}
|
||
}
|
||
|
||
function playbackKey(songId, mediaType) {
|
||
return `${songId}:${mediaType}`;
|
||
}
|
||
|
||
async function ensurePlaybackStarted(song, mediaType, statusElement) {
|
||
requireIdentity();
|
||
const key = playbackKey(song.id, mediaType);
|
||
const existing = appState.playRecords[key];
|
||
if (existing) {
|
||
if (existing.playId) return existing.playId;
|
||
return (await existing.promise).play_id;
|
||
}
|
||
const promise = request("/api/playback/start", {
|
||
method: "POST",
|
||
body: JSON.stringify({
|
||
device_id: appState.deviceId,
|
||
song_id: song.id,
|
||
study_date: appState.studyDate,
|
||
course_week: appState.data.week.number,
|
||
media_type: mediaType,
|
||
}),
|
||
});
|
||
const record = { playId: null, promise };
|
||
appState.playRecords[key] = record;
|
||
let result;
|
||
try {
|
||
result = await promise;
|
||
} catch (error) {
|
||
delete appState.playRecords[key];
|
||
throw error;
|
||
}
|
||
record.playId = result.play_id;
|
||
if (statusElement) statusElement.textContent = "正在播放";
|
||
if (statusElement) statusElement.hidden = false;
|
||
return result.play_id;
|
||
}
|
||
|
||
async function onMediaPlay(card, song, mediaType, player) {
|
||
pauseAll(player);
|
||
const expected = appState.playback.expected;
|
||
if (!expected || expected.songId !== song.id || expected.mediaType !== mediaType) {
|
||
appState.playback = {
|
||
mode: "single",
|
||
mediaType,
|
||
songId: song.id,
|
||
playlistIndex: appState.data.week.songs.findIndex((item) => item.id === song.id),
|
||
expected: null,
|
||
};
|
||
} else {
|
||
appState.playback.expected = null;
|
||
}
|
||
renderPlaylistControl();
|
||
try {
|
||
await ensurePlaybackStarted(song, mediaType, card.querySelector("[data-card-status]"));
|
||
if (mediaType === "video") updateVideoButton(card, player);
|
||
if (mediaType === "audio") updateAudioControls(card, player);
|
||
} catch (error) {
|
||
player.pause();
|
||
showToast(error.message);
|
||
}
|
||
}
|
||
|
||
function updateVideoButton(card, video) {
|
||
const button = card.querySelector("[data-video-toggle]");
|
||
button.hidden = !video.paused;
|
||
if (video.ended) button.textContent = "重新播放视频";
|
||
else button.textContent = video.currentTime > 0 ? "继续播放视频" : "播放本首视频";
|
||
}
|
||
|
||
function updatePausedStatus(card, player) {
|
||
if (player.currentTime > 0 && !player.ended) {
|
||
const status = card.querySelector("[data-card-status]");
|
||
status.textContent = "已暂停";
|
||
status.hidden = false;
|
||
}
|
||
}
|
||
|
||
async function toggleVideo(card, song) {
|
||
try {
|
||
requireIdentity();
|
||
const video = card.querySelector("[data-video-player]");
|
||
if (video.paused) await playCardMedia(song.id, "video", "single");
|
||
else {
|
||
video.pause();
|
||
renderPlaylistControl();
|
||
}
|
||
} catch (error) {
|
||
showToast(error.message || "请点一下播放按钮继续");
|
||
}
|
||
}
|
||
|
||
function formatMediaTime(value) {
|
||
if (!Number.isFinite(value) || value < 0) return "0:00";
|
||
const minutes = Math.floor(value / 60);
|
||
const seconds = Math.floor(value % 60).toString().padStart(2, "0");
|
||
return `${minutes}:${seconds}`;
|
||
}
|
||
|
||
function updateAudioControls(card, audio) {
|
||
const toggle = card.querySelector("[data-audio-toggle]");
|
||
const label = toggle.querySelector("strong");
|
||
const progress = card.querySelector("[data-audio-progress]");
|
||
const duration = Number.isFinite(audio.duration) ? audio.duration : 0;
|
||
progress.max = String(duration);
|
||
progress.value = String(Math.min(audio.currentTime || 0, duration));
|
||
card.querySelector("[data-audio-current]").textContent = formatMediaTime(audio.currentTime);
|
||
card.querySelector("[data-audio-duration]").textContent = duration ? formatMediaTime(duration) : "--:--";
|
||
card.querySelector("[data-card-panel='audio']").classList.toggle("playing", !audio.paused);
|
||
label.textContent = audio.paused
|
||
? audio.currentTime > 0 && !audio.ended
|
||
? "继续播放音频"
|
||
: audio.ended
|
||
? "重新播放音频"
|
||
: "播放本首音频"
|
||
: "暂停音频";
|
||
toggle.setAttribute("aria-label", `${label.textContent} ${toggle.querySelector("small").textContent}`);
|
||
}
|
||
|
||
async function toggleAudio(card, song) {
|
||
try {
|
||
requireIdentity();
|
||
const audio = card.querySelector("[data-audio-player]");
|
||
if (audio.paused) await playCardMedia(song.id, "audio", "single");
|
||
else {
|
||
audio.pause();
|
||
renderPlaylistControl();
|
||
}
|
||
} catch (error) {
|
||
showToast(error.message || "请点一下播放按钮继续");
|
||
}
|
||
}
|
||
|
||
async function completePlayback(song, mediaType, player) {
|
||
try {
|
||
const playback = {
|
||
mode: appState.playback.mode,
|
||
mediaType: appState.playback.mediaType,
|
||
songId: appState.playback.songId,
|
||
playlistIndex: appState.playback.playlistIndex,
|
||
expected: appState.playback.expected,
|
||
};
|
||
const playId = await ensurePlaybackStarted(
|
||
song,
|
||
mediaType,
|
||
player.closest("[data-song-card]").querySelector("[data-card-status]"),
|
||
);
|
||
const result = await request("/api/playback/complete", {
|
||
method: "POST",
|
||
body: JSON.stringify({
|
||
device_id: appState.deviceId,
|
||
play_id: playId,
|
||
duration_seconds: Number.isFinite(player.duration) ? player.duration : null,
|
||
}),
|
||
});
|
||
delete appState.playRecords[playbackKey(song.id, mediaType)];
|
||
if (result.song_progress) Object.assign(song, result.song_progress);
|
||
if (result.round_award) appState.data.round_award = result.round_award;
|
||
appState.data.day[`${mediaType}_plays`] += result.already_completed ? 0 : 1;
|
||
elements.todayPlays.textContent = appState.data.day.video_plays + appState.data.day.audio_plays;
|
||
refreshRewardDisplays();
|
||
if (!result.already_completed) {
|
||
showToast(
|
||
appState.childMode
|
||
? `${song.title} 播放完成!`
|
||
: result.checkin_eligible
|
||
? `${song.title} 播放完成,小红花亮起来啦!`
|
||
: `${song.title} 预习完成,本次不会提前解锁小红花`,
|
||
);
|
||
}
|
||
if (result.round_ready && !appState.childMode) {
|
||
showToast("整轮大红花亮起来啦,快去亲手领取!");
|
||
}
|
||
if (playback.mode === "single" && playback.songId === song.id && playback.mediaType === mediaType) {
|
||
await playCardMedia(song.id, mediaType, "single", playback.playlistIndex);
|
||
} else if (playback.mode === "playlist" && mediaType === "audio") {
|
||
await startPlaylistAt(playback.playlistIndex + 1);
|
||
}
|
||
} catch (error) {
|
||
resetPlaybackMode();
|
||
showToast(error.message);
|
||
}
|
||
}
|
||
|
||
async function claimFlower(songId) {
|
||
try {
|
||
await request("/api/song-checkin", {
|
||
method: "POST",
|
||
body: JSON.stringify({
|
||
device_id: appState.deviceId,
|
||
song_id: songId,
|
||
study_date: appState.studyDate,
|
||
}),
|
||
});
|
||
await loadState({ recover: false, celebrateRecovered: false });
|
||
const song = appState.data.week.songs.find((item) => item.id === songId);
|
||
celebrate("获得一朵小红花!", `${song ? song.title : "这首歌"}认真听完啦,真棒!`);
|
||
} catch (error) {
|
||
showToast(error.message);
|
||
}
|
||
}
|
||
|
||
async function claimRoundFlower() {
|
||
try {
|
||
const result = await request("/api/round-checkin", {
|
||
method: "POST",
|
||
body: JSON.stringify({
|
||
device_id: appState.deviceId,
|
||
study_date: appState.studyDate,
|
||
}),
|
||
});
|
||
await loadState({ recover: false, celebrateRecovered: false });
|
||
celebrate("整轮大奖到手啦!", `第 ${result.round_number} 轮全部听完,送你一朵大红花!`);
|
||
} catch (error) {
|
||
showToast(error.message);
|
||
}
|
||
}
|
||
|
||
async function changeStudyDate(value, scrollToPlayer = false) {
|
||
pauseAll();
|
||
resetPlaybackMode();
|
||
appState.studyDate = value;
|
||
appState.viewWeek = null;
|
||
appState.playRecords = {};
|
||
await loadState();
|
||
if (scrollToPlayer) document.querySelector(".player-section").scrollIntoView({ behavior: "smooth" });
|
||
}
|
||
|
||
async function changeWeek(weekNumber, scrollToPlayer = false) {
|
||
const target = Math.max(1, Math.min(50, Number(weekNumber)));
|
||
const summary = appState.data.weeks.find((week) => week.number === target);
|
||
if (!summary) return;
|
||
pauseAll();
|
||
resetPlaybackMode();
|
||
appState.viewWeek = target;
|
||
appState.studyDate = target < appState.data.settings.current_week
|
||
? summary.start_date
|
||
: appState.data.today_date;
|
||
appState.playRecords = {};
|
||
await loadState();
|
||
if (scrollToPlayer) document.querySelector(".player-section").scrollIntoView({ behavior: "smooth" });
|
||
}
|
||
|
||
let celebrationTimer;
|
||
function celebrate(title, copy) {
|
||
clearTimeout(celebrationTimer);
|
||
elements.celebration.classList.remove("celebrating");
|
||
elements.celebrationTitle.textContent = title;
|
||
elements.celebrationCopy.textContent = copy;
|
||
elements.celebration.hidden = false;
|
||
void elements.celebration.offsetWidth;
|
||
elements.celebration.classList.add("celebrating");
|
||
celebrationTimer = window.setTimeout(() => {
|
||
elements.celebration.hidden = true;
|
||
elements.celebration.classList.remove("celebrating");
|
||
}, 3000);
|
||
}
|
||
|
||
let toastTimer;
|
||
function showToast(message) {
|
||
elements.toast.textContent = message;
|
||
elements.toast.classList.add("visible");
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(() => elements.toast.classList.remove("visible"), 2600);
|
||
}
|
||
|
||
elements.identityButton.addEventListener("click", () => showModal(elements.identityDialog));
|
||
elements.bottomSettingsButton.addEventListener("click", () => showModal(elements.settingsDialog));
|
||
elements.closeSettings.addEventListener("click", () => hideModal(elements.settingsDialog));
|
||
elements.previousWeek.addEventListener("click", () => changeWeek(appState.data.week.number - 1));
|
||
elements.nextWeek.addEventListener("click", () => changeWeek(appState.data.week.number + 1));
|
||
elements.currentWeek.addEventListener("click", () => changeWeek(appState.data.settings.current_week));
|
||
elements.playlistLoopButton.addEventListener("click", togglePlaylistLoop);
|
||
elements.weeklyLoopPlayer.addEventListener("play", () => {
|
||
if (appState.playback.mode === "weekly-loop") renderPlaylistControl();
|
||
});
|
||
elements.weeklyLoopPlayer.addEventListener("pause", () => {
|
||
if (appState.playback.mode === "weekly-loop") renderPlaylistControl();
|
||
});
|
||
elements.celebration.addEventListener("click", () => {
|
||
clearTimeout(celebrationTimer);
|
||
elements.celebration.hidden = true;
|
||
elements.celebration.classList.remove("celebrating");
|
||
});
|
||
elements.settingsForm.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
try {
|
||
await request("/api/settings", {
|
||
method: "POST",
|
||
body: JSON.stringify({
|
||
start_date: elements.startDate.value,
|
||
checkin_window_minutes: Number(elements.checkinWindow.value),
|
||
}),
|
||
});
|
||
setChildMode(elements.childMode.checked);
|
||
hideModal(elements.settingsDialog);
|
||
appState.studyDate = null;
|
||
appState.viewWeek = null;
|
||
showToast("学习设置已保存");
|
||
await loadState();
|
||
} catch (error) {
|
||
showToast(error.message);
|
||
}
|
||
});
|
||
|
||
function refreshRewardDisplays() {
|
||
if (!appState.data || appState.childMode) return;
|
||
appState.data.week.songs.forEach((song) => {
|
||
const card = elements.songCards.querySelector(`[data-song-card="${song.id}"]`);
|
||
const container = card ? card.querySelector("[data-song-reward]") : null;
|
||
if (!container) return;
|
||
container.innerHTML = songRewardMarkup(song);
|
||
bindRewardButtons(container);
|
||
});
|
||
renderRoundAward();
|
||
}
|
||
|
||
setInterval(refreshRewardDisplays, 15000);
|
||
applyChildMode();
|
||
loadState();
|