Files
speaking-practice/progress-sync.js
T
TTlaji 64e7cc5d8b
Deploy Speaking Practice / deploy (push) Successful in 44s
feat: sync learning progress to backend
2026-06-15 12:52:20 +08:00

168 lines
5.2 KiB
JavaScript

(function () {
const IS_BROWSER = typeof window !== "undefined";
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 {
currentTime: Number(progress.currentTime) || 0,
activeLineIndex: Number.isInteger(progress.activeLineIndex) && progress.activeLineIndex >= 0
? progress.activeLineIndex
: 0,
practicedLineIndexes: normalizeIndexList(progress.practicedLineIndexes),
difficultLineIndexes: normalizeIndexList(progress.difficultLineIndexes),
updatedAt: String(progress.updatedAt || ""),
};
}
function normalizeRemoteLearningState(payload = {}) {
const progress = {};
Object.entries(payload.progress || {}).forEach(([videoId, item]) => {
progress[String(videoId)] = normalizeProgress(item);
});
return {
favorites: normalizeIdList(payload.favorites),
progress,
};
}
function normalizeIdList(value) {
if (!Array.isArray(value)) return [];
return [...new Set(value.map((item) => String(item)).filter(Boolean))]
.sort((a, b) => Number(a) - Number(b));
}
function mergeProgress(localProgress = {}, remoteProgress = {}) {
const merged = {};
const videoIds = new Set([
...Object.keys(localProgress || {}),
...Object.keys(remoteProgress || {}),
]);
videoIds.forEach((videoId) => {
const local = normalizeProgress(localProgress[videoId]);
const remote = normalizeProgress(remoteProgress[videoId]);
const localTime = Date.parse(local.updatedAt || "") || 0;
const remoteTime = Date.parse(remote.updatedAt || "") || 0;
const newest = remoteTime >= localTime ? remote : local;
merged[String(videoId)] = {
...newest,
practicedLineIndexes: normalizeIndexList([
...local.practicedLineIndexes,
...remote.practicedLineIndexes,
]),
difficultLineIndexes: normalizeIndexList([
...local.difficultLineIndexes,
...remote.difficultLineIndexes,
]),
};
});
return merged;
}
function mergeLearningState(localUser, remoteState) {
const remote = normalizeRemoteLearningState(remoteState);
return {
favorites: normalizeIdList([...(localUser?.favorites || []), ...remote.favorites]),
progress: mergeProgress(localUser?.progress || {}, remote.progress),
};
}
function applyLearningStateToUser(user, learningState) {
if (!user) return null;
const normalized = normalizeRemoteLearningState(learningState);
user.favorites = normalized.favorites;
user.progress = normalized.progress;
return user;
}
function buildLearningStatePayload(user) {
return {
favorites: normalizeIdList(user?.favorites || []),
progress: normalizeRemoteLearningState({ progress: user?.progress || {} }).progress,
};
}
async function fetchRemoteLearningState(apiRequest) {
if (!apiRequest) return { favorites: [], progress: {} };
return normalizeRemoteLearningState(await apiRequest("/api/me/progress"));
}
async function saveRemoteLearningState(apiRequest, user) {
if (!apiRequest || !user) return { favorites: [], progress: {} };
return normalizeRemoteLearningState(await apiRequest("/api/me/progress", {
method: "PUT",
body: JSON.stringify(buildLearningStatePayload(user)),
}));
}
async function syncLearningState({ user, apiRequest, saveState }) {
if (!user || !apiRequest) return null;
const remote = await fetchRemoteLearningState(apiRequest);
const merged = mergeLearningState(user, remote);
applyLearningStateToUser(user, merged);
saveState?.();
const saved = await saveRemoteLearningState(apiRequest, user);
applyLearningStateToUser(user, mergeLearningState(user, saved));
saveState?.();
return saved;
}
function createProgressSyncQueue({ getUser, apiRequest, saveState, delay = 800 }) {
let timer = null;
let inFlight = null;
async function flush() {
if (timer) {
clearTimeout(timer);
timer = null;
}
const user = getUser?.();
if (!user || !apiRequest) return null;
inFlight = saveRemoteLearningState(apiRequest, user)
.then((saved) => {
applyLearningStateToUser(user, mergeLearningState(user, saved));
saveState?.();
return saved;
})
.catch(() => null)
.finally(() => {
inFlight = null;
});
return inFlight;
}
function schedule() {
if (timer) clearTimeout(timer);
timer = setTimeout(flush, delay);
}
return { schedule, flush, get inFlight() { return inFlight; } };
}
const api = {
applyLearningStateToUser,
buildLearningStatePayload,
createProgressSyncQueue,
fetchRemoteLearningState,
mergeLearningState,
normalizeProgress,
normalizeRemoteLearningState,
saveRemoteLearningState,
syncLearningState,
};
if (IS_BROWSER) {
window.SpeakingProgressSync = api;
}
if (typeof module !== "undefined" && module.exports) {
module.exports = api;
}
})();