// ==UserScript== // @name 学习通作业/考试/任务列表(优化版) // @namespace https://github.com/Cooanyh // @version 2.6.0 // @author 甜檸Cirtron (lcandy2); Modified by Coren // @description 【优化版】支持作业、考试与课程任务快速查看;提供深浅色主题、KPI概览、全局搜索、作业直达答题页、考试自动整卷预览、轻量/定时同步与配置导入导出。 // @license AGPL-3.0-or-later // @copyright lcandy2 All Rights Reserved // @copyright 2025, Coren (Modified based on original work) // @icon https://www.google.com/s2/favicons?sz=64&domain=chaoxing.com // @source https://github.com/Cooanyh/chaoxing-list // @match *://i.chaoxing.com/* // @match *://i.mooc.chaoxing.com/space/index* // @match *://i.mooc.chaoxing.com/settings* // @match *://mooc2-ans.chaoxing.com/* // @match *://mooc1-api.chaoxing.com/work/stu-work* // @match *://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode* // @match *://mooc1.chaoxing.com/exam-ans/exam/test/examcode/examlist* // @match *://mooc1.chaoxing.com/exam-ans/exam/test/reVersionTestStartNew* // @match *://mooc2-ans.chaoxing.com/exam-ans/exam/test/reVersionTestStartNew* // @match *://mooc1-api.chaoxing.com/exam-ans/exam/test/reVersionTestStartNew* // @match *://mobilelearn.chaoxing.com/widget/pcpick/stu/index* // @require https://cdn.jsdelivr.net/npm/vue@3.4.27/dist/vue.global.prod.js // @require data:application/javascript,%3Bwindow.Vue%3DVue%3B // @require https://cdn.jsdelivr.net/npm/vuetify@3.6.6/dist/vuetify.min.js // @require data:application/javascript,%3B // @grant GM_addStyle // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant unsafeWindow // @connect cdn.jsdelivr.net // @connect fonts.googlefonts.cn // @connect mooc1-api.chaoxing.com // @connect mobilelearn.chaoxing.com // @connect stat2-ans.chaoxing.com // @connect mooc2-ans.chaoxing.com // @connect mooc1.chaoxing.com // @connect i.chaoxing.com // @connect task.chaoxing.com // @run-at document-end // ==/UserScript== (function (vuetify, vue) { 'use strict'; // --- 开源内联 SVG 图标(Lucide 风格,MIT/ISC 几何路径,零外链依赖) --- const CX_ICON_PATHS = Object.freeze({ barChart: '', settings: '', sun: '', moon: '', contrast: '', zap: '', refreshCw: '', search: '', ban: '', xCircle: '', x: '', check: '', checkCircle: '', clock: '', bell: '', sparkles: '', bookOpen: '', fileText: '', clipboardList: '', book: '', messageSquare: '', alertTriangle: '', shield: '', upload: '', download: '', user: '' }); const cxSvgHtml = (name, size = 15) => { const body = CX_ICON_PATHS[name] || CX_ICON_PATHS.sparkles; return `${body}`; }; const cxIcon = (name, size = 15, extraClass = '') => vue.createVNode('span', { class: extraClass ? `cx-icon ${extraClass}` : 'cx-icon', 'aria-hidden': 'true', innerHTML: cxSvgHtml(name, size) }); // --- 核心工具函数 --- const wrapElements = () => { const wrapper = document.createElement("body"); wrapper.id = "chaoxing-assignment-wrapper"; while (document.body.firstChild) { wrapper.appendChild(document.body.firstChild); } document.body.appendChild(wrapper); wrapper.style.display = "none"; }; const ensureResponsiveViewport = () => { if (!document.head) return; let viewport = Array.from(document.head.querySelectorAll('meta[name]')) .find(meta => meta.getAttribute('name')?.trim().toLowerCase() === 'viewport'); if (!viewport) { viewport = document.createElement('meta'); viewport.setAttribute('name', 'viewport'); document.head.appendChild(viewport); } const directives = (viewport.getAttribute('content') || '') .split(',') .map(directive => directive.trim()) .filter(Boolean); const widthIndex = directives.findIndex(directive => /^width\s*=/i.test(directive)); if (widthIndex >= 0) directives[widthIndex] = 'width=device-width'; else directives.unshift('width=device-width'); if (!directives.some(directive => /^initial-scale\s*=/i.test(directive))) { directives.push('initial-scale=1'); } viewport.setAttribute('content', directives.join(', ')); }; const removeStyles = () => { removeHtmlStyle(); const styles = document.querySelectorAll("link[rel=stylesheet]"); styles.forEach((style) => { var _a; if ((_a = style.getAttribute("href")) == null ? void 0 : _a.includes("chaoxing")) { style.remove(); } }); }; const removeHtmlStyle = () => { const html = document.querySelector("html"); html == null ? void 0 : html.removeAttribute("style"); }; const keepRemoveHtmlStyle = () => { const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === "attributes" && mutation.attributeName === "style") { removeHtmlStyle(); } }); }); const html = document.querySelector("html"); html && observer.observe(html, { attributes: true }); }; const removeScripts = () => { const scripts = document.querySelectorAll("script"); scripts.forEach((script) => { var _a; if ((_a = script.getAttribute("src")) == null ? void 0 : _a.includes("chaoxing")) { script.remove(); } }); }; // --- 课程进度查询开关管理 --- const PROGRESS_ENABLED_KEY = 'chaoxing_progress_enabled'; const PROGRESS_DELAY_KEY = 'chaoxing_progress_delay'; const DEFAULT_PROGRESS_DELAY = 500; const MIN_PROGRESS_DELAY = 300; const MAX_PROGRESS_DELAY = 10000; const isProgressEnabled = () => { try { const stored = localStorage.getItem(PROGRESS_ENABLED_KEY); return stored === null ? true : stored === 'true'; } catch { return true; } }; const setProgressEnabled = (enabled) => { try { localStorage.setItem(PROGRESS_ENABLED_KEY, String(enabled)); console.log('[课程进度] 查询功能已', enabled ? '开启' : '关闭'); } catch (e) { console.error('[课程进度] 保存开关状态失败:', e); } }; const normalizeProgressDelay = (value) => { const parsed = Number.parseInt(value, 10); if (!Number.isFinite(parsed)) return DEFAULT_PROGRESS_DELAY; return Math.min(MAX_PROGRESS_DELAY, Math.max(MIN_PROGRESS_DELAY, parsed)); }; const getProgressDelay = () => { try { const stored = localStorage.getItem(PROGRESS_DELAY_KEY); return stored === null ? DEFAULT_PROGRESS_DELAY : normalizeProgressDelay(stored); } catch { return DEFAULT_PROGRESS_DELAY; } }; const setProgressDelay = (delay) => { const normalizedDelay = normalizeProgressDelay(delay); try { localStorage.setItem(PROGRESS_DELAY_KEY, String(normalizedDelay)); console.log('[课程进度] 请求延迟已设置为', normalizedDelay, 'ms'); } catch (e) { console.error('[课程进度] 保存延迟设置失败:', e); } return normalizedDelay; }; const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); const getCourseCompletionRate = (item) => { const rate = Number.parseFloat(String(item?.completionRate ?? '').replace('%', '')); return Number.isFinite(rate) ? rate : null; }; const hasCourseProgressTaskCount = item => item?.totalTasks !== null && item?.totalTasks !== undefined && item?.totalTasks !== ''; const compareEmptyProgressLast = (a, b) => { const emptyA = hasCourseProgressTaskCount(a) && Number(a.totalTasks) === 0; const emptyB = hasCourseProgressTaskCount(b) && Number(b.totalTasks) === 0; if (emptyA === emptyB) return 0; return emptyA ? 1 : -1; }; const compareCourseProgress = (a, b, direction = 1) => { const emptyOrder = compareEmptyProgressLast(a, b); if (emptyOrder) return emptyOrder; const rateA = getCourseCompletionRate(a); const rateB = getCourseCompletionRate(b); if (rateA === null && rateB !== null) return 1; if (rateA !== null && rateB === null) return -1; if (rateA !== null && rateB !== null && rateA !== rateB) return (rateA - rateB) * direction; return (a.courseName || '').localeCompare(b.courseName || '', 'zh-CN'); }; const compareCourseProgressByName = (a, b) => compareEmptyProgressLast(a, b) || (a.courseName || '').localeCompare(b.courseName || '', 'zh-CN'); // --- 忽略管理 - 使用 localStorage 持久化 --- const IGNORE_STORAGE_KEY = 'chaoxing_ignored_items'; const SETTINGS_STORAGE_KEY = 'chaoxing_list_settings_v1'; const DASHBOARD_CACHE_STORAGE_KEY = 'chaoxing_list_dashboard_cache_v1'; const DEADLINE_REMINDER_STORAGE_KEY = 'chaoxing_list_deadline_reminders_v1'; const SCHEDULED_SYNC_LOG_KEY = 'chaoxing_list_scheduled_sync_log_v1'; const DASHBOARD_CACHE_TTL = 5 * 60 * 1000; const LIGHT_REFRESH_MIN_INTERVAL = 2 * 60 * 1000; const DEADLINE_REMINDER_CHECK_INTERVAL = 30 * 1000; const DEADLINE_REMINDER_THRESHOLDS = Object.freeze([ { key: '12h', label: '12 小时', milliseconds: 12 * 60 * 60 * 1000 }, { key: '6h', label: '6 小时', milliseconds: 6 * 60 * 60 * 1000 }, { key: '3h', label: '3 小时', milliseconds: 3 * 60 * 60 * 1000 }, { key: '30m', label: '30 分钟', milliseconds: 30 * 60 * 1000 } ]); const COURSE_IGNORE_PREFIX = 'course__'; const PRESET_SYNC_TIMES = Object.freeze(['07:00', '08:00', '12:00', '18:00', '21:00', '22:00']); const DEFAULT_SETTINGS = Object.freeze({ ignoreEnabled: false, showOtherTasks: false, otherTaskTypes: [], deadlineReminderEnabled: true, deadlineBrowserNotificationEnabled: false, shortTermCacheEnabled: true, dynamicIgnoreRules: { homework: false, exam: false, activities: false, progress: false }, settingsHintSeen: false, courseIgnoreHintSeen: false, themeMode: 'system', tabBadgeCountMode: 'pending', defaultTaskFilter: 'pending', zeroTaskSuggestSeen: false, onboardingTourSeen: false, directHomeworkJumpEnabled: true, examAutoFullPreviewEnabled: true, lightRefreshEnabled: true, scheduledSyncEnabled: true, scheduledSyncTimes: ['08:00', '12:00', '18:00', '21:00'] }); const CORE_TASK_TYPES = new Set(['作业', '视频/任务点', 'AI实践', '任务引擎', '分组讨论', '分组任务', '测验', '随堂练习', '考试']); const OTHER_TASK_TYPES = ['签到', '问卷', '抢答', '通知', '投票', '直播', '评分', '拍照', '笔记', '其他任务']; const getSettings = () => { try { const parsed = JSON.parse(localStorage.getItem(SETTINGS_STORAGE_KEY) || '{}'); return { ...DEFAULT_SETTINGS, ...parsed, scheduledSyncTimes: Array.isArray(parsed?.scheduledSyncTimes) && parsed.scheduledSyncTimes.length ? parsed.scheduledSyncTimes : [...DEFAULT_SETTINGS.scheduledSyncTimes] }; } catch { return { ...DEFAULT_SETTINGS, scheduledSyncTimes: [...DEFAULT_SETTINGS.scheduledSyncTimes] }; } }; const EXAM_AUTO_PREVIEW_GM_KEY = 'chaoxing_list_exam_auto_preview_v1'; const syncExamAutoPreviewPreference = (enabled) => { try { if (typeof GM_setValue === 'function') { GM_setValue(EXAM_AUTO_PREVIEW_GM_KEY, Boolean(enabled)); } } catch {} }; const isExamAutoFullPreviewEnabled = () => { try { if (typeof GM_getValue === 'function') { const stored = GM_getValue(EXAM_AUTO_PREVIEW_GM_KEY, null); if (typeof stored === 'boolean') return stored; } } catch {} return Boolean(getSettings().examAutoFullPreviewEnabled); }; const saveSettings = (settings) => { const merged = { ...DEFAULT_SETTINGS, ...settings }; localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(merged)); syncExamAutoPreviewPreference(merged.examAutoFullPreviewEnabled); }; let vuetifyInstance = null; const HOST_THEME_STORAGE_KEY = 'chaoxing_list_host_theme_v1'; const resolveThemeMode = (mode = getSettings().themeMode) => { if (mode === 'dark' || mode === 'light') return mode; return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; }; const extractThemeOrigin = (originEvent) => { if (!originEvent) return null; try { const rect = originEvent.currentTarget?.getBoundingClientRect?.(); if (rect && (rect.width > 0 || rect.height > 0)) { return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; } if (typeof originEvent.clientX === 'number' && typeof originEvent.clientY === 'number' && (originEvent.clientX > 0 || originEvent.clientY > 0)) { return { x: originEvent.clientX, y: originEvent.clientY }; } } catch {} return null; }; const runCircularThemeTransition = (origin, commitFn, prevTheme = 'light') => { const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches; if (!origin || reduced || !document.body) { commitFn(); return; } try { const rootEl = document.querySelector?.('.chaoxing-list-root'); if (!rootEl || typeof rootEl.animate !== 'function') { commitFn(); return; } if (window.__cxThemeRevealAnim) { try { window.__cxThemeRevealAnim.cancel(); } catch {} window.__cxThemeRevealAnim = null; } const prevSnap = document.getElementById('cx-theme-old-snapshot'); if (prevSnap) prevSnap.remove(); const rootRect = rootEl.getBoundingClientRect?.() || { left: 0, top: 0, width: window.innerWidth || 1280 }; const vw = window.innerWidth || document.documentElement.clientWidth || 1280; const vh = window.innerHeight || document.documentElement.clientHeight || 800; const scrollX = window.scrollX || 0; const scrollY = window.scrollY || 0; const localX = origin.x - rootRect.left; const localY = origin.y - rootRect.top; const endRadius = Math.hypot(Math.max(origin.x, vw - origin.x), Math.max(origin.y, vh - origin.y)) + 24; const clone = rootEl.cloneNode(true); clone.querySelectorAll?.('style')?.forEach?.((s) => s.remove()); const scrollSelector = '.cx-panel-body, .cx-progress-body, .card-body, .detail-body, .cx-settings-main'; const origScrolls = rootEl.querySelectorAll?.(scrollSelector) || []; const cloneScrolls = clone.querySelectorAll?.(scrollSelector) || []; for (let i = 0; i < origScrolls.length && i < cloneScrolls.length; i++) { if (origScrolls[i].scrollTop) cloneScrolls[i].scrollTop = origScrolls[i].scrollTop; } clone.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`; clone.style.width = `${rootRect.width || vw}px`; clone.style.margin = '0'; clone.style.pointerEvents = 'none'; const snapHost = document.createElement('div'); snapHost.id = 'cx-theme-old-snapshot'; snapHost.setAttribute('data-cx-theme', prevTheme || 'light'); snapHost.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none;overflow:hidden;background:var(--cx-bg);color:var(--cx-text);'; snapHost.appendChild(clone); document.body.appendChild(snapHost); const savedStyles = { position: rootEl.style.position, zIndex: rootEl.style.zIndex, willChange: rootEl.style.willChange, backgroundColor: rootEl.style.backgroundColor, clipPath: rootEl.style.clipPath }; rootEl.style.position = 'relative'; rootEl.style.zIndex = '2'; rootEl.style.willChange = 'clip-path'; rootEl.style.backgroundColor = 'var(--cx-bg)'; commitFn(); let cleaned = false; const cleanup = () => { if (cleaned) return; cleaned = true; window.__cxThemeRevealAnim = null; snapHost.remove(); rootEl.style.position = savedStyles.position; rootEl.style.zIndex = savedStyles.zIndex; rootEl.style.willChange = savedStyles.willChange; rootEl.style.backgroundColor = savedStyles.backgroundColor; rootEl.style.clipPath = savedStyles.clipPath; }; const anim = rootEl.animate( [ { clipPath: `circle(0px at ${localX}px ${localY}px)` }, { clipPath: `circle(${endRadius}px at ${localX}px ${localY}px)` } ], { duration: 460, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' } ); window.__cxThemeRevealAnim = anim; if (anim && typeof anim.finished?.then === 'function') { anim.finished.then(cleanup).catch(cleanup); } setTimeout(cleanup, 520); } catch { commitFn(); } }; const broadcastHostThemeSync = (themeMode, resolved, animate = false, origin = null) => { try { if (window.parent && window.parent !== window) { window.parent.postMessage({ type: 'chaoxing-list-theme-sync', themeMode, resolved, animate, origin }, '*'); } } catch {} }; const applyThemeMode = (mode = getSettings().themeMode, originEvent = null) => { const resolved = resolveThemeMode(mode); const prevResolved = document.documentElement.getAttribute('data-cx-theme'); const origin = extractThemeOrigin(originEvent); const shouldAnimate = Boolean(origin && prevResolved && prevResolved !== resolved); const commit = () => { document.documentElement.setAttribute('data-cx-theme', resolved); if (vuetifyInstance?.theme?.global?.name) { vuetifyInstance.theme.global.name.value = resolved; } }; if (shouldAnimate) { runCircularThemeTransition(origin, commit, prevResolved); } else { commit(); } broadcastHostThemeSync(mode, resolved, shouldAnimate, origin); return resolved; }; const getScheduledSyncLog = () => { try { const parsed = JSON.parse(localStorage.getItem(SCHEDULED_SYNC_LOG_KEY) || '{}'); return parsed && typeof parsed === 'object' ? parsed : {}; } catch { return {}; } }; const saveScheduledSyncLog = (log) => { try { localStorage.setItem(SCHEDULED_SYNC_LOG_KEY, JSON.stringify(log)); } catch {} }; const isScheduledSyncDueNow = (settings) => { if (!settings?.scheduledSyncEnabled) return null; const times = Array.isArray(settings.scheduledSyncTimes) && settings.scheduledSyncTimes.length ? [...settings.scheduledSyncTimes].sort() : [...DEFAULT_SETTINGS.scheduledSyncTimes]; const now = new Date(); const todayKey = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`; const nowHHmm = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`; const log = getScheduledSyncLog(); const triggeredToday = Array.isArray(log[todayKey]) ? log[todayKey] : []; const dueSlots = times.filter(t => /^\d{2}:\d{2}$/.test(t) && t <= nowHHmm && !triggeredToday.includes(t)); if (!dueSlots.length) return null; return { todayKey, dueSlots, triggeredToday }; }; const markScheduledSyncTriggered = (todayKey, dueSlots, triggeredToday) => { const next = Array.from(new Set([...(triggeredToday || []), ...(dueSlots || [])])).sort(); saveScheduledSyncLog({ [todayKey]: next }); }; const exportScriptConfigJson = () => { let ignoredItems = {}; try { ignoredItems = JSON.parse(localStorage.getItem(IGNORE_STORAGE_KEY) || '{}'); } catch {} return JSON.stringify({ schema: 'chaoxing-list-config-v1', exportedAt: new Date().toISOString(), settings: getSettings(), ignoredItems, progressEnabled: isProgressEnabled(), progressDelay: getProgressDelay() }, null, 2); }; const importScriptConfigJson = (rawText) => { const parsed = JSON.parse(String(rawText || '').trim()); if (!parsed || typeof parsed !== 'object' || (!parsed.settings && !parsed.ignoredItems)) { throw new Error('无效的配置 JSON 格式'); } if (parsed.settings && typeof parsed.settings === 'object') { saveSettings({ ...getSettings(), ...parsed.settings }); } if (parsed.ignoredItems && typeof parsed.ignoredItems === 'object' && !Array.isArray(parsed.ignoredItems)) { localStorage.setItem(IGNORE_STORAGE_KEY, JSON.stringify(parsed.ignoredItems)); } if (typeof parsed.progressEnabled === 'boolean') setProgressEnabled(parsed.progressEnabled); if (parsed.progressDelay !== undefined) setProgressDelay(parsed.progressDelay); return getSettings(); }; const getDeadlineReminderState = () => { try { const stored = JSON.parse(localStorage.getItem(DEADLINE_REMINDER_STORAGE_KEY) || '{}'); if (!stored || typeof stored !== 'object' || !stored.tasks || typeof stored.tasks !== 'object') return { tasks: {} }; return { ...stored, tasks: Object.fromEntries(Object.entries(stored.tasks) .filter(([, entry]) => entry && typeof entry === 'object' && !Array.isArray(entry))) }; } catch { return { tasks: {} }; } }; const saveDeadlineReminderState = (state) => { try { localStorage.setItem(DEADLINE_REMINDER_STORAGE_KEY, JSON.stringify(state)); } catch (error) { console.warn('[临近提醒] 保存提醒状态失败:', error); } }; const getDashboardCache = () => { try { return JSON.parse(localStorage.getItem(DASHBOARD_CACHE_STORAGE_KEY) || '{}'); } catch { return {}; } }; const cleanupDashboardCache = () => { const cache = getDashboardCache(); const now = Date.now(); Object.keys(cache).forEach(key => { if (!cache[key] || !cache[key].savedAt || now - cache[key].savedAt > DASHBOARD_CACHE_TTL) delete cache[key]; }); try { localStorage.setItem(DASHBOARD_CACHE_STORAGE_KEY, JSON.stringify(cache)); } catch { /* localStorage 不可用时直接跳过 */ } return cache; }; const saveDashboardCache = (key, data) => { const cache = cleanupDashboardCache(); cache[key] = { savedAt: Date.now(), data }; try { localStorage.setItem(DASHBOARD_CACHE_STORAGE_KEY, JSON.stringify(cache)); } catch (error) { console.warn('[短时缓存] 写入失败', error); } }; const isOtherTask = (item) => item && item.isActivity && !CORE_TASK_TYPES.has(item.type); const isOtherTaskVisible = (item, settings) => !isOtherTask(item) || settings.showOtherTasks || (settings.otherTaskTypes || []).includes(item.type); // 动态忽略只接受明确的完成/过期标记,避免状态缺失或未知内容被误选。 const isExplicitlyCompletedAiPractice = (item) => item?.type === 'AI实践' && (item.finished === true || item.status === '已完成'); const isExplicitlyCompletedHomework = (item) => { if (!item) return false; if (item.type === 'AI实践') return isExplicitlyCompletedAiPractice(item); return item.uncommitted === false || item.finished === true || item.status === '已完成'; }; const isExplicitlyClosedExam = (item) => item?.finished === true || item?.expired === true; const isExplicitlyEndedActivity = (item) => item?.finished === true || item?.status === '已结束'; const isExplicitlyCompletedProgress = (item) => item?.isComplete === true || Number.parseInt(item?.completionRate, 10) >= 100; const getTaskEnginePlanSection = (item) => { if (!item?.taskEnginePlan) return 'activities'; if (item.type === '作业') return 'homework'; if (item.type === '考试') return 'exam'; return 'activities'; }; const isDynamicallyIgnored = (item, sectionType, settings) => { const rules = settings.dynamicIgnoreRules || {}; // 待办中的任务引擎子任务按实际类目应用规则,其余课程任务沿用课程任务规则。 if (sectionType === 'todo' && item.isActivity) sectionType = getTaskEnginePlanSection(item); switch (sectionType) { case 'homework': return !!rules.homework && isExplicitlyCompletedHomework(item); case 'exam': return !!rules.exam && isExplicitlyClosedExam(item); case 'activities': return !!rules.activities && isExplicitlyEndedActivity(item); case 'progress': return !!rules.progress && isExplicitlyCompletedProgress(item); default: return false; } }; const getCourseIgnoreKey = (item) => `${COURSE_IGNORE_PREFIX}${item.courseId || ''}__${item.clazzId || item.classId || ''}`; const isCourseIgnored = (item) => { const courseId = item && item.courseId; if (!courseId) return false; return !!getIgnoredItems()[getCourseIgnoreKey(item)]; }; const ignoreCourse = (course) => { const ignored = getIgnoredItems(); ignored[getCourseIgnoreKey(course)] = { title: course.courseName || course.course || '未知课程', course: course.courseName || course.course || '', sectionType: 'course', ignoredAt: Date.now(), courseId: course.courseId, clazzId: course.clazzId || course.classId }; saveIgnoredItems(ignored); }; const unignoreCourse = (course) => { const ignored = getIgnoredItems(); delete ignored[getCourseIgnoreKey(course)]; saveIgnoredItems(ignored); }; const getIgnoredItems = () => { try { return JSON.parse(localStorage.getItem(IGNORE_STORAGE_KEY) || '{}'); } catch { return {}; } }; const saveIgnoredItems = (items) => { localStorage.setItem(IGNORE_STORAGE_KEY, JSON.stringify(items)); }; // 生成唯一标识(包含板块前缀,防止不同板块同名项冲突) const getItemKey = (item, sectionType) => { const sec = sectionType || item._sectionType || 'unknown'; const id = item.courseId || item.examId || item.workId || item.activeId || ''; const title = item.title || item.courseName || ''; return `${sec}__${id}__${title}`; }; const isItemIgnored = (item, sectionType) => { const ignored = getIgnoredItems(); return isCourseIgnored(item) || !!ignored[getItemKey(item, sectionType)]; }; const ignoreItem = (item, sectionType) => { const ignored = getIgnoredItems(); const sec = sectionType || item._sectionType || 'unknown'; ignored[getItemKey(item, sectionType)] = { title: item.title || item.courseName || '', type: item.type || '', course: item.course || item.courseName || '', sectionType: sec, ignoredAt: Date.now() }; saveIgnoredItems(ignored); }; const unignoreItem = (item, sectionType) => { const ignored = getIgnoredItems(); delete ignored[getItemKey(item, sectionType)]; saveIgnoredItems(ignored); }; const ignoreItems = (items, sectionType) => { const ignored = getIgnoredItems(); items.forEach(item => { const sec = sectionType || item._sectionType || 'unknown'; ignored[getItemKey(item, sectionType)] = { title: item.title || item.courseName || '', type: item.type || '', course: item.course || item.courseName || '', sectionType: sec, ignoredAt: Date.now() }; }); saveIgnoredItems(ignored); }; const unignoreItems = (items, sectionType) => { const ignored = getIgnoredItems(); items.forEach(item => { delete ignored[getItemKey(item, sectionType)]; }); saveIgnoredItems(ignored); }; // 获取某板块的所有已忽略项(按 sectionType 过滤) const getIgnoredItemsBySection = (sectionType) => { const ignored = getIgnoredItems(); const result = []; for (const [key, val] of Object.entries(ignored)) { if ((val.sectionType || 'unknown') === sectionType) { result.push({ ...val, _key: key }); } } return result; }; const unignoreByKey = (key) => { const ignored = getIgnoredItems(); delete ignored[key]; saveIgnoredItems(ignored); }; const unignoreByKeys = (keys) => { const ignored = getIgnoredItems(); keys.forEach(k => delete ignored[k]); saveIgnoredItems(ignored); }; const urlDetection = () => { const url = window.location.href; const hash = window.location.hash; // 新版仪表盘检测 if (hash.includes("chaoxing-dashboard")) { return "dashboard"; } if (hash.includes("chaoxing-assignment-activities")) { return "activities"; } if (hash.includes("chaoxing-assignment-todo")) { return "todo"; } if (hash.includes("chaoxing-assignment")) { if (url.includes("mooc1-api.chaoxing.com/work/stu-work")) { return "homework"; } if (url.includes("mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode")) { return "exam"; } } if (url.includes("mooc1.chaoxing.com/exam-ans/exam/test/examcode/examlist")) { return "exam"; } if (url.includes("i.chaoxing.com")) { return "home"; } if (url.includes("i.mooc.chaoxing.com/space/index") || url.includes("i.mooc.chaoxing.com/settings")) { return "legacyHome"; } if (url.includes("/exam-ans/exam/test/reVersionTestStartNew")) { return "exam_take"; } if (url.includes("mobilelearn.chaoxing.com/widget/pcpick/stu/index") && hash.includes("active_")) { return "pcpick_auto"; } // 课程章节页面检测 if (url.includes("mooc2-ans.chaoxing.com/mooc2-ans/mycourse/studentcourse") || url.includes("mooc2-ans.chaoxing.com/mooc2-ans/mycourse/stu")) { return "course_chapter"; } }; const startHostDarkModeSync = () => { if (!document.getElementById('cx-host-dark-style')) { const hostStyle = document.createElement('style'); hostStyle.id = 'cx-host-dark-style'; hostStyle.textContent = ` html[data-cx-theme="dark"], html[data-cx-theme="dark"] body { color-scheme: dark !important; background: #0b0d12 !important; background-image: none !important; color: #f3f4f6 !important; } html[data-cx-theme="dark"] .box, html[data-cx-theme="dark"] .main, html[data-cx-theme="dark"] .main-box, html[data-cx-theme="dark"] .content, html[data-cx-theme="dark"] .wrap, html[data-cx-theme="dark"] .container, html[data-cx-theme="dark"] .layout, html[data-cx-theme="dark"] .page-wrap, html[data-cx-theme="dark"] .space_main, html[data-cx-theme="dark"] #space_main, html[data-cx-theme="dark"] .right, html[data-cx-theme="dark"] .right-box, html[data-cx-theme="dark"] .frame_box, html[data-cx-theme="dark"] .iframe-box, html[data-cx-theme="dark"] .main-right, html[data-cx-theme="dark"] .rightContent, html[data-cx-theme="dark"] .right_content, html[data-cx-theme="dark"] .wid100 { background: #0b0d12 !important; background-image: none !important; color: #f3f4f6 !important; border-color: rgba(255, 255, 255, 0.08) !important; } html[data-cx-theme="dark"] .header, html[data-cx-theme="dark"] .head, html[data-cx-theme="dark"] .top, html[data-cx-theme="dark"] .header-wrap, html[data-cx-theme="dark"] .top-header, html[data-cx-theme="dark"] #header, html[data-cx-theme="dark"] .space_top, html[data-cx-theme="dark"] .headerBox, html[data-cx-theme="dark"] .topbar, html[data-cx-theme="dark"] header, html[data-cx-theme="dark"] [data-cx-host-header="1"], html[data-cx-theme="dark"] [data-cx-host-header="1"] > div { background: #12151c !important; background-color: #12151c !important; background-image: none !important; color: #f3f4f6 !important; border-bottom: 1px solid rgba(255, 255, 255, 0.08) !important; box-shadow: none !important; } html[data-cx-theme="dark"] .left, html[data-cx-theme="dark"] .left-box, html[data-cx-theme="dark"] .leftnav, html[data-cx-theme="dark"] .left_nav, html[data-cx-theme="dark"] .leftSide, html[data-cx-theme="dark"] .left-side, html[data-cx-theme="dark"] #space_left, html[data-cx-theme="dark"] .space-left, html[data-cx-theme="dark"] .menubar, html[data-cx-theme="dark"] div.menubar[role="menubar"], html[data-cx-theme="dark"] .menu-list, html[data-cx-theme="dark"] .menu-list-box, html[data-cx-theme="dark"] ul.menu-list-ul, html[data-cx-theme="dark"] ul.funclistul, html[data-cx-theme="dark"] .side-bar, html[data-cx-theme="dark"] .sidebar, html[data-cx-theme="dark"] .nav-left, html[data-cx-theme="dark"] .leftMenu, html[data-cx-theme="dark"] .left-menu, html[data-cx-theme="dark"] .user-info, html[data-cx-theme="dark"] .userInfo, html[data-cx-theme="dark"] .personal-info, html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] { background: #12151c !important; background-color: #12151c !important; background-image: none !important; color: #d1d5db !important; border-color: rgba(255, 255, 255, 0.08) !important; box-shadow: none !important; } html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(div, section, nav, header, footer, ul, li, a, button, p, span) { background-color: transparent !important; background-image: none !important; border-color: rgba(255, 255, 255, 0.08) !important; box-shadow: none !important; } html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a, h1, h2, h3, h4, h5, p, span), html[data-cx-theme="dark"] .leftnav a, html[data-cx-theme="dark"] .left_nav a, html[data-cx-theme="dark"] .menubar a, html[data-cx-theme="dark"] .menu-list a, html[data-cx-theme="dark"] ul.menu-list-ul li a, html[data-cx-theme="dark"] ul.funclistul li a, html[data-cx-theme="dark"] .leftnav h3, html[data-cx-theme="dark"] .left_nav h3, html[data-cx-theme="dark"] .menubar h5, html[data-cx-theme="dark"] .menu-list h3, html[data-cx-theme="dark"] .user-info *, html[data-cx-theme="dark"] .personalName, html[data-cx-theme="dark"] .schoolName, html[data-cx-theme="dark"] .header a, html[data-cx-theme="dark"] .header span { color: #e5e7eb !important; } html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a, li):hover, html[data-cx-theme="dark"] .menubar a:hover, html[data-cx-theme="dark"] .menu-list li:hover, html[data-cx-theme="dark"] ul.menu-list-ul li a:hover, html[data-cx-theme="dark"] ul.funclistul li a:hover { background-color: rgba(255, 255, 255, 0.06) !important; color: #ffffff !important; } html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a.cur, a.active, a.on, a.selected, li.cur, li.active, li.on, li.selected, [class*="active"], [class*="selected"], [class*="cur"]), html[data-cx-theme="dark"] .menubar a.cur, html[data-cx-theme="dark"] .menubar a.active, html[data-cx-theme="dark"] .menu-list li.active, html[data-cx-theme="dark"] .menu-list li.cur, html[data-cx-theme="dark"] ul.menu-list-ul li.cur a, html[data-cx-theme="dark"] ul.funclistul li.cur a { background-color: rgba(96, 165, 250, 0.16) !important; color: #93c5fd !important; } html[data-cx-theme="dark"] [data-cx-host-sidebar="1"] :is(a.cur, a.active, li.cur, li.active, [class*="active"], [class*="cur"]) :is(span, h3, h5) { color: #93c5fd !important; } html[data-cx-theme="dark"] .space_opt a.manageBtn { background: #181c26 !important; color: #e5e7eb !important; border: 1px solid rgba(255, 255, 255, 0.12) !important; } html[data-cx-theme="dark"] .dropdown-menu, html[data-cx-theme="dark"] .user-dropdown, html[data-cx-theme="dark"] .pop { background: #171b24 !important; color: #f3f4f6 !important; border-color: rgba(255, 255, 255, 0.12) !important; } html[data-cx-theme="dark"] iframe { background: #0b0d12 !important; border-color: rgba(255, 255, 255, 0.08) !important; } html[data-cx-theme-switching="1"], html[data-cx-theme-switching="1"] body, html[data-cx-theme-switching="1"] .box, html[data-cx-theme-switching="1"] .main, html[data-cx-theme-switching="1"] .header, html[data-cx-theme-switching="1"] [data-cx-host-sidebar="1"], html[data-cx-theme-switching="1"] [data-cx-host-sidebar="1"] *, html[data-cx-theme-switching="1"] [data-cx-host-header="1"], html[data-cx-theme-switching="1"] [data-cx-host-header="1"] * { transition: background-color 360ms cubic-bezier(0.22, 1, 0.36, 1), color 360ms ease, border-color 360ms ease !important; } html[data-cx-theme="dark"] ::-webkit-scrollbar { width: 6px; height: 6px; } html[data-cx-theme="dark"] ::-webkit-scrollbar-track { background: transparent; } html[data-cx-theme="dark"] ::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.16); border-radius: 3px; } html[data-cx-theme="dark"] ::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.28); } `; (document.head || document.documentElement).appendChild(hostStyle); } const tagHostLayoutNodes = () => { try { const anchor = document.querySelector('div.menubar[role="menubar"], ul.menu-list-ul, ul.funclistul, #first1000000, #first_chaoxing_assignment_dashboard'); if (anchor) { let cur = anchor; let sidebarRoot = anchor; while (cur && cur.parentElement && cur.parentElement !== document.body && cur.parentElement !== document.documentElement) { const p = cur.parentElement; const rect = p.getBoundingClientRect?.(); if (rect && rect.width > 0 && rect.width < 360 && !p.querySelector?.('iframe')) { sidebarRoot = p; cur = p; } else { break; } } sidebarRoot?.setAttribute?.('data-cx-host-sidebar', '1'); } const winW = window.innerWidth || 1000; const candidates = document.querySelectorAll('body > div, body > header, .box > div, .main > div'); for (const el of candidates) { if (el.getAttribute('data-cx-host-header') === '1') continue; const r = el.getBoundingClientRect?.(); if (r && r.top <= 8 && r.height >= 36 && r.height <= 96 && r.width >= winW * 0.6 && !el.querySelector?.('iframe')) { el.setAttribute('data-cx-host-header', '1'); } } } catch {} }; tagHostLayoutNodes(); setTimeout(tagHostLayoutNodes, 400); setTimeout(tagHostLayoutNodes, 1500); if (typeof MutationObserver === 'function' && !window.__cxHostLayoutObserver) { let tagTimer = null; const obs = new MutationObserver(() => { if (tagTimer) return; tagTimer = setTimeout(() => { tagTimer = null; tagHostLayoutNodes(); }, 120); }); window.__cxHostLayoutObserver = obs; obs.observe(document.documentElement || document, { childList: true, subtree: true }); setTimeout(() => { try { obs.disconnect(); } catch {} }, 15000); } const readHostMode = () => { try { return localStorage.getItem(HOST_THEME_STORAGE_KEY) || 'system'; } catch { return 'system'; } }; const applyHostTheme = (resolved, animate = false) => { const prev = document.documentElement.getAttribute('data-cx-theme'); if (animate && prev && prev !== resolved) { document.documentElement.setAttribute('data-cx-theme-switching', '1'); clearTimeout(window.__cxHostThemeSwitchTimer); window.__cxHostThemeSwitchTimer = setTimeout(() => { document.documentElement.removeAttribute('data-cx-theme-switching'); }, 460); } document.documentElement.setAttribute('data-cx-theme', resolved); }; applyHostTheme(resolveThemeMode(readHostMode())); window.matchMedia?.('(prefers-color-scheme: dark)')?.addEventListener?.('change', () => { if (readHostMode() === 'system') applyHostTheme(resolveThemeMode('system')); }); if (!window.__cxHostThemeSyncAttached) { window.__cxHostThemeSyncAttached = true; window.addEventListener('message', (event) => { const payload = event?.data; if (!payload || payload.type !== 'chaoxing-list-theme-sync') return; if (event.origin && !event.origin.includes('chaoxing.com')) return; if (payload.themeMode) { try { localStorage.setItem(HOST_THEME_STORAGE_KEY, payload.themeMode); } catch {} } const resolved = (payload.resolved === 'dark' || payload.resolved === 'light') ? payload.resolved : resolveThemeMode(payload.themeMode || readHostMode()); applyHostTheme(resolved, Boolean(payload.animate), payload.origin || null); }); } }; const fixCssConflict = () => { const style = document.createElement('style'); style.textContent = ` .menu-list .label-item h3 { font-size: 14px !important; margin: 0 !important; line-height: 24px !important; font-weight: normal !important; } div.menubar a h5 { font-size: 14px !important; margin: 0 !important; line-height: normal !important; font-weight: bold !important; white-space: nowrap !important; } .leftnav h3, .left_nav h3, .funclistul h3, .user-info h3, div[class*="menu"] h3, div[class*="nav"] h3, #space_left h3, .space-left h3 { font-size: 14px !important; } .space_opt .manageBtn { font-size: 12px !important; line-height: 24px !important; height: auto !important; width: auto !important; padding: 0 10px !important; margin: 0 5px !important; display: inline-block !important; box-sizing: content-box !important; text-align: center !important; white-space: nowrap !important; border-radius: 4px !important; } .space_opt a.manageBtn { text-decoration: none !important; color: #333 !important; } `; document.head.appendChild(style); }; const createMenuItem = (id, text, iconClass, targetUrl, insertFunc) => { const url = targetUrl; const menubarElement = document.querySelector('div.menubar[role="menubar"]'); if (menubarElement) { const a = document.createElement("a"); a.setAttribute("role", "menuitem"); a.setAttribute("tabindex", "-1"); a.id = `first${id}`; a.setAttribute("onclick", `setUrl('${id}','${url}',this,'0','${text}')`); a.setAttribute("dataurl", url); const icon = document.createElement("span"); icon.className = `icon-space ${iconClass}`; a.appendChild(icon); const h5 = document.createElement("h5"); h5.title = text; h5.innerHTML = `${text}`; a.appendChild(h5); const arrow = document.createElement("span"); arrow.className = "arrow icon-uniE900"; a.appendChild(arrow); if (insertFunc) insertFunc(menubarElement, a); else menubarElement.prepend(a); } }; const createMenuItemNew = (id, text, iconClass, targetUrl, insertFunc) => { const menuListElement = document.querySelector("ul.menu-list-ul"); if (menuListElement) { const li = document.createElement("li"); li.setAttribute("level", "1"); li.setAttribute("table-type", "1"); li.setAttribute("data-id", `chaoxing-assignment-${id}`); const div = document.createElement("div"); div.className = "label-item"; div.setAttribute("role", "menuitem"); div.setAttribute("level", "1"); div.setAttribute("tabindex", "-1"); div.setAttribute("name", text); div.setAttribute("id", `first_chaoxing_assignment_${id}`); div.setAttribute("onclick", `setUrl('chaoxing-assignment-${id}','${targetUrl}',this,'0','${text}')`); div.setAttribute("dataurl", targetUrl); const icon = document.createElement("span"); icon.className = `icon-space ${iconClass}`; div.appendChild(icon); const h3 = document.createElement("h3"); h3.title = text; h3.textContent = text; div.appendChild(h3); const arrow = document.createElement("span"); arrow.className = "slide-arrow icon-h-arrow-l hide"; div.appendChild(arrow); li.appendChild(div); li.appendChild(Object.assign(document.createElement("div"), { className: "school-level" })).appendChild(document.createElement("ul")); if (insertFunc) insertFunc(menuListElement, li); else menuListElement.prepend(li); } }; const createMenuItemLegacy = (id, text, iconClass, targetUrl) => { const list = document.querySelector("ul.funclistul"); if (list && !document.querySelector(`#li_chaoxing-assignment-${id}`)) { const li = document.createElement("li"); li.id = `li_chaoxing-assignment-${id}`; li.className = ''; li.innerHTML = `${text}`; list.prepend(li); } }; // URL 常量 const URL_HOMEWORK = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-assignment'; const URL_EXAM = 'https://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode#chaoxing-assignment'; const URL_TODO = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-assignment-todo'; const URL_ACTIVITIES = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-assignment-activities'; const URL_DASHBOARD = 'https://mooc1-api.chaoxing.com/work/stu-work#chaoxing-dashboard'; const API_COURSE_LIST = 'https://mooc1-api.chaoxing.com/mycourse/backclazzdata?view=json&mcode='; const initMenus = () => { // 只创建单个"学习仪表盘"入口 if (document.querySelector('div.menubar[role="menubar"]')) { if (!document.querySelector('#first1000000')) { createMenuItem('1000000', '学习仪表盘', 'icon-bj', URL_DASHBOARD); } } else if (document.querySelector("ul.menu-list-ul")) { if (!document.querySelector('#first_chaoxing_assignment_dashboard')) { createMenuItemNew('dashboard', '学习仪表盘', 'icon-bj', URL_DASHBOARD); } } else if (document.querySelector("ul.funclistul")) { createMenuItemLegacy('dashboard', '学习仪表盘', 'zne_bj_icon', URL_DASHBOARD); } }; const getDashboardMenuItem = () => document.querySelector( '#first1000000, #first_chaoxing_assignment_dashboard, #li_chaoxing-assignment-dashboard a, a[href*="chaoxing-dashboard"]' ); const startDashboardMenuBootstrap = () => { let stopped = false; let autoOpenScheduled = false; let observerTimer = null; const stop = () => { if (stopped) return; stopped = true; observer.disconnect(); clearInterval(pollTimer); clearTimeout(stopTimer); if (observerTimer !== null) clearTimeout(observerTimer); window.removeEventListener('pagehide', stop); }; const ensureMenu = () => { if (stopped) return; initMenus(); if (autoOpenScheduled) return; const menuItem = getDashboardMenuItem(); if (!menuItem) return; autoOpenScheduled = true; setTimeout(() => { const currentMenuItem = getDashboardMenuItem(); if (currentMenuItem?.isConnected) { currentMenuItem.click(); console.log('[脚本] 自动切换到学习仪表盘'); } }, 500); }; const scheduleEnsureMenu = () => { if (stopped || observerTimer !== null) return; observerTimer = setTimeout(() => { observerTimer = null; ensureMenu(); }, 100); }; const observer = new MutationObserver(scheduleEnsureMenu); observer.observe(document.documentElement || document, { childList: true, subtree: true }); const pollTimer = setInterval(ensureMenu, 1000); const stopTimer = setTimeout(stop, 60000); window.addEventListener('pagehide', stop, { once: true }); ensureMenu(); }; // 新标签页打开的菜单项创建函数 const createMenuItemNewTab = (id, text, iconClass, targetUrl) => { const menubarElement = document.querySelector('div.menubar[role="menubar"]'); if (menubarElement) { const a = document.createElement("a"); a.setAttribute("role", "menuitem"); a.setAttribute("tabindex", "-1"); a.id = `first${id}`; a.href = targetUrl; a.target = "_blank"; a.style.cursor = "pointer"; const icon = document.createElement("span"); icon.className = `icon-space ${iconClass}`; a.appendChild(icon); const h5 = document.createElement("h5"); h5.title = text; h5.innerHTML = `${text}`; a.appendChild(h5); const arrow = document.createElement("span"); arrow.className = "arrow icon-uniE900"; a.appendChild(arrow); menubarElement.prepend(a); } }; const createMenuItemNewTabNew = (id, text, iconClass, targetUrl) => { const menuListElement = document.querySelector("ul.menu-list-ul"); if (menuListElement) { const li = document.createElement("li"); li.setAttribute("level", "1"); li.setAttribute("table-type", "1"); li.setAttribute("data-id", `chaoxing-assignment-${id}`); const div = document.createElement("div"); div.className = "label-item"; div.setAttribute("role", "menuitem"); div.setAttribute("level", "1"); div.setAttribute("tabindex", "-1"); div.setAttribute("name", text); div.setAttribute("id", `first_chaoxing_assignment_${id}`); div.style.cursor = "pointer"; div.onclick = () => window.open(targetUrl, '_blank'); const icon = document.createElement("span"); icon.className = `icon-space ${iconClass}`; div.appendChild(icon); const h3 = document.createElement("h3"); h3.title = text; h3.textContent = text; div.appendChild(h3); const arrow = document.createElement("span"); arrow.className = "slide-arrow icon-h-arrow-l hide"; div.appendChild(arrow); li.appendChild(div); li.appendChild(Object.assign(document.createElement("div"), { className: "school-level" })).appendChild(document.createElement("ul")); menuListElement.prepend(li); } }; const createMenuItemLegacyNewTab = (id, name, iconClass, url) => { const list = document.querySelector("ul.funclistul"); if (list && !document.querySelector(`#first_chaoxing_assignment_${id}`)) { const existingItem = list.querySelector('li a'); if (existingItem) { const li = document.createElement("li"); li.id = `first_chaoxing_assignment_${id}`; const a = document.createElement("a"); a.href = url; a.target = "_blank"; a.title = name; const span = document.createElement("span"); span.className = iconClass; a.appendChild(span); a.appendChild(document.createTextNode(name)); li.appendChild(a); list.prepend(li); } } }; // --- 课程任务汇总功能 --- // GM_xmlhttpRequest 封装为 Promise const gmFetch = (url, options = {}) => { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: options.method || 'GET', url: url, headers: options.headers || {}, data: options.data, responseType: options.responseType || 'text', timeout: options.timeout || 15000, onload: (response) => { if (response.status >= 200 && response.status < 300) { resolve(response); } else { const error = new Error(`Request failed: ${response.status}`); error.status = response.status; reject(error); } }, onerror: (error) => reject(error), ontimeout: () => reject(new Error('Request timeout')) }); }); }; const gmFetchWithRetry = async (url, options = {}, retries = 1) => { let attempt = 0; while (true) { try { return await gmFetch(url, options); } catch (error) { const status = Number(error?.status); const retryable = !Number.isFinite(status) || status === 0 || status === 408 || status === 429 || status >= 500; if (!retryable || attempt >= retries) throw error; await delay(status === 429 ? 1200 : 350 * (attempt + 1)); attempt += 1; } } }; // 获取所有课程列表 const fetchCourseList = async () => { let skippedCourseCount = 0; let wasEmpty = false; try { console.log('[课程任务] 正在获取课程列表:', API_COURSE_LIST); const response = await gmFetchWithRetry(API_COURSE_LIST); const data = JSON.parse(response.responseText); if (!data || !Array.isArray(data.channelList)) throw new Error('课程列表响应格式无法识别'); console.log('[课程任务] 收到课程栏位:', data.channelList.length); wasEmpty = data.channelList.length === 0; const courses = []; for (const channel of data.channelList) { if (!channel || typeof channel !== 'object') { skippedCourseCount += 1; continue; } const content = channel.content; if (!content) continue; // 检查是否是课程(有 course 对象) if (content.course) { if (!Array.isArray(content.course.data)) { skippedCourseCount += 1; continue; } if (content.course.data.length === 0) continue; const courseInfo = content.course.data[0]; // 尝试多种方式获取 clazzId let clazzId = ''; const clazzData = content.clazz?.data; if (Array.isArray(clazzData) && clazzData[0]?.id != null) { clazzId = String(clazzData[0].id).trim(); } else if (content.id != null && String(content.id).trim()) { clazzId = String(content.id).trim(); } else if (channel.key != null && String(channel.key).trim()) { clazzId = String(channel.key).trim(); } // 只添加有 clazzId 的课程(API 需要此参数) const courseId = courseInfo?.id == null ? '' : String(courseInfo.id).trim(); if (courseInfo && courseId && clazzId && courseId !== 'undefined' && clazzId !== 'undefined') { courses.push({ courseId, courseName: courseInfo.name || '未知课程', clazzId: clazzId, cpi: String(content.cpi || ''), teacherName: courseInfo.teacherfactor || '' }); console.log(`[课程任务] 解析课程: ${courseInfo.name}, clazzId=${clazzId}`); } else { skippedCourseCount += 1; console.warn(`[课程任务] 跳过字段不完整的课程栏位: ${courseInfo?.name || '未知课程'}`); } } } if (data.channelList.length > 0 && courses.length === 0) { throw new Error('课程列表有数据,但没有识别出可读取的课程'); } console.log('[课程任务] 最终解析到课程:', courses.length, '个'); courseListDiagnostics.set(courses, { skippedCourseCount, wasEmpty }); return courses; } catch (error) { console.error('[课程任务] 获取课程列表失败:', error?.message || error); throw error; } }; const getArrayByPaths = (value, paths) => { for (const path of paths) { let current = value; for (const key of path) current = current?.[key]; if (Array.isArray(current)) return current; } return null; }; const extractClassroomActivityList = (payload) => { const list = getArrayByPaths(payload, [ ['data', 'activeList'], ['data', 'list'], ['data', 'data'], ['activeList'], ['data'], [] ]); if (list) { const items = list.filter(item => item && typeof item === 'object' && !Array.isArray(item)); return { items, invalidCount: list.length - items.length }; } throw new Error('课堂活动响应格式无法识别'); }; const extractTaskEngineItems = (payload) => { if (payload?.success === false || payload?.result === false) { throw new Error('任务引擎接口返回失败'); } const list = getArrayByPaths(payload, [ ['data'], ['data', 'data'], ['data', 'list'], ['data', 'taskList'], ['data', 'taskListList'], ['data', 'tasks'], ['data', 'activeList'], ['data', 'records'], ['list'], ['taskList'], ['taskListList'], ['tasks'], ['activeList'], ['records'], [] ]); if (list) { const items = list.filter(item => item && typeof item === 'object' && !Array.isArray(item)); return { items, invalidCount: list.length - items.length }; } throw new Error('任务引擎响应格式无法识别'); }; const courseActivityIssues = new Map(); const courseActivityInFlight = new Map(); const courseListDiagnostics = new WeakMap(); const getCourseActivityKey = (course) => `${course?.courseId || ''}__${course?.clazzId || course?.classId || ''}`; const clearCourseActivityIssues = () => courseActivityIssues.clear(); const recordCourseActivityIssue = (course, source) => { const key = getCourseActivityKey(course); const sources = courseActivityIssues.get(key) || new Set(); sources.add(source); courseActivityIssues.set(key, sources); }; const getCourseActivityIssues = (courses, diagnosticsSource = courses) => { const courseListResult = Array.isArray(diagnosticsSource) ? (courseListDiagnostics.get(diagnosticsSource) || (Array.isArray(courses) ? courseListDiagnostics.get(courses) : null)) : (Array.isArray(courses) ? courseListDiagnostics.get(courses) : null); const issues = (courses || []).flatMap(course => { const sources = [...(courseActivityIssues.get(getCourseActivityKey(course)) || [])]; return sources.length ? [{ courseName: course.courseName, sources }] : []; }); for (let i = 0; i < (courseListResult?.skippedCourseCount || 0); i += 1) { issues.push({ courseName: '未识别课程', sources: ['课程列表'] }); } if (courseListResult?.wasEmpty) issues.push({ courseName: '课程列表', sources: ['课程列表'] }); return issues; }; const formatCourseActivityIssues = (issues) => { if (!issues?.length) return ''; if (issues.some(issue => issue.sources?.includes('课程列表'))) { const affectedCourses = issues.filter(issue => !issue.sources?.includes('课程列表')).length; const detail = affectedCourses ? `另有 ${affectedCourses} 门课程读取失败。` : ''; return `课程列表为空或部分课程未能识别,待办任务可能遗漏。${detail}请刷新重试。`; } const sources = [...new Set(issues.flatMap(issue => issue.sources || []))].join('、'); return `读取不完整:${issues.length} 门课程的${sources || '课程任务'}接口或数据格式异常,列表可能遗漏。请刷新重试。`; }; const normalizeTaskType = (item) => { const typeMap = { 0: '签到', 2: '签到', 4: '抢答', 5: '分组讨论', 6: '投票', 14: '问卷', 17: '直播', 23: '随堂练习', 35: '分组任务', 42: '随堂练习', 43: '评分', 45: '拍照', 47: '作业', 64: '笔记' }; const title = `${item.nameOne || item.name || item.title || ''}`; if (/AI\s*实践|AI\s*评价/i.test(title)) return 'AI实践'; if (/分组/.test(title) && /讨论/.test(title)) return '分组讨论'; if (/考试/.test(title)) return '考试'; if (/测验|练习/.test(title)) return '测验'; return typeMap[item.activeType] || typeMap[item.type] || '其他任务'; }; const getTaskEngineLink = (taskId, course) => taskId ? `https://task.chaoxing.com/api/v1/middlePageApi/jumpStudyPlanList?taskId=${encodeURIComponent(taskId)}&moocClassId=${encodeURIComponent(course.clazzId)}` : ''; const normalizeTaskEnginePlanType = (plan) => { const typeName = `${plan.planTypeName || ''}`.trim(); const searchable = `${typeName} ${plan.name || ''}`; if (/AI\s*实践|AI\s*评价|AI\s*对话/i.test(searchable)) return 'AI实践'; if (/分组/.test(searchable) && /(任务|作业)/.test(searchable)) return '分组任务'; if (/讨论/.test(searchable)) return '分组讨论'; if (/考试/.test(searchable)) return '考试'; if (/作业/.test(searchable)) return '作业'; if (/随堂练习/.test(searchable)) return '随堂练习'; if (/测验|自测|练习/.test(searchable)) return '测验'; if (/签到/.test(searchable)) return '签到'; if (/问卷/.test(searchable)) return '问卷'; if (/抢答/.test(searchable)) return '抢答'; if (/投票/.test(searchable)) return '投票'; if (/直播/.test(searchable)) return '直播'; if (/评分/.test(searchable)) return '评分'; if (/拍照/.test(searchable)) return '拍照'; if (/笔记/.test(searchable)) return '笔记'; if (/课程|章节|知识点|视频|文档|音频|阅读/.test(searchable)) return '视频/任务点'; const typeMap = { 0: '视频/任务点', 1: '视频/任务点', 4: '作业', 5: '考试', 8: '视频/任务点', 9: '签到', 10: '视频/任务点', 11: '视频/任务点', 13: '测验', 14: '分组讨论', 15: 'AI实践', 17: '测验', 22: '视频/任务点' }; return typeMap[plan.planType] || '其他任务'; }; const normalizeTaskEngineSummaryItem = (item, course) => { const planCount = Number(item.planCount) || 0; const planFinishCount = Number(item.planFinishCount) || 0; const studyProgress = Number(item.taskStudyProgress) || 0; const qualifyStatus = `${item.userTaskQualifyStatus || ''}`; const isFinished = qualifyStatus === '已达标' || qualifyStatus === '已完成' || studyProgress >= 1 || (planCount > 0 && planFinishCount >= planCount); const taskId = item.id ? String(item.id) : ''; return { activeId: taskId ? `task-engine-${taskId}` : `task-engine-${course.courseId}-${item.name || ''}`, taskId, title: item.name || '未命名任务引擎任务', type: '任务引擎', status: isFinished ? '已结束' : '进行中', time: item.lastStudyDateStr || item.createDate || '', endTime: '', courseName: course.courseName, course: course.courseName, courseId: course.courseId, clazzId: course.clazzId, cpi: course.cpi, finished: isFinished, ongoing: !isFinished, activeType: 'task-engine', taskEngine: true, taskEnginePlan: false, taskLink: getTaskEngineLink(taskId, course), progressText: planCount > 0 ? `${planFinishCount}/${planCount}` : '', isActivity: true }; }; const extractTaskEngineUserId = (response) => { const html = `${response?.responseText || ''}`; const htmlMatch = html.match(/(?:const|let|var)\s+eTaskUserId\s*=\s*["']([^"']+)["']/); if (htmlMatch) return htmlMatch[1]; try { return new URL(response?.finalUrl || '').searchParams.get('encryTaskUserId') || ''; } catch { return ''; } }; const parseTaskEngineDate = (value) => { if (value === null || value === undefined || value === '') return NaN; if (typeof value === 'number') return Number.isFinite(value) ? value : NaN; const text = normalizeTaskEngineDateText(value); // 平台详情页常返回“09-20 20:00”这种省略年份的日期。 // Date.parse 会把它误解析为 2001 年,进而把当前年度的任务判为已过期。 const shortDateMatch = text.match(/^(\d{1,2})-(\d{1,2})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/); if (shortDateMatch) { const [, monthText, dayText, hourText = '0', minuteText = '0', secondText = '0'] = shortDateMatch; const now = new Date(); const year = now.getFullYear(); const parsed = new Date( year, Number(monthText) - 1, Number(dayText), Number(hourText), Number(minuteText), Number(secondText) ); if ( parsed.getFullYear() === year && parsed.getMonth() === Number(monthText) - 1 && parsed.getDate() === Number(dayText) ) return parsed.getTime(); } return Date.parse(text.replace(/-/g, '/')); }; const parseTaskDeadlineText = (value) => { if (typeof value === 'number') { if (!Number.isFinite(value) || value <= 0) return NaN; return value < 1e12 ? value * 1000 : value; } const text = `${value || ''}`.trim(); if (!text) return NaN; if (/^\d{13}$/.test(text)) return Number(text); if (/^\d{10}$/.test(text)) return Number(text) * 1000; if (/^\d{4}-\d{2}-\d{2}T/i.test(text)) { const isoTimestamp = Date.parse(text); if (Number.isFinite(isoTimestamp)) return isoTimestamp; } const datePattern = '(?:\\d{4}[-/.年]\\d{1,2}[-/.月]\\d{1,2}日?|\\d{1,2}[-/.月]\\d{1,2}日?)'; const timePattern = '\\d{1,2}:\\d{2}(?::\\d{2})?'; const rangeMatch = text.match(new RegExp(`(${datePattern})\\s+(${timePattern})\\s*(?:至|到|[-–—~~])\\s*(?:(${datePattern})\\s*)?(${timePattern})`)); if (rangeMatch) { return parseTaskEngineDate(`${rangeMatch[3] || rangeMatch[1]} ${rangeMatch[4]}`); } const dateTimePattern = new RegExp(`${datePattern}(?:\\s+${timePattern})?`, 'g'); const dateMatches = Array.from(text.matchAll(dateTimePattern), match => match[0]); if (!dateMatches.length) return NaN; const lastDate = dateMatches[dateMatches.length - 1].trim(); const hasTime = new RegExp(`${timePattern}`).test(lastDate); return parseTaskEngineDate(hasTime ? lastDate : `${lastDate} 23:59:59`); }; const getTaskDeadlineTimestamp = (item) => { // info 是展示字段,课程任务可能在这里写“进度 1/2”,不能当作截止日期解析。 const candidates = [item?.endTimeTimestamp, item?.deadlineAt, item?.deadline, item?.endTime, item?.timeRange, item?.timeLeft, item?.leftTime]; for (const candidate of candidates) { const timestamp = parseTaskDeadlineText(candidate); if (Number.isFinite(timestamp)) return timestamp; } return NaN; }; const parseTaskRemainingMinutes = (value) => { const text = `${value || ''}`; if (!text) return Infinity; if (/过期|已结束|已截止/.test(text)) return -1; let minutes = 0; let matched = false; const dayMatch = text.match(/(\d+)\s*天/); const hourMatch = text.match(/(\d+)\s*小时/); const minuteMatch = text.match(/(\d+)\s*分/); const secondMatch = text.match(/(\d+)\s*秒/); if (dayMatch) { minutes += Number(dayMatch[1]) * 24 * 60; matched = true; } if (hourMatch) { minutes += Number(hourMatch[1]) * 60; matched = true; } if (minuteMatch) { minutes += Number(minuteMatch[1]); matched = true; } if (secondMatch) { minutes += Number(secondMatch[1]) / 60; matched = true; } return matched ? minutes : Infinity; }; const getTaskRemainingMinutes = (item, now = Date.now()) => { const deadlineAt = getTaskDeadlineTimestamp(item); if (Number.isFinite(deadlineAt)) return (deadlineAt - now) / 60000; return parseTaskRemainingMinutes(item?.leftTime || item?.timeLeft || item?.info || ''); }; const compareTodoItemsByDeadline = (a, b, direction = 1) => { const remainingA = getTaskRemainingMinutes(a); const remainingB = getTaskRemainingMinutes(b); if (remainingA === remainingB) return 0; if (!Number.isFinite(remainingA)) return 1; if (!Number.isFinite(remainingB)) return -1; return (remainingA - remainingB) * direction; }; const getTaskReminderKey = (item) => { const identity = [item?.workId, item?.examId, item?.planId, item?.taskId, item?.activeId] .filter(value => value !== null && value !== undefined && value !== '') .join(':'); const classId = item?.clazzId || item?.classId || ''; const fallback = `${item?.course || item?.courseName || ''}|${item?.title || ''}`; return [item?.type || '任务', item?.courseId || '', classId, identity || fallback].join('|'); }; const isTaskEnginePlanFinished = (plan) => plan.isFinish === true || Number(plan.isFinish) === 1 || Number(plan.planUser?.finish) === 1 || Number(plan.score?.completed) === 1; const taskEngineDetailCache = new Map(); const TASK_ENGINE_DEADLINE_TYPES = new Set([ '作业', '考试', '测验', '随堂练习', '分组任务', '分组讨论', '签到', '问卷', '抢答', '投票', '直播', 'AI实践' ]); const TASK_ENGINE_DETAIL_HOSTS = new Set([ 'mooc1.chaoxing.com', 'mooc2-ans.chaoxing.com', 'mobilelearn.chaoxing.com', 'i.chaoxing.com', 'task.chaoxing.com' ]); const htmlToTaskEngineText = (html) => { const source = `${html || ''}`; if (typeof DOMParser !== 'undefined') { const doc = new DOMParser().parseFromString(source, 'text/html'); return `${doc.body?.textContent || ''}`.replace(/\s+/g, ' ').trim(); } return source .replace(//gi, ' ') .replace(//gi, ' ') .replace(/<[^>]+>/g, ' ') .replace(/ | /gi, ' ') .replace(/&/gi, '&') .replace(/\s+/g, ' ') .trim(); }; const normalizeTaskEngineDateText = (value) => `${value || ''}` .trim() .replace(/年|\//g, '-') .replace(/月/g, '-') .replace(/日/g, '') .replace(/\./g, '-') .replace(/\s+/g, ' '); const extractTaskEngineDetailTimes = (html) => { const text = htmlToTaskEngineText(html); if (!text) return { startTime: '', endTime: '' }; const datePattern = '(?:\\d{4}[-/.年]\\d{1,2}[-/.月]\\d{1,2}日?|\\d{1,2}[-/.月]\\d{1,2}日?)(?:\\s+\\d{1,2}:\\d{2}(?::\\d{2})?)?'; const endMatch = text.match(new RegExp(`(?:截止时间|结束时间|截止日期|有效期至)\\s*[::]?\\s*(${datePattern})`, 'i')); const startMatch = text.match(new RegExp(`(?:开始时间|开放时间)\\s*[::]?\\s*(${datePattern})`, 'i')); const periodMatch = text.match(new RegExp(`(?:作答时间|考试时间|活动时间|任务时间|学习时间|开放时间)\\s*[::]?\\s*(${datePattern})\\s*(?:至|到|~|~)\\s*(${datePattern})`, 'i')); return { startTime: normalizeTaskEngineDateText(startMatch?.[1] || periodMatch?.[1] || ''), endTime: normalizeTaskEngineDateText(endMatch?.[1] || periodMatch?.[2] || '') }; }; const normalizeTaskEngineStudyUrl = (url, domainName = '') => { if (!url) return ''; try { const base = /^https?:\/\//i.test(domainName) ? domainName : 'https://task.chaoxing.com/'; const resolved = new URL(url, base); return /^https?:$/.test(resolved.protocol) ? resolved.href : ''; } catch { return ''; } }; const isTaskEngineCompletedStudyUrl = (url) => { if (!url) return false; try { const parsed = new URL(url); if (!/(^|\.)chaoxing\.com$/i.test(parsed.hostname)) return false; return /\/exam\/test\/look\/?$/i.test(parsed.pathname); } catch { return false; } }; const resolveTaskEnginePlanDetails = async (plan, taskUserId, apiHeaders, fallbackLink, reportIssue = () => {}) => { const planFallbackLink = normalizeTaskEngineStudyUrl(plan.hyperLink || plan.url) || fallbackLink; if (!plan.encryptPlanId) { return { taskLink: planFallbackLink, startTime: '', endTime: '', finished: isTaskEngineCompletedStudyUrl(planFallbackLink) }; } const cacheKey = `${taskUserId}:${plan.encryptPlanId}`; if (taskEngineDetailCache.has(cacheKey)) return taskEngineDetailCache.get(cacheKey); const pending = (async () => { const result = { taskLink: planFallbackLink, startTime: '', endTime: '', finished: isTaskEngineCompletedStudyUrl(planFallbackLink) }; try { const studyUrl = `https://task.chaoxing.com/userStudyPlan/getToStudyUrl?encryptPlanId=${encodeURIComponent(plan.encryptPlanId)}&encryTaskUserId=${encodeURIComponent(taskUserId)}&studyJumpType=0&isInterface=false`; const studyResponse = await gmFetchWithRetry(studyUrl, { method: 'POST', headers: apiHeaders }); const studyPayload = JSON.parse(studyResponse.responseText); if (!studyPayload?.result) throw new Error(studyPayload?.message || '直达链接接口返回失败'); const directUrl = normalizeTaskEngineStudyUrl(studyPayload.data?.url, studyPayload.data?.domainName); if (!directUrl) return result; result.taskLink = directUrl; result.finished = result.finished || isTaskEngineCompletedStudyUrl(directUrl); const type = normalizeTaskEnginePlanType(plan); if (plan.endDateStr || isTaskEnginePlanFinished(plan) || result.finished || !TASK_ENGINE_DEADLINE_TYPES.has(type)) return result; const host = new URL(directUrl).hostname; if (!TASK_ENGINE_DETAIL_HOSTS.has(host)) return result; try { const detailResponse = await gmFetchWithRetry(directUrl, { headers: { Referer: 'https://task.chaoxing.com/' }, timeout: 12000 }); result.taskLink = normalizeTaskEngineStudyUrl(detailResponse.finalUrl) || directUrl; result.finished = result.finished || isTaskEngineCompletedStudyUrl(result.taskLink); Object.assign(result, extractTaskEngineDetailTimes(detailResponse.responseText)); } catch (error) { reportIssue('任务引擎计划详情'); console.warn(`[任务引擎] “${plan.name || plan.planId || ''}”期限读取失败,保留平台直达链接:`, error?.message || error); } } catch (error) { reportIssue('任务引擎计划详情'); console.warn(`[任务引擎] “${plan.name || plan.planId || ''}”直达链接读取失败,保留任务包链接:`, error?.message || error); } return result; })(); taskEngineDetailCache.set(cacheKey, pending); return pending; }; const normalizeTaskEnginePlan = (plan, task, course, details = {}) => { const taskId = task.id ? String(task.id) : ''; const planId = plan.planId ? String(plan.planId) : ''; const type = normalizeTaskEnginePlanType(plan); const isFinished = isTaskEnginePlanFinished(plan) || details.finished === true || isTaskEngineCompletedStudyUrl(details.taskLink); const startTime = plan.startDateStr || details.startTime || ''; const endTime = plan.endDateStr || details.endTime || ''; const isExpired = !isFinished && Number.isFinite(parseTaskEngineDate(endTime)) && parseTaskEngineDate(endTime) < Date.now(); const isLocked = !isFinished && !isExpired && plan.planAllowStudy === false; const status = isFinished ? '已完成' : (isExpired ? '已过期' : (isLocked ? '未开始' : '进行中')); const taskLink = details.taskLink || getTaskEngineLink(taskId, course); return { activeId: `task-engine-${taskId}-plan-${planId || plan.name || ''}`, taskId, planId, title: plan.name || task.name || '未命名任务', type, planType: plan.planType, planTypeName: plan.planTypeName || '', parentTaskTitle: task.name || '', status, time: endTime || startTime, startTime, endTime, leftTime: endTime, timeLeft: endTime, courseName: course.courseName, course: course.courseName, courseId: course.courseId, clazzId: course.clazzId, classId: course.clazzId, cpi: course.cpi, finished: isFinished, expired: isExpired, ongoing: !isFinished && !isExpired && !isLocked, uncommitted: type === '作业' ? !isFinished && !isExpired : undefined, activeType: 'task-engine-plan', taskEngine: true, taskEnginePlan: true, taskLink, isActivity: true }; }; const extractTaskEngineStandardPlans = (payload) => { const entries = payload?.data?.userTaskQualifyDTO?.planUserBOList; if (!Array.isArray(entries)) throw new Error('任务引擎备用子任务列表格式无法识别'); let invalidCount = 0; const plans = []; for (const entry of entries) { if (!entry?.plan || typeof entry.plan !== 'object' || Array.isArray(entry.plan)) { invalidCount += 1; continue; } plans.push({ ...entry.plan, isFinish: entry.plan.isFinish ?? entry.finish, planUser: { ...(entry.plan.planUser || {}), finish: entry.plan.planUser?.finish ?? entry.finish } }); } return { plans, invalidCount }; }; const dedupeTaskEnginePlans = (plans) => { const seen = new Set(); return plans.filter(plan => { const identity = plan.encryptPlanId || plan.planId || plan.id || plan.externalDataId; if (identity == null || identity === '') return true; const key = String(identity); if (seen.has(key)) return false; seen.add(key); return true; }); }; const fetchTaskEngineStandardPlans = async (taskUserId, apiHeaders) => { const url = `https://task.chaoxing.com/userStudyPlan/getUserStandard?encryTaskUserId=${encodeURIComponent(taskUserId)}`; const response = await gmFetchWithRetry(url, { headers: apiHeaders }); return extractTaskEngineStandardPlans(JSON.parse(response.responseText)); }; const fetchTaskEnginePlans = async (task, course, reportIssue = () => {}) => { const fallback = normalizeTaskEngineSummaryItem(task, course); if (!fallback.taskLink) return [fallback]; try { let landingResponse; try { landingResponse = await gmFetchWithRetry(fallback.taskLink, { headers: { Referer: 'https://mobilelearn.chaoxing.com/' } }); } catch { landingResponse = null; } let taskUserId = extractTaskEngineUserId(landingResponse); if (!taskUserId) { const subPageUrl = `https://task.chaoxing.com/userStudyPlan/studyPlanSubPage?taskId=${encodeURIComponent(fallback.taskId)}&encryJumpGroupId=null`; landingResponse = await gmFetchWithRetry(subPageUrl, { headers: { Referer: fallback.taskLink } }); taskUserId = extractTaskEngineUserId(landingResponse); } if (!taskUserId) throw new Error('未找到任务用户标识'); const apiHeaders = { 'X-Requested-With': 'XMLHttpRequest', Referer: landingResponse.finalUrl || fallback.taskLink }; let groupedPlans = []; let groupedReadHadIssue = false; let groupedReadComplete = false; const expectedPlanCount = Number(task.planCount) || 0; try { const groupUrl = `https://task.chaoxing.com/userStudyPlan/getGroupData?encryTaskUserId=${encodeURIComponent(taskUserId)}`; const groupResponse = await gmFetchWithRetry(groupUrl, { method: 'POST', headers: apiHeaders }); const groups = JSON.parse(groupResponse.responseText).data; if (!Array.isArray(groups)) throw new Error('任务分组列表格式异常'); const readableGroups = groups.filter(group => group?.encryptGroupId); if (readableGroups.length !== groups.length) groupedReadHadIssue = true; const planResults = await Promise.allSettled(readableGroups.map(group => { const planUrl = `https://task.chaoxing.com/userStudyPlan/getPlanDataByGroupId?encryTaskUserId=${encodeURIComponent(taskUserId)}&encryGroupId=${encodeURIComponent(group.encryptGroupId)}`; return gmFetchWithRetry(planUrl, { method: 'POST', headers: apiHeaders }); })); for (const result of planResults) { if (result.status !== 'fulfilled') { groupedReadHadIssue = true; continue; } try { const data = JSON.parse(result.value.responseText).data; if (!Array.isArray(data)) { groupedReadHadIssue = true; continue; } const validPlans = data.filter(plan => plan && typeof plan === 'object' && !Array.isArray(plan)); if (validPlans.length !== data.length) groupedReadHadIssue = true; groupedPlans.push(...validPlans); } catch { groupedReadHadIssue = true; } } groupedPlans = dedupeTaskEnginePlans(groupedPlans); if (expectedPlanCount > 0 && groupedPlans.length < expectedPlanCount) groupedReadHadIssue = true; groupedReadComplete = !groupedReadHadIssue && groupedPlans.length > 0; } catch (error) { groupedReadHadIssue = true; console.warn(`[任务引擎] ${course.courseName} 分组任务明细读取失败,尝试备用接口:`, error?.message || error); } let plans = groupedPlans; let standardReadSucceeded = false; let standardReadHadIssue = false; if (!groupedReadComplete) { try { const standardResult = await fetchTaskEngineStandardPlans(taskUserId, apiHeaders); standardReadSucceeded = true; const standardPlans = dedupeTaskEnginePlans(standardResult.plans); standardReadHadIssue = standardResult.invalidCount > 0 || (expectedPlanCount > 0 && standardPlans.length < expectedPlanCount); if (standardPlans.length > 0) plans = standardPlans; } catch (error) { console.warn(`[任务引擎] ${course.courseName} 备用子任务列表读取失败:`, error?.message || error); } } if (standardReadHadIssue || (groupedReadHadIssue && (!standardReadSucceeded || plans === groupedPlans))) { reportIssue('任务引擎分组明细'); } if (!plans.length) { if (!standardReadSucceeded || expectedPlanCount > 0 || groupedReadHadIssue) reportIssue('任务引擎明细'); return [fallback]; } const normalizedPlans = []; for (const plan of plans) { const details = await resolveTaskEnginePlanDetails(plan, taskUserId, apiHeaders, fallback.taskLink, reportIssue); normalizedPlans.push(normalizeTaskEnginePlan(plan, task, course, details)); } return normalizedPlans; } catch (error) { reportIssue('任务引擎明细'); console.warn(`[任务引擎] ${course.courseName} 的任务“${task.name || task.id || ''}”明细读取失败,保留任务包:`, error?.message || error); return [fallback]; } }; const expandTaskEngineItems = async (items, course, reportIssue = () => {}) => { const expanded = []; for (const item of items) { expanded.push(...await fetchTaskEnginePlans(item, course, reportIssue)); } return expanded; }; const isRateLimitOrCaptchaResponse = (status, text = '') => { const code = Number(status) || 0; if (code === 429 || code === 403) return true; const body = String(text || ''); return /验证码|滑动验证|antispider|访问过于频繁|请求过于频繁|请先完成验证/i.test(body); }; const fetchCourseClassroomActivities = async (course) => { const issueKey = getCourseActivityKey(course); if (!courseActivityIssues.has(issueKey)) courseActivityIssues.set(issueKey, new Set()); const reportIssue = (source) => recordCourseActivityIssue(course, source); try { const timestamp = Date.now(); const activityUrl = `https://mobilelearn.chaoxing.com/v2/apis/active/student/activelist?fid=0&courseId=${course.courseId}&classId=${course.clazzId}&showNotStartedActive=0&_=${timestamp}`; const res = await gmFetchWithRetry(activityUrl); if (isRateLimitOrCaptchaResponse(res?.status, res?.responseText)) { reportIssue('课堂活动限流'); return { items: [], rateLimited: true }; } const data = JSON.parse(res.responseText); const parsedActivityList = extractClassroomActivityList(data); if (parsedActivityList.invalidCount > 0) reportIssue('课堂活动数据'); const items = parsedActivityList.items.map((item) => { const isOngoing = item.status === 1; const isEnded = item.status === 2; return { activeId: item.id || item.activeId || '', title: item.nameOne || item.name || item.title || '未知任务', type: normalizeTaskType(item), status: isOngoing ? '进行中' : (isEnded ? '已结束' : '未开始'), time: item.startTime ? new Date(item.startTime).toLocaleString() : '', endTime: item.endTime ? new Date(item.endTime).toLocaleString() : '', endTimeTimestamp: item.endTime ?? '', courseName: course.courseName, courseId: course.courseId, clazzId: course.clazzId, cpi: course.cpi, finished: isEnded, ongoing: isOngoing, activeType: item.activeType || item.type, url: item.url || item.sourceUrl || '', isActivity: true }; }); return { items, rateLimited: false }; } catch (error) { if (isRateLimitOrCaptchaResponse(error?.status, error?.responseText || error?.message)) { reportIssue('课堂活动限流'); return { items: [], rateLimited: true }; } reportIssue('课堂活动'); return { items: [], rateLimited: false }; } }; const fetchCourseTaskEngineActivities = async (course) => { const issueKey = getCourseActivityKey(course); if (!courseActivityIssues.has(issueKey)) courseActivityIssues.set(issueKey, new Set()); const reportIssue = (source) => recordCourseActivityIssue(course, source); try { const taskEngineUrl = `https://mobilelearn.chaoxing.com/v2/apis/active/getData?DB_STRATEGY=DEFAULT&courseId=${course.courseId}&classId=${course.clazzId}`; const res = await gmFetchWithRetry(taskEngineUrl); if (isRateLimitOrCaptchaResponse(res?.status, res?.responseText)) { reportIssue('任务引擎限流'); return { items: [], rateLimited: true }; } const taskEngineData = JSON.parse(res.responseText); const parsedTaskEngineList = extractTaskEngineItems(taskEngineData); if (parsedTaskEngineList.invalidCount > 0) reportIssue('任务引擎数据'); const items = await expandTaskEngineItems(parsedTaskEngineList.items, course, reportIssue); return { items, rateLimited: false }; } catch (error) { if (isRateLimitOrCaptchaResponse(error?.status, error?.responseText || error?.message)) { reportIssue('任务引擎限流'); return { items: [], rateLimited: true }; } reportIssue('任务引擎'); return { items: [], rateLimited: false }; } }; // 获取单个课程的课堂活动与任务引擎任务。视频/任务点仅在课程进度中展示,避免重复出现。 const fetchCourseActivitiesOnce = async (course) => { const issueKey = getCourseActivityKey(course); courseActivityIssues.set(issueKey, new Set()); const reportIssue = (source) => recordCourseActivityIssue(course, source); try { const timestamp = Date.now(); const activityUrl = `https://mobilelearn.chaoxing.com/v2/apis/active/student/activelist?fid=0&courseId=${course.courseId}&classId=${course.clazzId}&showNotStartedActive=0&_=${timestamp}`; const taskEngineUrl = `https://mobilelearn.chaoxing.com/v2/apis/active/getData?DB_STRATEGY=DEFAULT&courseId=${course.courseId}&classId=${course.clazzId}`; console.log(`[课程任务] 获取课程活动与任务引擎 ${course.courseName}`); const [activityResult, taskEngineResult] = await Promise.allSettled([ gmFetchWithRetry(activityUrl), gmFetchWithRetry(taskEngineUrl) ]); let activeList = []; if (activityResult.status === 'fulfilled') { try { const data = JSON.parse(activityResult.value.responseText); const parsedActivityList = extractClassroomActivityList(data); activeList = parsedActivityList.items; if (parsedActivityList.invalidCount > 0) reportIssue('课堂活动数据'); } catch (error) { reportIssue('课堂活动'); console.warn(`[课程任务] ${course.courseName} 课堂活动解析失败:`, error?.message || error); } } else { reportIssue('课堂活动'); console.warn(`[课程任务] ${course.courseName} 课堂活动读取失败:`, activityResult.reason?.message || activityResult.reason); } const activities = activeList.map((item) => { // 状态判断:status=1 进行中,status=2 已结束 const isOngoing = item.status === 1; const isEnded = item.status === 2; return { activeId: item.id || item.activeId || '', title: item.nameOne || item.name || item.title || '未知任务', type: normalizeTaskType(item), status: isOngoing ? '进行中' : (isEnded ? '已结束' : '未开始'), time: item.startTime ? new Date(item.startTime).toLocaleString() : '', endTime: item.endTime ? new Date(item.endTime).toLocaleString() : '', endTimeTimestamp: item.endTime ?? '', courseName: course.courseName, courseId: course.courseId, clazzId: course.clazzId, cpi: course.cpi, finished: isEnded, ongoing: isOngoing, activeType: item.activeType || item.type, url: item.url || item.sourceUrl || '', isActivity: true }; }); let taskEngineItems = []; if (taskEngineResult.status === 'fulfilled') { try { const taskEngineData = JSON.parse(taskEngineResult.value.responseText); const parsedTaskEngineList = extractTaskEngineItems(taskEngineData); if (parsedTaskEngineList.invalidCount > 0) reportIssue('任务引擎数据'); taskEngineItems = await expandTaskEngineItems(parsedTaskEngineList.items, course, reportIssue); } catch (error) { reportIssue('任务引擎'); console.warn(`[课程任务] ${course.courseName} 任务引擎解析失败:`, error?.message || error); } } else { reportIssue('任务引擎'); console.warn(`[课程任务] ${course.courseName} 任务引擎读取失败:`, taskEngineResult.reason?.message || taskEngineResult.reason); } console.log(`[课程任务] ${course.courseName} 找到 ${activities.length} 个课堂活动、${taskEngineItems.length} 个任务引擎任务`); return [...activities, ...taskEngineItems]; } catch (error) { reportIssue('课程任务'); console.error(`[课程任务] 获取课程 ${course.courseName} 的任务失败:`, error?.message || error); return []; } }; const fetchCourseActivities = (course) => { const key = getCourseActivityKey(course); const current = courseActivityInFlight.get(key); if (current) return current; const request = fetchCourseActivitiesOnce(course).finally(() => { if (courseActivityInFlight.get(key) === request) courseActivityInFlight.delete(key); }); courseActivityInFlight.set(key, request); return request; }; // 获取所有课程的任务汇总 const fetchAllActivities = async () => { const courses = await fetchCourseList(); console.log(`[课程任务] 找到 ${courses.length} 个课程`); if (courses.length === 0) { return []; } // 并发获取所有课程的任务(限制并发数防止请求过多) const batchSize = 3; const allActivities = []; for (let i = 0; i < courses.length; i += batchSize) { const batch = courses.slice(i, i + batchSize); const batchResults = await Promise.all( batch.map(course => fetchCourseActivities(course)) ); allActivities.push(...batchResults.flat()); } console.log(`[课程任务] 共获取 ${allActivities.length} 个任务`); return allActivities; }; function extractTasks(doc = document) { let taskElements = doc.querySelectorAll("#chaoxing-assignment-wrapper ul.nav > li"); if (taskElements.length === 0) taskElements = doc.querySelectorAll("ul.nav > li"); const tasks = Array.from(taskElements).map((task) => { var _a, _b, _c; const optionElement = task.querySelector('div[role="option"]'); let title = ""; let status = ""; let uncommitted = false; let statusKnown = false; let course = ""; let leftTime = ""; if (optionElement) { title = ((_a = optionElement.querySelector("p")) == null ? void 0 : _a.textContent) || ""; const statusElement = optionElement.querySelector("span:nth-of-type(1)"); status = (statusElement == null ? void 0 : statusElement.textContent) || ""; statusKnown = !!statusElement; uncommitted = (statusElement == null ? void 0 : statusElement.className.includes("status")) || false; course = ((_b = optionElement.querySelector("span:nth-of-type(2)")) == null ? void 0 : _b.textContent) || ""; leftTime = ((_c = optionElement.querySelector(".fr")) == null ? void 0 : _c.textContent) || ""; } const raw = task.getAttribute("data") || ""; let workId = ""; let courseId = ""; let clazzId = ""; if (raw) { const rawUrl = new URL(raw); const searchParams = rawUrl.searchParams; workId = searchParams.get("taskrefId") || ""; courseId = searchParams.get("courseId") || ""; clazzId = searchParams.get("clazzId") || ""; } return { type: "作业", title, status, statusKnown, uncommitted, course, leftTime, workId, courseId, clazzId, raw }; }); return tasks; } function extractExams(doc = document) { let examElements = doc.querySelectorAll("#chaoxing-assignment-wrapper ul.ks_list > li"); if (examElements.length === 0) examElements = doc.querySelectorAll("ul.ks_list > li"); const exams = Array.from(examElements).map((exam) => { var _a, _b, _c, _d; const dlElement = exam.querySelector("dl"); const imgElement = exam.querySelector("div.ks_pic > img"); let title = ""; let timeLeft = ""; let status = ""; let expired = false; let examId = ""; let courseId = ""; let classId = ""; if (dlElement) { title = ((_a = dlElement.querySelector("dt")) == null ? void 0 : _a.textContent) || ""; timeLeft = ((_b = dlElement.querySelector("dd")) == null ? void 0 : _b.textContent) || ""; } if (imgElement) { expired = ((_c = imgElement.getAttribute("src")) == null ? void 0 : _c.includes("ks_02")) || false; } status = ((_d = exam.querySelector("span.ks_state")) == null ? void 0 : _d.textContent) || ""; const raw = exam.getAttribute("data") || ""; if (raw) { let fullRaw = raw; if (raw.startsWith('/')) fullRaw = window.location.protocol + "//" + window.location.host + raw; try { const rawUrl = new URL(fullRaw); const searchParams = rawUrl.searchParams; examId = searchParams.get("taskrefId") || searchParams.get("examId") || ""; courseId = searchParams.get("courseId") || ""; classId = searchParams.get("classId") || searchParams.get("clazzId") || ""; } catch (e) { } } const finished = status.includes("已完成") || status.includes("待批阅"); return { type: "考试", title, status, timeLeft, expired, finished, examId, courseId, classId, raw }; }); return exams; } function extractExamsFromTable(doc = document) { let examRows = doc.querySelectorAll("table.dataTable tr.dataTr"); if (examRows.length === 0) return []; const exams = Array.from(examRows).map((row) => { const cells = row.querySelectorAll("td"); if (cells.length < 9) return null; const index = cells[0]?.textContent?.trim() || ""; const title = cells[1]?.textContent?.trim() || ""; const timeRange = cells[2]?.textContent?.trim() || ""; const duration = cells[3]?.textContent?.trim() || ""; const examStatus = cells[4]?.textContent?.trim() || ""; const answerStatus = cells[5]?.textContent?.trim() || ""; const score = cells[6]?.textContent?.trim() || "---"; const examMethod = cells[7]?.textContent?.trim() || ""; // 从操作链接中提取参数 const actionLink = cells[8]?.querySelector("a"); const actionText = actionLink?.textContent?.trim() || ""; const onclickAttr = actionLink?.getAttribute("onclick") || ""; let courseId = ""; let classId = ""; let examId = ""; let raw = ""; const goMatch = onclickAttr.match(/go\(['"]([^'"]+)['"]\)/); if (goMatch) { raw = goMatch[1]; try { const fullUrl = new URL(raw, window.location.origin); const refer = fullUrl.searchParams.get("refer") || ""; const referDecoded = decodeURIComponent(refer); const referUrl = new URL(referDecoded, window.location.origin); courseId = referUrl.searchParams.get("courseId") || fullUrl.searchParams.get("moocId") || ""; classId = referUrl.searchParams.get("classId") || fullUrl.searchParams.get("clazzid") || ""; examId = referUrl.searchParams.get("examId") || ""; } catch (e) { const moocMatch = onclickAttr.match(/moocId=(\d+)/); const clazzMatch = onclickAttr.match(/clazzid=(\d+)/); const examIdMatch = onclickAttr.match(/examId=(\d+)/); if (moocMatch) courseId = moocMatch[1]; if (clazzMatch) classId = clazzMatch[1]; if (examIdMatch) examId = examIdMatch[1]; } } const expired = examStatus.includes("已结束"); const finished = answerStatus.includes("已完成") || answerStatus.includes("待批阅"); const status = answerStatus || examStatus; const timeLeft = expired ? "已结束" : timeRange; return { type: "考试", title, status, timeLeft, timeRange, duration, examStatus, answerStatus, score, examMethod, expired, finished, examId, courseId, classId, raw }; }).filter(e => e !== null); return exams; } const API_VISIT_COURSE = "https://mooc1.chaoxing.com/visit/stucoursemiddle?ismooc2=1"; const API_EXAM_LIST = "https://mooc1.chaoxing.com/exam-ans/exam/test/examcode/examlist?edition=1&nohead=0&fid="; const API_OPEN_EXAM = "https://mooc1-api.chaoxing.com/exam-ans/exam/test/examcode/examnotes"; const workEncCache = new Map(); const gmRequestHtml = (url, referer = '') => new Promise((resolve) => { if (typeof GM_xmlhttpRequest === 'function') { try { GM_xmlhttpRequest({ method: 'GET', url, headers: referer ? { Referer: referer } : undefined, timeout: 12000, onload: (res) => resolve({ ok: res.status >= 200 && res.status < 300, finalUrl: res.finalUrl || url, text: res.responseText || '' }), onerror: () => resolve({ ok: false, finalUrl: url, text: '' }), ontimeout: () => resolve({ ok: false, finalUrl: url, text: '' }) }); return; } catch {} } fetch(url, { credentials: 'include' }) .then(async (res) => ({ ok: res.ok, finalUrl: res.url || url, text: await res.text() })) .catch(() => ({ ok: false, finalUrl: url, text: '' })) .then(resolve); }); const normalizeChaoxingUrl = (rawUrl, baseUrl = 'https://mooc1.chaoxing.com') => { if (!rawUrl) return ''; try { return new URL(String(rawUrl).replace(/&/g, '&'), baseUrl).href; } catch { return String(rawUrl); } }; const extractWorkEncFromHtml = (html) => { if (!html) return ''; const m = html.match(/id=["']workEnc["'][^>]*value=["']([^"']+)["']/i) || html.match(/value=["']([^"']+)["'][^>]*id=["']workEnc["']/i) || html.match(/workEnc["']?\s*[:=]\s*["']([a-zA-Z0-9]+)["']/i) || html.match(/[?&]enc=([a-zA-Z0-9]{16,})/i); return m?.[1] || ''; }; const resolveDirectHomeworkUrl = async (item, fallbackUrl) => { const courseId = String(item?.courseId || '').trim(); const classId = String(item?.clazzId || item?.classId || '').trim(); if (!courseId || !classId) { return item?.raw ? normalizeChaoxingUrl(item.raw, 'https://mooc1-api.chaoxing.com') : fallbackUrl; } const cacheKey = `${courseId}_${classId}`; try { let cpi = String(item?.cpi || '').trim(); if (!cpi) { try { const courses = await fetchCourseList(); const matchedCourse = courses.find(c => String(c.courseId) === courseId && String(c.clazzId || c.classId) === classId); cpi = String(matchedCourse?.cpi || '').trim(); } catch {} } let cached = workEncCache.get(cacheKey) || {}; let { stuenc = '', workEnc = '', directFrameSrc = '', finalStuUrl = '' } = cached; const middleUrl = `https://mooc1.chaoxing.com/visit/stucoursemiddle?ismooc2=1&courseid=${encodeURIComponent(courseId)}&clazzid=${encodeURIComponent(classId)}&pageHeader=8`; const stuFallbackUrl = `https://mooc2-ans.chaoxing.com/mooc2-ans/mycourse/stu?courseid=${encodeURIComponent(courseId)}&clazzid=${encodeURIComponent(classId)}${cpi ? `&cpi=${encodeURIComponent(cpi)}` : ''}&ut=s`; if (!workEnc && !directFrameSrc) { const middleRes = await gmRequestHtml(middleUrl); finalStuUrl = middleRes.finalUrl || stuFallbackUrl; const middleHtml = middleRes.text || ''; const frameMatch = middleHtml.match(/]+src=["']([^"']*\/work\/[^"']+)["']/i); if (frameMatch?.[1]) { directFrameSrc = normalizeChaoxingUrl(frameMatch[1], 'https://mooc1.chaoxing.com'); } try { stuenc = new URL(finalStuUrl).searchParams.get('enc') || ''; } catch {} workEnc = extractWorkEncFromHtml(middleHtml); if (!workEnc && !directFrameSrc) { const stuRes = await gmRequestHtml(finalStuUrl.startsWith('http') ? finalStuUrl : stuFallbackUrl, middleUrl); const stuHtml = stuRes.text || ''; if (!stuenc && stuRes.finalUrl) { try { stuenc = new URL(stuRes.finalUrl).searchParams.get('enc') || ''; } catch {} } workEnc = extractWorkEncFromHtml(stuHtml); } if (workEnc || directFrameSrc) { workEncCache.set(cacheKey, { stuenc, workEnc, directFrameSrc, finalStuUrl }); } } if (!directFrameSrc && !workEnc) return fallbackUrl; const workListUrl = directFrameSrc || `https://mooc1.chaoxing.com/mooc2/work/list?courseId=${encodeURIComponent(courseId)}&classId=${encodeURIComponent(classId)}${cpi ? `&cpi=${encodeURIComponent(cpi)}` : ''}&ut=s${stuenc ? `&stuenc=${encodeURIComponent(stuenc)}` : ''}&enc=${encodeURIComponent(workEnc)}`; let workRes = await gmRequestHtml(workListUrl, finalStuUrl || middleUrl); if (!workRes.ok || !workRes.text) { const altUrl = `https://mooc2-ans.chaoxing.com/mooc2/work/list?courseId=${encodeURIComponent(courseId)}&classId=${encodeURIComponent(classId)}${cpi ? `&cpi=${encodeURIComponent(cpi)}` : ''}&ut=s${stuenc ? `&stuenc=${encodeURIComponent(stuenc)}` : ''}&enc=${encodeURIComponent(workEnc)}`; workRes = await gmRequestHtml(altUrl, finalStuUrl || middleUrl); } if (workRes.finalUrl && (/dowork/i.test(workRes.finalUrl) || /\/work\/view/i.test(workRes.finalUrl))) { return workRes.finalUrl; } if (!workRes.text) return fallbackUrl; const hasExactWorkIdParam = (normalizedUrl, workId) => { if (!normalizedUrl || !workId) return false; try { const parsed = new URL(normalizedUrl); for (const param of ['workId', 'workid', 'taskrefId', 'workRelationId']) { if (parsed.searchParams.get(param) === workId) return true; } const escaped = workId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const nestedRe = new RegExp(`(?:workId|workid|taskrefId|workRelationId)(?:=|%3D)${escaped}(?:&|%26|$)`, 'i'); return nestedRe.test(normalizedUrl); } catch { return false; } }; const doc = new DOMParser().parseFromString(workRes.text, 'text/html'); const workId = String(item?.workId || '').trim(); const targetTitle = String(item?.title || '').replace(/\s+/g, '').trim(); const items = doc.querySelectorAll('li, .bottomList ul li, .work-list li'); const exactTitleMatches = []; const substringTitleMatches = []; for (const li of items) { let candidateUrl = li.getAttribute('data') || li.querySelector('[data]')?.getAttribute('data') || li.querySelector('a[href*="work"], a[href*="doHomeWork"]')?.getAttribute('href') || ''; if (!candidateUrl && li.innerHTML) { const urlInHtml = li.innerHTML.match(/(?:https?:)?\/\/[^"'\s<>)]*work[^"'\s<>)]*/i); if (urlInHtml?.[0]) candidateUrl = urlInHtml[0]; } if (!candidateUrl || (!/work/i.test(candidateUrl) && !/doHomeWork/i.test(candidateUrl))) continue; const normalized = normalizeChaoxingUrl(candidateUrl, 'https://mooc1.chaoxing.com'); if (workId && /^\d+$/.test(workId) && hasExactWorkIdParam(normalized, workId)) { return normalized; } if (targetTitle) { const titleNodeText = (li.querySelector?.('.overHidden2, .tit, p, a, h3, h4')?.textContent || '').replace(/\s+/g, '').trim(); const cleanText = (li.textContent || '').replace(/\s+/g, '').trim(); if (titleNodeText && titleNodeText === targetTitle) { exactTitleMatches.push(normalized); } else if (cleanText.includes(targetTitle)) { substringTitleMatches.push(normalized); } } } if (exactTitleMatches.length === 1) return exactTitleMatches[0]; if (exactTitleMatches.length === 0 && substringTitleMatches.length === 1) return substringTitleMatches[0]; } catch (err) { console.warn('[作业直达] 解析直达链接失败,回退课程页:', err); } return fallbackUrl; }; const tryOpenExamFullPreview = () => { const href = window.location?.href || ''; if (href.includes('ispreview=1') || href.includes('examPreview') || href.includes('topreview')) { return 'already_full'; } const docs = [document]; try { document.querySelectorAll('iframe').forEach((frame) => { try { if (frame.contentDocument) docs.push(frame.contentDocument); } catch {} }); } catch {} let visibleLeafCount = 0; for (const doc of docs) { const raw = doc.querySelectorAll('.questionLi, .TiMu'); for (const el of raw) { if (el.querySelector('.questionLi, .TiMu')) continue; if ((el.innerText || '').trim().length > 0 && el.offsetHeight > 0) visibleLeafCount++; } } if (visibleLeafCount > 1) return 'already_full'; const triggerClick = (el) => { if (!el) return false; if (el.getAttribute?.('target') === '_blank') el.removeAttribute('target'); el.click(); return true; }; const cleanTxt = (el) => (el?.innerText || el?.textContent || '').replace(/\s+/g, '').trim(); const isPreviewText = (txt) => txt === '整卷预览' || txt === '预览整卷' || txt === '显示全部题目' || txt === '全部题目' || (txt.includes('整卷预览') && txt.length <= 10); for (const doc of docs) { const actionEls = doc.querySelectorAll('a, button, input[type="button"]'); for (const c of actionEls) { if (c.offsetParent === null) continue; const onclickStr = `${c.getAttribute('onclick') || ''} ${c.getAttribute('href') || ''}`; const txt = cleanTxt(c) || String(c.value || '').replace(/\s+/g, '').trim(); if (/topreview|examPreview|previewPaper|preview/i.test(onclickStr) && (txt.includes('整卷') || txt.includes('预览'))) { if (triggerClick(c)) return 'clicked'; } } for (const c of actionEls) { if (c.offsetParent === null) continue; const txt = cleanTxt(c) || String(c.value || '').replace(/\s+/g, '').trim(); if (isPreviewText(txt) && triggerClick(c)) return 'clicked'; } } for (const doc of docs) { const containers = doc.querySelectorAll('span, li, div'); for (const c of containers) { if (c.offsetParent === null) continue; const txt = cleanTxt(c); if (!isPreviewText(txt)) continue; const hasChildMatch = Array.from(c.children || []).some((ch) => { const cTxt = cleanTxt(ch); return cTxt.includes('整卷预览') || cTxt.includes('全部题目') || cTxt.includes('预览整卷'); }); if (hasChildMatch) continue; const target = c.querySelector('a, button') || c.closest?.('[onclick], a, button') || c; if (triggerClick(target)) return 'clicked'; } } try { if (typeof window.topreview === 'function') { window.topreview(); return 'clicked'; } } catch {} return 'not_found'; }; const showExamPreviewToast = (msg, isHtml = false) => { if (!document.body) return; const old = document.getElementById('cx-exam-preview-toast'); if (old) old.remove(); const el = document.createElement('div'); el.id = 'cx-exam-preview-toast'; if (isHtml) el.innerHTML = msg; else el.textContent = msg; el.style.cssText = 'position:fixed;right:20px;bottom:20px;z-index:999999;display:inline-flex;align-items:center;gap:6px;padding:8px 14px;border-radius:10px;background:rgba(15,23,42,.88);color:#fff;font-size:13px;box-shadow:0 8px 24px rgba(0,0,0,.22);pointer-events:none;transition:opacity .25s ease;'; document.body.appendChild(el); setTimeout(() => { el.style.opacity = '0'; setTimeout(() => el.remove(), 260); }, 2800); }; const startExamAutoFullPreview = () => { if (!isExamAutoFullPreviewEnabled()) return; const delays = [400, 1500, 3000]; let done = false; delays.forEach((ms) => { setTimeout(() => { if (done) return; const result = tryOpenExamFullPreview(); if (result === 'clicked') { done = true; showExamPreviewToast(`${cxSvgHtml('checkCircle', 15)} 已自动切换至整卷预览`, true); } else if (result === 'already_full') { done = true; } }, ms); }); }; const tryOpenPcpickActive = (activeId) => { const exactActiveId = String(activeId || '').trim(); if (!exactActiveId) return false; const escapedId = exactActiveId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const exactOnclickRe = new RegExp(`activeDetail\\(\\s*['"]?${escapedId}['"]?\\s*(?:,|\\))`); const tokenOnclickRe = new RegExp(`(?:^|[^\\d])${escapedId}(?:$|[^\\d])`); const docs = [document]; try { document.querySelectorAll('iframe').forEach((frame) => { try { if (frame.contentDocument) docs.push(frame.contentDocument); } catch {} }); } catch {} for (const doc of docs) { let target = doc.querySelector(`[data-activeid="${exactActiveId}"], #active_${exactActiveId}`); if (!target) { const detailCandidates = doc.querySelectorAll('[onclick*="activeDetail("]'); for (const el of detailCandidates) { if (exactOnclickRe.test(el.getAttribute('onclick') || '')) { target = el; break; } } } if (!target) { const onclickCandidates = doc.querySelectorAll('[onclick]'); for (const el of onclickCandidates) { if (tokenOnclickRe.test(el.getAttribute('onclick') || '')) { target = el; break; } } } if (target) { const pageWin = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const origOpen = pageWin?.open; const origWinOpen = window.open; let navigated = false; const sameTabOpen = (url) => { if (url && String(url) !== 'about:blank') { navigated = true; window.location.href = normalizeChaoxingUrl(url, window.location.origin); } return window; }; try { if (pageWin) pageWin.open = sameTabOpen; window.open = sameTabOpen; } catch {} try { if (target.getAttribute?.('target') === '_blank') target.removeAttribute('target'); const innerClick = target.querySelector('a, dd, p, .Mct') || target; if (innerClick.getAttribute?.('target') === '_blank') innerClick.removeAttribute('target'); innerClick.click(); } finally { setTimeout(() => { try { if (pageWin && origOpen) pageWin.open = origOpen; if (origWinOpen) window.open = origWinOpen; } catch {} }, 1500); } return true; } } return false; }; const startPcpickAutoOpen = () => { const hash = window.location?.hash || ''; const match = hash.match(/#active_(\d+)/); const activeId = match?.[1] || ''; if (!activeId) return; const delays = [150, 500, 1000, 1800, 3000]; let opened = false; delays.forEach((ms) => { setTimeout(() => { if (opened) return; if (tryOpenPcpickActive(activeId)) { opened = true; showExamPreviewToast(`${cxSvgHtml('checkCircle', 15)} 已自动进入目标活动`, true); } }, ms); }); }; const DASHBOARD_STYLESHEETS = [ { name: 'Vuetify', url: 'https://cdn.jsdelivr.net/npm/vuetify@3.6.6/dist/vuetify.min.css' }, { name: 'Material Icons', url: 'https://fonts.googlefonts.cn/css?family=Material+Icons' } ]; // 先同步注入必要的组件基础样式;完整 Vuetify 样式在后台加载后会覆盖这些规则。 const DASHBOARD_STYLE_FALLBACK_CSS = ` :where(.chaoxing-list-root) .v-application { min-height: 100vh; color: var(--cx-text, #212121); background: var(--cx-bg, #fff); font-family: Arial, "Microsoft YaHei", sans-serif; line-height: 1.5; } :where(.chaoxing-list-root) .v-application__wrap { display: flex; flex-direction: column; min-height: 100vh; } :where(.chaoxing-list-root) .v-container { width: 100%; max-width: 1200px; margin: 0 auto; padding: 16px; } :where(.chaoxing-list-root) .v-card { display: block; position: relative; overflow: hidden; border-radius: 4px; color: #212121; background: #fff; } :where(.chaoxing-list-root) .v-card-title { display: flex; align-items: center; padding: 16px; font-size: 1.25rem; font-weight: 500; line-height: 1.5; } :where(.chaoxing-list-root) .v-card-subtitle { padding: 0 16px; color: #666; font-size: .875rem; } :where(.chaoxing-list-root) .v-card-text { padding: 16px; } :where(.chaoxing-list-root) .v-btn { display: inline-flex; align-items: center; justify-content: center; min-width: 64px; min-height: 36px; padding: 0 16px; border: 0; border-radius: 4px; color: #fff; background: #1976d2; font: inherit; font-size: .875rem; font-weight: 500; text-decoration: none; cursor: pointer; } :where(.chaoxing-list-root) .v-btn__content { display: inline-flex; align-items: center; justify-content: center; } :where(.chaoxing-list-root) .v-chip { display: inline-flex; align-items: center; min-height: 28px; padding: 0 12px; border-radius: 16px; color: #333; background: #eee; font-size: .8125rem; } :where(.chaoxing-list-root) .v-alert { display: flex; align-items: flex-start; gap: 12px; padding: 12px 16px; border-radius: 4px; color: #333; background: #f5f5f5; } :where(.chaoxing-list-root) .v-row { display: flex; flex-wrap: wrap; margin: -8px; } :where(.chaoxing-list-root) .v-col { flex: 1 0 0; max-width: 100%; padding: 8px; } :where(.chaoxing-list-root) .v-col-8 { flex: 0 0 66.6667%; max-width: 66.6667%; } :where(.chaoxing-list-root) .v-col-4 { flex: 0 0 33.3333%; max-width: 33.3333%; } :where(.chaoxing-list-root) .v-table { width: 100%; overflow: hidden; background: #fff; } :where(.chaoxing-list-root) .v-table__wrapper { overflow-x: auto; } :where(.chaoxing-list-root) .v-table__wrapper > table { width: 100%; border-collapse: collapse; } :where(.chaoxing-list-root) .v-table th, :where(.chaoxing-list-root) .v-table td { padding: 10px 12px; border-bottom: 1px solid #eee; text-align: left; } :where(.chaoxing-list-root) .v-data-table-header__content { display: flex; align-items: center; gap: 6px; } :where(.chaoxing-list-root) .v-data-table-footer { display: flex; align-items: center; justify-content: flex-end; gap: 16px; padding: 8px 16px; } :where(.chaoxing-list-root) .v-input { display: flex; flex-direction: column; min-width: 0; margin-bottom: 12px; } :where(.chaoxing-list-root) .v-input__control { display: flex; } :where(.chaoxing-list-root) .v-field { display: flex; align-items: center; min-height: 48px; padding: 0 12px; border: 1px solid #888; border-radius: 4px; } :where(.chaoxing-list-root) .v-field__field, :where(.chaoxing-list-root) .v-field__input { display: flex; flex: 1 1 auto; align-items: center; min-width: 0; } :where(.chaoxing-list-root) .v-field__input input { width: 100%; min-width: 0; padding: 8px 0; border: 0; outline: 0; color: inherit; background: transparent; font: inherit; } :where(.chaoxing-list-root) .v-switch .v-selection-control { display: inline-flex; align-items: center; gap: 10px; } :where(.chaoxing-list-root) .v-switch .v-selection-control__wrapper { display: inline-flex; align-items: center; } :where(.chaoxing-list-root) .v-switch .v-switch__track { width: 36px; height: 20px; border-radius: 10px; background: #aaa; } :where(.chaoxing-list-root) .v-switch .v-switch__thumb { width: 16px; height: 16px; margin: 2px; border-radius: 50%; background: #fff; } :where(.chaoxing-list-root) .v-progress-linear { position: relative; width: 100%; height: 4px; overflow: hidden; background: #ddd; } :where(.chaoxing-list-root) .v-progress-linear__determinate, :where(.chaoxing-list-root) .v-progress-linear__indeterminate { position: absolute; inset: 0 auto 0 0; width: 40%; background: #1976d2; } :where(.chaoxing-list-root) .v-icon { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 1em; height: 1em; font-size: 24px; line-height: 1; vertical-align: middle; } :where(.chaoxing-list-root) .material-icons { display: inline-block; font-family: "Material Icons", "Segoe UI Symbol", sans-serif; font-weight: normal; font-style: normal; line-height: 1; white-space: nowrap; letter-spacing: normal; text-transform: none; } `; let dashboardStylesPromise = null; const materialIconsFontAvailable = vue.ref(false); const installDashboardStyleFallback = () => { if (document.getElementById('chaoxing-vuetify-fallback-style')) return; const fallbackStyle = document.createElement('style'); fallbackStyle.id = 'chaoxing-vuetify-fallback-style'; fallbackStyle.textContent = DASHBOARD_STYLE_FALLBACK_CSS; (document.head || document.documentElement).appendChild(fallbackStyle); }; const loadDashboardStylesheet = ({ name, url }) => new Promise((resolve) => { if (typeof GM_xmlhttpRequest !== 'function') { console.warn(`[脚本] GM_xmlhttpRequest 不可用,跳过 ${name} 样式`); resolve(false); return; } try { GM_xmlhttpRequest({ method: 'GET', url, timeout: 15000, onload: (response) => { if (response.status >= 200 && response.status < 300 && response.responseText) { try { GM_addStyle(response.responseText); if (name === 'Material Icons' && document.fonts?.load) { document.fonts.load('24px "Material Icons"', 'check') .then((loadedFonts) => { materialIconsFontAvailable.value = loadedFonts.some((font) => font.status === 'loaded'); }) .catch(() => { materialIconsFontAvailable.value = false; }); } resolve(true); } catch (error) { console.warn(`[脚本] 注入 ${name} 样式失败:`, error); resolve(false); } return; } console.warn(`[脚本] 获取 ${name} 样式失败,HTTP ${response.status}`); resolve(false); }, onerror: (error) => { console.warn(`[脚本] 获取 ${name} 样式失败:`, error); resolve(false); }, ontimeout: () => { console.warn(`[脚本] 获取 ${name} 样式超时`); resolve(false); } }); } catch (error) { console.warn(`[脚本] 请求 ${name} 样式失败:`, error); resolve(false); } }); const ensureDashboardStyles = () => { installDashboardStyleFallback(); if (!dashboardStylesPromise) { dashboardStylesPromise = Promise.all(DASHBOARD_STYLESHEETS.map(loadDashboardStylesheet)); } return dashboardStylesPromise; }; // --- Vue Components --- const _sfc_main$2 = /* @__PURE__ */ vue.defineComponent({ __name: "tasks-list", setup(__props) { const extractedData = extractTasks(); const headers = [ { key: "title", title: "作业名称" }, { key: "course", title: "课程" }, { key: "leftTime", title: "剩余时间" }, { key: "status", title: "状态" }, { key: "action", title: "", sortable: false } ]; const search = vue.ref(""); const getCourseLinkHref = (item) => { const courseId = item.courseId; const clazzId = item.clazzId; const requestUrl = new URL(API_VISIT_COURSE); requestUrl.searchParams.append("courseid", courseId); requestUrl.searchParams.append("clazzid", clazzId); requestUrl.searchParams.append("pageHeader", "8"); return requestUrl.href; }; return (_ctx, _cache) => { const _component_v_text_field = vue.resolveComponent("v-text-field"); const _component_v_btn = vue.resolveComponent("v-btn"); const _component_v_data_table = vue.resolveComponent("v-data-table"); const _component_v_card = vue.resolveComponent("v-card"); return vue.openBlock(), vue.createBlock(_component_v_card, { title: "作业列表", variant: "flat" }, { text: vue.withCtx(() => [ vue.createVNode(_component_v_text_field, { modelValue: search.value, "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => search.value = $event), label: "搜索", "prepend-inner-icon": "search", variant: "outlined", "hide-details": "", "single-line": "" }) ]), default: vue.withCtx(() => [ vue.createVNode(_component_v_data_table, { items: vue.unref(extractedData), search: search.value, hover: "", headers, sticky: "", "items-per-page": "-1", "hide-default-footer": "" }, { "item.action": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_btn, { variant: item.uncommitted ? "tonal" : "plain", color: "primary", href: getCourseLinkHref(item), target: "_blank" }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(item.uncommitted ? "立即完成" : "查看详情"), 1)]) }, 1032, ["variant", "href"]) ]) }, 8, ["items", "search"]) ]) }); }; } }); const _sfc_main$1 = /* @__PURE__ */ vue.defineComponent({ __name: "App", setup(__props) { return (_ctx, _cache) => { return vue.openBlock(), vue.createBlock(_sfc_main$2); }; } }); // --- Vuetify Helper Functions (恢复原版代码) --- // 这些是原脚本为了适配图标组件而手写的一堆辅助函数,之前被误删 function isObject(obj) { return obj !== null && typeof obj === "object" && !Array.isArray(obj); } function pick(obj, paths) { const found = {}; const keys = new Set(Object.keys(obj)); for (const path of paths) { if (keys.has(path)) { found[path] = obj[path]; } } return found; } function mergeDeep() { let source = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; let target = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; let arrayFn = arguments.length > 2 ? arguments[2] : void 0; const out = {}; for (const key in source) { out[key] = source[key]; } for (const key in target) { const sourceProperty = source[key]; const targetProperty = target[key]; if (isObject(sourceProperty) && isObject(targetProperty)) { out[key] = mergeDeep(sourceProperty, targetProperty, arrayFn); continue; } if (Array.isArray(sourceProperty) && Array.isArray(targetProperty) && arrayFn) { out[key] = arrayFn(sourceProperty, targetProperty); continue; } out[key] = targetProperty; } return out; } function toKebabCase() { let str = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; if (toKebabCase.cache.has(str)) return toKebabCase.cache.get(str); const kebab = str.replace(/[^a-z]/gi, "-").replace(/\B([A-Z])/g, "-$1").toLowerCase(); toKebabCase.cache.set(str, kebab); return kebab; } toKebabCase.cache = /* @__PURE__ */ new Map(); function consoleWarn(message) { vue.warn(`Vuetify: ${message}`); } function propsFactory(props, source) { return (defaults) => { return Object.keys(props).reduce((obj, prop) => { const isObjectDefinition = typeof props[prop] === "object" && props[prop] != null && !Array.isArray(props[prop]); const definition = isObjectDefinition ? props[prop] : { type: props[prop] }; if (defaults && prop in defaults) { obj[prop] = { ...definition, default: defaults[prop] }; } else { obj[prop] = definition; } if (source && !obj[prop].source) { obj[prop].source = source; } return obj; }, {}); }; } const DefaultsSymbol = Symbol.for("vuetify:defaults"); function injectDefaults() { const defaults = vue.inject(DefaultsSymbol); if (!defaults) throw new Error("[Vuetify] Could not find defaults instance"); return defaults; } function propIsDefined(vnode, prop) { var _a, _b; return typeof ((_a = vnode.props) == null ? void 0 : _a[prop]) !== "undefined" || typeof ((_b = vnode.props) == null ? void 0 : _b[toKebabCase(prop)]) !== "undefined"; } function internalUseDefaults() { let props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; let name = arguments.length > 1 ? arguments[1] : void 0; let defaults = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : injectDefaults(); const vm = getCurrentInstance("useDefaults"); name = name ?? vm.type.name ?? vm.type.__name; if (!name) { throw new Error("[Vuetify] Could not determine component name"); } const componentDefaults = vue.computed(() => { var _a; return (_a = defaults.value) == null ? void 0 : _a[props._as ?? name]; }); const _props = new Proxy(props, { get(target, prop) { var _a, _b, _c, _d; const propValue = Reflect.get(target, prop); if (prop === "class" || prop === "style") { return [(_a = componentDefaults.value) == null ? void 0 : _a[prop], propValue].filter((v) => v != null); } else if (typeof prop === "string" && !propIsDefined(vm.vnode, prop)) { return ((_b = componentDefaults.value) == null ? void 0 : _b[prop]) ?? ((_d = (_c = defaults.value) == null ? void 0 : _c.global) == null ? void 0 : _d[prop]) ?? propValue; } return propValue; } }); const _subcomponentDefaults = vue.shallowRef(); vue.watchEffect(() => { if (componentDefaults.value) { const subComponents = Object.entries(componentDefaults.value).filter((_ref) => { let [key] = _ref; return key.startsWith(key[0].toUpperCase()); }); _subcomponentDefaults.value = subComponents.length ? Object.fromEntries(subComponents) : void 0; } else { _subcomponentDefaults.value = void 0; } }); function provideSubDefaults() { const injected = injectSelf(DefaultsSymbol, vm); vue.provide(DefaultsSymbol, vue.computed(() => { return _subcomponentDefaults.value ? mergeDeep((injected == null ? void 0 : injected.value) ?? {}, _subcomponentDefaults.value) : injected == null ? void 0 : injected.value; })); } return { props: _props, provideSubDefaults }; } function defineComponent(options) { options._setup = options._setup ?? options.setup; if (!options.name) { consoleWarn("The component is missing an explicit name, unable to generate default prop value"); return options; } if (options._setup) { options.props = propsFactory(options.props ?? {}, options.name)(); const propKeys = Object.keys(options.props).filter((key) => key !== "class" && key !== "style"); options.filterProps = function filterProps(props) { return pick(props, propKeys); }; options.props._as = String; options.setup = function setup(props, ctx) { const defaults = injectDefaults(); if (!defaults.value) return options._setup(props, ctx); const { props: _props, provideSubDefaults } = internalUseDefaults(props, props._as ?? options.name, defaults); const setupBindings = options._setup(_props, ctx); provideSubDefaults(); return setupBindings; }; } return options; } function genericComponent() { let exposeDefaults = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true; return (options) => (exposeDefaults ? defineComponent : vue.defineComponent)(options); } function getCurrentInstance(name, message) { const vm = vue.getCurrentInstance(); if (!vm) { throw new Error(`[Vuetify] ${name} ${"must be called from inside a setup function"}`); } return vm; } function injectSelf(key) { let vm = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : getCurrentInstance("injectSelf"); const { provides } = vm; if (provides && key in provides) { return provides[key]; } return void 0; } const IconValue = [String, Function, Object, Array]; const makeIconProps = propsFactory({ icon: { type: IconValue }, tag: { type: String, required: true } }, "icon"); genericComponent()({ name: "VComponentIcon", props: makeIconProps(), setup(props, _ref) { let { slots } = _ref; return () => { const Icon = props.icon; return vue.createVNode(props.tag, null, { default: () => { var _a; return [props.icon ? vue.createVNode(Icon, null, null) : (_a = slots.default) == null ? void 0 : _a.call(slots)]; } }); }; } }); defineComponent({ name: "VSvgIcon", inheritAttrs: false, props: makeIconProps(), setup(props, _ref2) { let { attrs } = _ref2; return () => { return vue.createVNode(props.tag, vue.mergeProps(attrs, { "style": null }), { default: () => [vue.createVNode("svg", { "class": "v-icon__svg", "xmlns": "http://www.w3.org/2000/svg", "viewBox": "0 0 24 24", "role": "img", "aria-hidden": "true" }, [Array.isArray(props.icon) ? props.icon.map((path) => Array.isArray(path) ? vue.createVNode("path", { "d": path[0], "fill-opacity": path[1] }, null) : vue.createVNode("path", { "d": path }, null)) : vue.createVNode("path", { "d": props.icon }, null)])] }); }; } }); const MATERIAL_ICON_FALLBACKS = { keyboard_arrow_up: '⌃', check: '✓', cancel: '×', close: '×', check_circle: '✓', info: 'ⓘ', priority_high: '!', warning: '⚠', chevron_left: '‹', chevron_right: '›', check_box: '☑', check_box_outline_blank: '□', indeterminate_check_box: '⊟', fiber_manual_record: '•', arrow_upward: '↑', arrow_downward: '↓', keyboard_arrow_down: '⌄', menu: '☰', arrow_drop_down: '▾', radio_button_checked: '⦿', radio_button_unchecked: '◯', edit: '✎', star_border: '☆', star: '★', star_half: '◐', cached: '↻', first_page: '|‹', last_page: '›|', unfold_more: '↕', attach_file: '📎', add: '+', remove: '−', event: '▦', arrow_right: '›', colorize: '✎', search: '⌕', settings: '⚙', refresh: '↻', more_vert: '⋮', visibility: '◉', visibility_off: '⊘', arrow_back: '←', arrow_forward: '→', help: '?', notifications: '♢', delete: '×', filter_list: '☷', open_in_new: '↗' }; const VLigatureIcon = defineComponent({ name: "VLigatureIcon", props: makeIconProps(), setup(props) { return () => { const icon = materialIconsFontAvailable.value ? props.icon : MATERIAL_ICON_FALLBACKS[props.icon] || '•'; return vue.createVNode(props.tag, null, { default: () => [icon] }); }; } }); defineComponent({ name: "VClassIcon", props: makeIconProps(), setup(props) { return () => { return vue.createVNode(props.tag, { "class": props.icon }, null); }; } }); const aliases = { collapse: "keyboard_arrow_up", complete: "check", cancel: "cancel", close: "close", delete: "cancel", clear: "cancel", success: "check_circle", info: "info", warning: "priority_high", error: "warning", prev: "chevron_left", next: "chevron_right", checkboxOn: "check_box", checkboxOff: "check_box_outline_blank", checkboxIndeterminate: "indeterminate_check_box", delimiter: "fiber_manual_record", sortAsc: "arrow_upward", sortDesc: "arrow_downward", expand: "keyboard_arrow_down", menu: "menu", subgroup: "arrow_drop_down", dropdown: "arrow_drop_down", radioOn: "radio_button_checked", radioOff: "radio_button_unchecked", edit: "edit", ratingEmpty: "star_border", ratingFull: "star", ratingHalf: "star_half", loading: "cached", first: "first_page", last: "last_page", unfold: "unfold_more", file: "attach_file", plus: "add", minus: "remove", calendar: "event", treeviewCollapse: "arrow_drop_down", treeviewExpand: "arrow_right", eyeDropper: "colorize" }; const md = { component: (props) => vue.h(VLigatureIcon, { ...props, class: "material-icons" }) }; const _sfc_main = /* @__PURE__ */ vue.defineComponent({ __name: "exams-list", setup(__props) { const extractedData = extractExams(); const headers = [ { key: "title", title: "考试名称" }, { key: "timeLeft", title: "剩余时间" }, { key: "status", title: "状态" }, { key: "action", title: "", sortable: false } ]; const search = vue.ref(""); const getCourseLinkHref = (item) => { const requestUrl = new URL(API_OPEN_EXAM); requestUrl.searchParams.append("courseId", item.courseId); requestUrl.searchParams.append("classId", item.classId); requestUrl.searchParams.append("examId", item.examId); return requestUrl.href; }; return (_ctx, _cache) => { const _component_v_text_field = vue.resolveComponent("v-text-field"); const _component_v_btn = vue.resolveComponent("v-btn"); const _component_v_data_table = vue.resolveComponent("v-data-table"); const _component_v_card = vue.resolveComponent("v-card"); return vue.openBlock(), vue.createBlock(_component_v_card, { title: "考试列表", variant: "flat" }, { text: vue.withCtx(() => [ vue.createVNode(_component_v_text_field, { modelValue: search.value, "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => search.value = $event), label: "搜索", "prepend-inner-icon": "search", variant: "outlined", "hide-details": "", "single-line": "" }) ]), default: vue.withCtx(() => [ vue.createVNode(_component_v_data_table, { items: vue.unref(extractedData), search: search.value, hover: "", headers, sticky: "", "items-per-page": "-1", "hide-default-footer": "" }, { "item.action": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_btn, { variant: item.finished || item.expired ? "plain" : "tonal", color: "primary", href: getCourseLinkHref(item), target: "_blank" }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(item.finished || item.expired ? "查看详情" : "前往考试"), 1)]) }, 1032, ["variant", "href"]) ]) }, 8, ["items", "search"]) ]) }); }; } }); const _sfc_todo = /* @__PURE__ */ vue.defineComponent({ __name: "todo-list", setup(__props) { const allTodoItems = vue.ref([]); // 所有待办项 const loading = vue.ref(true); const search = vue.ref(""); const showActivities = vue.ref(true); // 是否显示课程任务(默认开启) const showUrgentOnly = vue.ref(false); // 是否只显示紧急任务 const activityReadWarning = vue.ref(''); // 计算属性:根据开关过滤显示的列表 const todoList = vue.computed(() => { let list = allTodoItems.value; // 如果启用紧急模式,只显示紧急任务 if (showUrgentOnly.value) { return [...urgentTasks.value].sort(compareTodoItemsByDeadline); } // 如果关闭课程任务显示,过滤掉 isActivity 项 if (!showActivities.value) { list = list.filter(item => !item.isActivity); } return [...list].sort(compareTodoItemsByDeadline); }); const headers = [ { key: "type", title: "类型" }, { key: "title", title: "任务名称" }, { key: "course", title: "课程" }, { key: "info", title: "截止/剩余时间" }, { key: "status", title: "状态" }, { key: "action", title: "", sortable: false } ]; // 检测24小时内截止的紧急任务 const urgentTasks = vue.computed(() => { return allTodoItems.value.filter(item => { const remainingMinutes = getTaskRemainingMinutes(item); if (Number.isFinite(remainingMinutes)) return remainingMinutes >= 0 && remainingMinutes <= 24 * 60; if (item.isActivity && item.status === '进行中') { return true; } return false; }); }); const getLink = (item) => { if (item.isActivity) { if (item.taskLink) return item.taskLink; // 课程活动跳转到课程页面 const requestUrl = new URL(API_VISIT_COURSE); requestUrl.searchParams.append("courseid", item.courseId); requestUrl.searchParams.append("clazzid", item.clazzId); requestUrl.searchParams.append("pageHeader", "0"); // 任务页面 return requestUrl.href; } else if (item.type === "作业") { const requestUrl = new URL(API_VISIT_COURSE); requestUrl.searchParams.append("courseid", item.courseId); requestUrl.searchParams.append("clazzid", item.clazzId); requestUrl.searchParams.append("pageHeader", "8"); return requestUrl.href; } else { const requestUrl = new URL(API_OPEN_EXAM); requestUrl.searchParams.append("courseId", item.courseId); requestUrl.searchParams.append("classId", item.classId); requestUrl.searchParams.append("examId", item.examId); return requestUrl.href; } }; vue.onMounted(async () => { clearCourseActivityIssues(); activityReadWarning.value = ''; const currentTasks = extractTasks(); const pendingTasks = currentTasks.filter(t => t.uncommitted).map(t => ({ ...t, info: t.leftTime })); let pendingExams = []; const seenExamIds = new Set(); try { const res1 = await fetch('https://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode'); const text1 = await res1.text(); const parser1 = new DOMParser(); const doc1 = parser1.parseFromString(text1, 'text/html'); const exams1 = extractExams(doc1); exams1.filter(e => !e.finished && !e.expired).forEach(e => { const key = e.examId || e.title; if (!seenExamIds.has(key)) { seenExamIds.add(key); pendingExams.push({ ...e, course: "考试课程", info: e.timeLeft }); } }); } catch (e) { console.error("Fetch exams from old API failed", e); } try { const res2 = await fetch(API_EXAM_LIST); const text2 = await res2.text(); const parser2 = new DOMParser(); const doc2 = parser2.parseFromString(text2, 'text/html'); const exams2 = extractExamsFromTable(doc2); exams2.filter(e => !e.finished && !e.expired).forEach(e => { const key = e.examId || e.title; if (!seenExamIds.has(key)) { seenExamIds.add(key); pendingExams.push({ ...e, course: "考试课程", info: e.timeLeft }); } }); } catch (e) { console.error("Fetch exams from new API failed", e); } // 获取进行中的课程任务(签到、讨论等) let ongoingActivities = []; try { const courses = await fetchCourseList(); console.log('[待办任务] 获取到课程:', courses.length, '个'); // 限制并发数 const batchSize = 3; for (let i = 0; i < courses.length; i += batchSize) { const batch = courses.slice(i, i + batchSize); const batchResults = await Promise.all( batch.map(course => fetchCourseActivities(course)) ); batchResults.flat() .filter(activity => activity.ongoing) .forEach(activity => { ongoingActivities.push({ type: activity.type, title: activity.title, course: activity.courseName, info: activity.progressText ? `进度 ${activity.progressText}` : (activity.endTime || '进行中'), status: '进行中', courseId: activity.courseId, clazzId: activity.clazzId, activeId: activity.activeId, taskId: activity.taskId, planId: activity.planId, taskEngine: activity.taskEngine, taskEnginePlan: activity.taskEnginePlan, taskLink: activity.taskLink, isActivity: true }); }); } activityReadWarning.value = formatCourseActivityIssues(getCourseActivityIssues(courses)); console.log('[待办任务] 进行中任务:', ongoingActivities.length, '个'); } catch (e) { console.error('[待办任务] 获取课程任务失败:', e); activityReadWarning.value = '课程列表或任务引擎读取失败,待办清单可能不完整。请刷新重试。'; } allTodoItems.value = [...pendingTasks, ...pendingExams, ...ongoingActivities] .sort(compareTodoItemsByDeadline); loading.value = false; }); return (_ctx, _cache) => { const _component_v_text_field = vue.resolveComponent("v-text-field"); const _component_v_switch = vue.resolveComponent("v-switch"); const _component_v_btn = vue.resolveComponent("v-btn"); const _component_v_data_table = vue.resolveComponent("v-data-table"); const _component_v_card = vue.resolveComponent("v-card"); const _component_v_chip = vue.resolveComponent("v-chip"); const _component_v_row = vue.resolveComponent("v-row"); const _component_v_col = vue.resolveComponent("v-col"); const _component_v_alert = vue.resolveComponent("v-alert"); return vue.openBlock(), vue.createBlock(_component_v_card, { title: showUrgentOnly.value ? "紧急任务" : "待办任务", variant: "flat" }, { text: vue.withCtx(() => [ // 紧急模式下显示"返回全部"按钮 showUrgentOnly.value ? vue.createVNode(_component_v_alert, { type: "info", variant: "tonal", class: "mb-4" }, { default: () => [ vue.createVNode("div", { class: "d-flex align-center justify-space-between" }, [ vue.createVNode("span", {}, `正在查看 ${urgentTasks.value.length} 个紧急任务`), vue.createVNode(_component_v_btn, { variant: "outlined", size: "small", onClick: () => { showUrgentOnly.value = false; } }, { default: () => [vue.createTextVNode("← 返回全部待办")] }) ]) ] }) : ( // 非紧急模式下显示紧急任务提醒 urgentTasks.value.length > 0 ? vue.createVNode(_component_v_alert, { type: "warning", variant: "tonal", class: "mb-4", prominent: true, icon: "warning" }, { default: () => [ vue.createVNode("div", { class: "d-flex align-center justify-space-between" }, [ vue.createVNode("div", {}, [ vue.createVNode("div", { class: "font-weight-bold" }, `有 ${urgentTasks.value.length} 个任务即将到期!`), vue.createVNode("div", { class: "text-caption" }, urgentTasks.value.slice(0, 2).map(t => t.title).join('、') + (urgentTasks.value.length > 2 ? ` 等${urgentTasks.value.length}个任务` : '') ) ]), vue.createVNode(_component_v_btn, { variant: "elevated", color: "warning", size: "small", onClick: () => { showUrgentOnly.value = true; } }, { default: () => [vue.createTextVNode("去查看 →")] }) ]) ] }) : null ), activityReadWarning.value ? vue.createVNode(_component_v_alert, { type: "error", variant: "tonal", class: "mb-4" }, { default: () => [ vue.createVNode("div", { class: "d-flex align-center justify-space-between ga-3" }, [ vue.createVNode("span", {}, activityReadWarning.value), vue.createVNode(_component_v_btn, { variant: "outlined", size: "small", onClick: () => window.location.reload() }, { default: () => [vue.createTextVNode("刷新重试")] }) ]) ] }) : null, vue.createVNode(_component_v_row, { align: "center", class: "mb-2" }, { default: () => [ vue.createVNode(_component_v_col, { cols: "8" }, { default: () => [ vue.createVNode(_component_v_text_field, { modelValue: search.value, "onUpdate:modelValue": ($event) => search.value = $event, label: "搜索待办", "prepend-inner-icon": "search", variant: "outlined", "hide-details": "", "single-line": "", density: "compact" }) ] }), vue.createVNode(_component_v_col, { cols: "4" }, { default: () => [ vue.createVNode(_component_v_switch, { modelValue: showActivities.value, "onUpdate:modelValue": ($event) => showActivities.value = $event, label: "显示课程任务", color: "primary", "hide-details": "", density: "compact" }) ] }) ] }) ]), default: vue.withCtx(() => [ vue.createVNode(_component_v_data_table, { items: todoList.value, loading: loading.value, search: search.value, hover: "", headers, sticky: "", "items-per-page": "-1", "hide-default-footer": "" }, { "item.type": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_chip, { color: item.isActivity ? 'orange' : (item.type === '作业' ? 'blue' : 'purple'), size: 'small', label: '' }, { default: () => [vue.createTextVNode(item.type)] }) ]), "item.action": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_btn, { variant: "tonal", color: "error", href: getLink(item), target: "_blank" }, { default: vue.withCtx(() => [vue.createTextVNode("立即去办")]) }, 8, ["href"]) ]) }, 8, ["items", "loading", "search"]) ]) }); }; } }); // 课程任务列表组件 const _sfc_activities = /* @__PURE__ */ vue.defineComponent({ __name: "activities-list", setup(__props) { const activitiesList = vue.ref([]); const loading = vue.ref(true); const search = vue.ref(""); const progress = vue.ref(""); const headers = [ { key: "courseName", title: "课程" }, { key: "title", title: "任务名称" }, { key: "type", title: "类型" }, { key: "endTime", title: "结束时间" }, { key: "status", title: "状态" }, { key: "action", title: "", sortable: false } ]; const getCourseLink = (item) => { const requestUrl = new URL(API_VISIT_COURSE); requestUrl.searchParams.append("courseid", item.courseId); requestUrl.searchParams.append("clazzid", item.clazzId); return requestUrl.href; }; const loadActivities = async () => { loading.value = true; clearCourseActivityIssues(); try { progress.value = "正在获取课程列表..."; const courses = await fetchCourseList(); progress.value = `找到 ${courses.length} 个课程,正在获取任务...`; const allActivities = []; const batchSize = 3; for (let i = 0; i < courses.length; i += batchSize) { const batch = courses.slice(i, i + batchSize); progress.value = `正在获取课程任务 (${Math.min(i + batchSize, courses.length)}/${courses.length})...`; const batchResults = await Promise.all( batch.map(course => fetchCourseActivities(course)) ); allActivities.push(...batchResults.flat()); } const issues = getCourseActivityIssues(courses); if (!issues.length || !activitiesList.value.length) activitiesList.value = allActivities; progress.value = formatCourseActivityIssues(issues); } catch (error) { console.error('[课程任务] 加载失败:', error); progress.value = "加载失败,请刷新重试"; } finally { loading.value = false; } }; vue.onMounted(loadActivities); return (_ctx, _cache) => { const _component_v_text_field = vue.resolveComponent("v-text-field"); const _component_v_chip = vue.resolveComponent("v-chip"); const _component_v_btn = vue.resolveComponent("v-btn"); const _component_v_data_table = vue.resolveComponent("v-data-table"); const _component_v_card = vue.resolveComponent("v-card"); const _component_v_progress_linear = vue.resolveComponent("v-progress-linear"); const _component_v_alert = vue.resolveComponent("v-alert"); return vue.openBlock(), vue.createBlock(_component_v_card, { title: "课程任务列表", variant: "flat", subtitle: loading.value ? progress.value : '' }, { text: vue.withCtx(() => [ vue.createVNode(_component_v_text_field, { modelValue: search.value, "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => search.value = $event), label: "搜索", "prepend-inner-icon": "search", variant: "outlined", "hide-details": "", "single-line": "" }), (progress.value.includes('读取不完整') || progress.value.includes('课程列表为空') || progress.value.includes('加载失败')) ? vue.createVNode(_component_v_alert, { type: progress.value.includes('加载失败') ? 'error' : 'warning', variant: "tonal", class: "mt-4" }, { default: vue.withCtx(() => [ vue.createVNode("div", { class: "d-flex align-center justify-space-between ga-3" }, [ vue.createVNode("span", {}, progress.value), vue.createVNode(_component_v_btn, { variant: "outlined", size: "small", onClick: loadActivities }, { default: () => [vue.createTextVNode("刷新重试")] }) ]) ]) }) : null, loading.value ? vue.createVNode(_component_v_progress_linear, { indeterminate: "", color: "primary", class: "mt-4" }) : null ]), default: vue.withCtx(() => [ vue.createVNode(_component_v_data_table, { items: activitiesList.value, loading: loading.value, search: search.value, hover: "", headers, sticky: "", "items-per-page": "-1", "hide-default-footer": "" }, { "item.type": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_chip, { color: 'teal', size: 'small', label: '' }, { default: () => [vue.createTextVNode(item.type || '活动')] }) ]), "item.status": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_chip, { color: item.ongoing ? 'orange' : 'grey', size: 'small', label: '' }, { default: () => [vue.createTextVNode(item.status)] }) ]), "item.action": vue.withCtx(({ item }) => [ vue.createVNode(_component_v_btn, { variant: item.finished ? "plain" : "tonal", color: "primary", href: getCourseLink(item), target: "_blank" }, { default: vue.withCtx(() => [vue.createTextVNode(item.finished ? "查看详情" : "前往完成")]) }, 8, ["variant", "href"]) ]) }, 8, ["items", "loading", "search"]) ]) }, 8, ["subtitle"]); }; } }); // --- 数据提取辅助函数 --- const extractTextById = (html, id) => { const idPattern = new RegExp(`id=["']?${id}["']?[^>]*>([^<]*)`, 'i'); const match = html.match(idPattern); return match ? match[1].trim() : ''; }; const extractNumberById = (html, id) => { const idText = extractTextById(html, id); if (idText) { const numeric = idText.match(/\d+(\.\d+)?/); return numeric ? numeric[0] : ''; } const loosePattern = new RegExp(`${id}[^\\d]*(\\d+(?:\\.\\d+)?)`, 'i'); const looseMatch = html.match(loosePattern); return looseMatch ? looseMatch[1] : ''; }; const extractPairNearLabel = (html, label) => { const pairPattern = new RegExp(`${label}[^\\d]{0,50}(\\d+)\\s*\\/\\s*(\\d+)`, 'i'); const match = html.match(pairPattern); return match ? { first: match[1], second: match[2] } : null; }; const extractNumberNearLabel = (html, label) => { const numberPattern = new RegExp(`${label}[^\\d]{0,50}(\\d+(?:\\.\\d+)?)`, 'i'); const match = html.match(numberPattern); return match ? match[1] : ''; }; const getSiblingText = (element, selector) => { const parent = element?.closest('li') || element?.parentElement; if (!parent) return ''; const target = parent.querySelector(selector); return target?.textContent.trim() || ''; }; const extractTaskPairFromDom = (doc) => { const label = Array.from(doc.querySelectorAll('p')).find((el) => el.textContent.includes('完成进度')); if (!label) return null; const text = getSiblingText(label, 'h2'); const match = text.match(/(\d+)\s*\/\s*(\d+)/); return match ? { first: match[1], second: match[2] } : null; }; const extractDataFromDomByLabel = (doc, label) => { if (!doc) return null; const candidates = Array.from(doc.querySelectorAll('*')).filter(el => el.children.length === 0 && el.textContent.includes(label) ); for (const el of candidates) { let container = el.parentElement; let attempts = 3; while (container && attempts > 0) { const text = container.textContent.trim(); const textAfterLabel = text.substring(text.indexOf(label) + label.length); const match = textAfterLabel.match(/[::\s]*(\d+(?:\.\d+)?)/); if (match) return match[1]; container = container.parentElement; attempts--; } } return null; }; const extractRankFromDom = (doc) => { const candidates = Array.from(doc.querySelectorAll('*')).filter(el => { const text = el.textContent || ''; return (text.includes('当前排名') || text.includes('班级排名') || text.includes('排名')) && el.children.length === 0; }); for (const candidate of candidates) { let container = candidate.parentElement; for (let i = 0; i < 5 && container; i++) { const allText = container.textContent || ''; const match = allText.match(/(?:第\s*)?(\d+)\s*名/); if (match && match[1]) { return match[1]; } container = container.parentElement; } } const whiteBgContainers = doc.querySelectorAll('.whiteBg'); for (const container of whiteBgContainers) { const text = container.textContent || ''; if (text.includes('排名') || text.includes('名次')) { const match = text.match(/(?:第\s*)?(\d+)\s*名/); if (match && match[1]) { return match[1]; } const numMatch = text.match(/(\d+)\s*名/); if (numMatch && numMatch[1]) { return numMatch[1]; } } } const h2Elements = doc.querySelectorAll('h2, .stat-value, .count, .fr'); for (const el of h2Elements) { const text = el.textContent.trim(); if (text.match(/^\d+$/) && parseInt(text) < 10000) { return text; } const rankMatch = text.match(/(?:第\s*)?(\d+)\s*名/); if (rankMatch) { return rankMatch[1]; } } const frElements = doc.querySelectorAll('.fr'); for (const el of frElements) { const text = el.textContent.trim(); if (text.match(/^\d+$/) && parseInt(text) < 10000) { return text; } } return ''; }; const extractPointFromDom = (doc) => { const candidates = Array.from(doc.querySelectorAll('*')).filter(el => { const text = el.textContent || ''; return (text.includes('课程积分') || text.includes('积分')) && el.children.length === 0; }); for (const candidate of candidates) { let container = candidate.parentElement; for (let i = 0; i < 5 && container; i++) { const allText = container.textContent || ''; const match = allText.match(/[::]\s*(\d+(?:\.\d+)?)/); if (match && match[1]) { return match[1]; } const directMatch = allText.match(/(\d+(?:\.\d+)?)\s*(?:分|积分)/); if (directMatch && directMatch[1]) { return directMatch[1]; } container = container.parentElement; } } const whiteBgContainers = doc.querySelectorAll('.whiteBg'); for (const container of whiteBgContainers) { const text = container.textContent || ''; if (text.includes('积分')) { const match = text.match(/(?:课程)?积分[::\s]*(\d+(?:\.\d+)?)/); if (match && match[1]) { return match[1]; } const numMatch = text.match(/(\d+(?:\.\d+)?)\s*(?:分|积分)/); if (numMatch && numMatch[1]) { return numMatch[1]; } const pureNumMatch = text.match(/积分[^\\d]*(\d+)/); if (pureNumMatch && pureNumMatch[1]) { return pureNumMatch[1]; } } } const pointElements = doc.querySelectorAll('#point, .point, [class*="point"], [id*="point"]'); for (const el of pointElements) { const text = el.textContent.trim(); if (text.match(/^\d+(?:\.\d+)?$/)) { return text; } } const h2Elements = doc.querySelectorAll('h2, .stat-value, .fr'); for (const el of h2Elements) { const text = el.textContent.trim(); if (text.match(/^\d+(?:\.\d+)?$/) && parseFloat(text) <= 1000) { return text; } } return ''; }; const extractQuizPairFromDom = (doc) => { const candidates = Array.from(doc.querySelectorAll('*')).filter(el => { const text = el.textContent || ''; return text.includes('章节测验') || text.includes('测验'); }); for (const candidate of candidates) { let container = candidate.parentElement; for (let i = 0; i < 5 && container; i++) { const allText = container.textContent || ''; const match = allText.match(/(\d+)\s*\/\s*(\d+)/); if (match && match[1] && match[2]) { return { first: match[1], second: match[2] }; } container = container.parentElement; } } const whiteBgContainers = doc.querySelectorAll('.whiteBg'); for (const container of whiteBgContainers) { const text = container.textContent || ''; if (text.includes('测验')) { const match = text.match(/章节测验[::\s]*(\d+)\s*\/\s*(\d+)/); if (match && match[1] && match[2]) { return { first: match[1], second: match[2] }; } const shortMatch = text.match(/测验[::\s]*(\d+)\s*\/\s*(\d+)/); if (shortMatch && shortMatch[1] && shortMatch[2]) { return { first: shortMatch[1], second: shortMatch[2] }; } } } const statsBars = doc.querySelectorAll('.statistics-bar-list li, .stat-item, [class*="statistic"], .whiteBg'); for (const item of statsBars) { const text = item.textContent || ''; const match = text.match(/(\d+)\s*\/\s*(\d+)/); if (match && match[1] && match[2]) { return { first: match[1], second: match[2] }; } } const allText = doc.body?.textContent || ''; const quizMatch = allText.match(/章节测验[^\\n]{0,50}(\d+)\s*\/\s*(\d+)/i); if (quizMatch) { return { first: quizMatch[1], second: quizMatch[2] }; } return null; }; const _sfc_dashboard = /* @__PURE__ */ vue.defineComponent({ __name: "dashboard", setup(__props) { const fetchUserName = async () => { const userNameEl = document.querySelector('.user-name'); if (userNameEl && userNameEl.textContent.trim()) { return userNameEl.textContent.trim(); } const personalNameEl = document.querySelector('.personalName'); if (personalNameEl && personalNameEl.textContent.trim()) { return personalNameEl.textContent.trim(); } return new Promise((resolve) => { if (typeof GM_xmlhttpRequest !== 'undefined') { GM_xmlhttpRequest({ method: 'GET', url: 'https://i.chaoxing.com/base', timeout: 5000, onload: (response) => { try { const parser = new DOMParser(); const doc = parser.parseFromString(response.responseText, 'text/html'); const nameEl = doc.querySelector('.user-name') || doc.querySelector('.personalName'); if (nameEl && nameEl.textContent.trim()) { resolve(nameEl.textContent.trim()); } else { resolve('同学'); } } catch (e) { resolve('同学'); } }, onerror: () => resolve('同学'), ontimeout: () => resolve('同学') }); } else { resolve('同学'); } }); }; const getGreeting = () => { const hour = new Date().getHours(); if (hour < 6) return '夜深了'; if (hour < 12) return '早上好'; if (hour < 14) return '中午好'; if (hour < 18) return '下午好'; return '晚上好'; }; const getFormattedDate = () => { const now = new Date(); const weekdays = ['日', '一', '二', '三', '四', '五', '六']; return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 · 星期${weekdays[now.getDay()]}`; }; const userName = vue.ref('同学'); // 先显示默认值 const greeting = vue.ref(getGreeting()); const dateInfo = vue.ref(getFormattedDate()); // 异步获取用户名 fetchUserName().then(name => { userName.value = name; }); const loading = vue.ref({ todo: true, homework: false, exam: false, activities: false }); const todoItems = vue.ref([]); const homeworkItems = vue.ref([]); const examItems = vue.ref([]); const activitiesItems = vue.ref([]); // 课程进度数据 const courseProgressItems = vue.ref([]); const loadingProgress = vue.ref(false); const activitiesLoaded = vue.ref(false); const activitiesFetched = vue.ref(false); const activitiesLoadFailed = vue.ref(false); const activitiesLoadIssues = vue.ref([]); const activitiesFromCache = vue.ref(false); const progressLoaded = vue.ref(false); const progressLoadFailed = vue.ref(false); const progressFromCache = vue.ref(false); const progressLastUpdate = vue.ref(null); // 从页面 DOM 中提取 enc 参数 const extractEncFromDOM = (courses) => { console.log('[课程进度] 开始从DOM提取enc参数...'); console.log('[课程进度] 页面URL:', window.location.href); console.log('[课程进度] 页面标题:', document.title); // 先尝试从 courseSquareUrl 中提取 classId (注意是 classId 不是 clazzId) let foundFromSquareUrl = 0; courses.forEach(course => { if (course.courseSquareUrl) { const classIdMatch = course.courseSquareUrl.match(/[?&]classId=(\d+)/); if (classIdMatch) { const classId = classIdMatch[1]; console.log('[课程进度] 课程', course.courseName, 'courseSquareUrl中的classId:', classId); // 注意:courseSquareUrl 中的 classId 对应的是 channel.key (clazzId) // 如果匹配,我们可以尝试使用这个 classId if (String(course.clazzId) === classId) { console.log('[课程进度] 课程', course.courseName, 'clazzId匹配'); } } } }); // 查找课程卡片上的链接 const selectors = [ 'a[href*="mycourse/studentcourse"]', 'a[href*="course/course"]', 'a[href*="mooc2-ans"]', '.course-item a', '.courseCard a', '[class*="course"] a', '#courseList a', '.course-list a' ]; let foundEncCount = 0; // 先打印页面中所有的链接,查找包含关键参数的 console.log('[课程进度] 开始扫描页面所有链接...'); const allLinks = document.querySelectorAll('a[href]'); console.log('[课程进度] 页面共有', allLinks.length, '个链接'); let scannedCount = 0; allLinks.forEach(link => { const href = link.href; if (!href || scannedCount > 100) return; // 只扫描前100个链接 if (href.includes('clazzid') || href.includes('enc') || href.includes('mycourse')) { scannedCount++; console.log('[课程进度] 链接示例:', href.substring(0, 150)); // 从 URL 中提取 enc 参数 const encMatch = href.match(/[?&]enc=([^&]+)/); const clazzIdMatch = href.match(/[?&]clazzid=(\d+)/); if (encMatch && clazzIdMatch) { const enc = encMatch[1]; const clazzId = clazzIdMatch[1]; // 查找对应的课程并更新 enc const course = courses.find(c => String(c.clazzId) === clazzId); if (course && !course.enc) { course.enc = enc; foundEncCount++; console.log('[课程进度] 找到enc:', course.courseName, 'clazzId:', clazzId, 'enc:', enc); } } } }); if (foundEncCount === 0) { console.log('[课程进度] 未从链接中找到enc,尝试从courseSquareUrl提取...'); // courseSquareUrl 格式: https://tsjy.chaoxing.com/plaza/app?courseId=xxx&personId=xxx&classId=xxx&userId=xxx // 这里只有 classId,没有 enc // enc 可能在其他地方 } console.log('[课程进度] 共找到', foundEncCount, '个课程的enc参数'); // 保存到 localStorage 供后续使用 if (foundEncCount > 0) { const encMap = {}; courses.forEach(c => { if (c.enc) { encMap[c.clazzId] = c.enc; } }); localStorage.setItem('chaoxing_course_enc', JSON.stringify(encMap)); console.log('[课程进度] enc参数已保存到localStorage'); // 异步获取 pEnc setTimeout(() => { fetchPEncForCourses(courses); }, 200); } else { // 如果没找到enc,直接尝试获取pEnc(可能会失败,但至少尝试了) console.log('[课程进度] 未找到enc,但仍然尝试获取pEnc...'); setTimeout(() => { fetchPEncForCourses(courses); }, 500); } }; // 获取课程的 pEnc 参数 const fetchPEncForCourses = (courses) => { if (typeof GM_xmlhttpRequest === 'undefined') { console.log('[课程进度] GM_xmlhttpRequest 不可用,跳过获取pEnc'); return; } console.log('[课程进度] 开始获取课程的pEnc参数...'); // 从 stat2-ans.chaoxing.com/study-data/index 页面获取 pEnc // URL格式: https://stat2-ans.chaoxing.com/study-data/index?courseid=xxx&clazzid=xxx&cpi=xxx&ut=s&t=xxx&stuenc=xxx const promises = courses.slice(0, 25).map(course => { return new Promise((resolve) => { // 使用课程数据构建 stat2-ans 页面 URL // stuenc 参数使用 enc(如果有的话),否则使用空字符串 const stuenc = course.enc || ''; const studyIndexUrl = `https://stat2-ans.chaoxing.com/study-data/index?courseid=${course.courseId}&clazzid=${course.clazzId}&cpi=${course.cpi}&ut=s&t=${Date.now()}&stuenc=${stuenc}`; console.log('[课程进度] 获取pEnc, 课程:', course.courseName, 'URL:', studyIndexUrl); GM_xmlhttpRequest({ method: 'GET', url: studyIndexUrl, timeout: 10000, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' }, onload: (response) => { console.log('[课程进度] 获取pEnc响应, 课程:', course.courseName, '状态:', response.status, '长度:', response.responseText.length); // 从响应中提取 pEnc // 尝试多种正则表达式格式 const patterns = [ /pEnc["\s]*[:=]["\s]*([^"'&\s,}]+)/, // pEnc: 'xxx' 或 pEnc: "xxx" /var\s+pEnc\s*=\s*["']([^"']+)["']/, // var pEnc = 'xxx' /pEnc\s*=\s*["']([^"']+)["']/, // pEnc='xxx' ]; let pEnc = null; for (const pattern of patterns) { const match = response.responseText.match(pattern); if (match) { pEnc = match[1].replace(/^["']|["']$/g, ''); console.log('[课程进度] 使用正则找到pEnc:', course.courseName, 'pEnc:', pEnc, 'pattern:', pattern.toString()); break; } } if (pEnc) { course.pEnc = pEnc; // 保存到 localStorage try { const pEncMap = JSON.parse(localStorage.getItem('chaoxing_course_pEnc') || '{}'); pEncMap[course.clazzId] = pEnc; localStorage.setItem('chaoxing_course_pEnc', JSON.stringify(pEncMap)); console.log('[课程进度] pEnc已保存到localStorage:', course.courseName, course.clazzId, pEnc); } catch (e) { console.error('[课程进度] 保存pEnc失败:', e); } } else { console.log('[课程进度] 未找到pEnc:', course.courseName, '响应长度:', response.responseText.length); if (response.responseText.length > 100) { console.log('[课程进度] 响应前200字符:', response.responseText.substring(0, 200)); } } // 同时尝试从响应中提取 enc(如果还没有的话) if (!course.enc && encMatch) { course.enc = encMatch[1]; console.log('[课程进度] 从页面找到enc:', course.courseName, 'enc:', course.enc); try { const encMap = JSON.parse(localStorage.getItem('chaoxing_course_enc') || '{}'); encMap[course.clazzId] = course.enc; localStorage.setItem('chaoxing_course_enc', JSON.stringify(encMap)); } catch (e) { console.error('[课程进度] 保存enc失败:', e); } } resolve(); }, onerror: () => { console.error('[课程进度] 获取pEnc失败:', course.courseName); resolve(); } }); }); }); Promise.all(promises).then(() => { console.log('[课程进度] pEnc获取完成'); }); }; const getAllCourses = async () => { return new Promise((resolve) => { // 使用与课程任务相同的 API const courseListUrl = 'https://mooc1-api.chaoxing.com/mycourse/backclazzdata?view=json&mcode='; if (typeof GM_xmlhttpRequest !== 'undefined') { GM_xmlhttpRequest({ method: 'GET', url: courseListUrl, onload: (response) => { try { console.log('[课程进度] 课程列表响应前200字符:', response.responseText.substring(0, 200)); const data = JSON.parse(response.responseText); const courses = []; if (data && data.channelList) { console.log('[课程进度] channelList 长度:', data.channelList.length); data.channelList.forEach(channel => { // 调试:查看 channel 对象的 keys console.log('[课程进度] Channel keys:', Object.keys(channel)); console.log('[课程进度] Channel cataid:', channel.cataid); console.log('[课程进度] Channel content keys:', channel.content ? Object.keys(channel.content) : 'no content'); console.log('[课程进度] Channel content.enc:', channel.content ? channel.content.enc : 'no enc'); if (channel.cataid === '100000002' && channel.content && channel.content.course) { const courseData = channel.content.course.data; if (courseData && Array.isArray(courseData)) { courseData.forEach(course => { // 调试:查看课程对象的 keys console.log('[课程进度] 课程 keys:', Object.keys(course)); console.log('[课程进度] 课程 enc:', course.enc || '无'); console.log('[课程进度] 课程 courseSquareUrl:', course.courseSquareUrl || '无'); courses.push({ courseId: course.id, clazzId: channel.key, cpi: channel.cpi, courseName: course.name, teacherName: course.teacherfactor || '', // 尝试从 channel.content 中获取 enc 字段 enc: channel.content.enc || course.enc || '', pEnc: channel.content.pEnc || course.pEnc || '' }); }); } } }); } // 同一课程可能在课程列表接口中重复返回,按课程与班级组合键去重, // 避免重复卡片和重复的课程进度请求。 const uniqueCourseMap = new Map(); courses.forEach(course => { const key = `${course.courseId}_${course.clazzId}`; const existing = uniqueCourseMap.get(key); uniqueCourseMap.set(key, existing ? { ...existing, ...course, enc: existing.enc || course.enc || '', pEnc: existing.pEnc || course.pEnc || '' } : course); }); const uniqueCourses = Array.from(uniqueCourseMap.values()); console.log('[课程进度] 解析到课程:', courses.length, '个,去重后:', uniqueCourses.length, '个'); // 从页面 DOM 中提取 enc 参数 setTimeout(() => { extractEncFromDOM(uniqueCourses); }, 100); resolve(uniqueCourses); } catch (e) { console.error('[课程进度] 解析课程列表失败:', e); resolve([]); } }, onerror: (err) => { console.error('[课程进度] 请求课程列表失败:', err); resolve([]); } }); } else { resolve([]); } }); }; // 从学习任务页面HTML中提取AI实践和分组任务数据 const extractTaskDataFromHTML = (html, courseName) => { const result = { aiPractice: '--', groupTask: '--', chapterQuiz: '--', onlineExam: '--', courseWork: '--', interactiveQuiz: '--' }; try { // 提取章节测验 const testNumMatch = html.match(/id="testNum"[^>]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)]*>(\d+)(\d+)\/(\d+)<\/span>/); if (examMatch) { result.onlineExam = `${examMatch[1]}/${examMatch[2]}`; } console.log('[API学习记录]', courseName, '从学习任务页面提取的数据:', result); } catch (e) { console.error('[API学习记录]', courseName, '提取学习任务数据失败:', e); } return result; }; // 获取课程进度 - 从学习记录页面抓取任务点和排名等信息 const getCourseProgress = async (course) => { const courseEntryUrl = `https://mooc1.chaoxing.com/visit/stucoursemiddle?ismooc2=1&courseid=${course.courseId}&clazzid=${course.clazzId}&pageHeader=6`; // 尝试从 localStorage 获取 enc 参数 let enc = course.enc; if (!enc) { try { const encMap = JSON.parse(localStorage.getItem('chaoxing_course_enc') || '{}'); enc = encMap[course.clazzId] || ''; console.log('[API学习记录]', course.courseName, '从localStorage获取enc:', enc || '无'); } catch (e) { console.error('[API学习记录] 读取localStorage失败:', e); } } // 尝试从 localStorage 获取 pEnc 参数 let pEnc = course.pEnc; if (!pEnc) { try { const pEncMap = JSON.parse(localStorage.getItem('chaoxing_course_pEnc') || '{}'); pEnc = (pEncMap[course.clazzId] || '').replace(/^["']|["']$/g, ''); // 去除可能的引号 console.log('[API学习记录]', course.courseName, '从localStorage获取pEnc:', pEnc || '无'); } catch (e) { console.error('[API学习记录] 读取pEnc失败:', e); } } console.log('[API学习记录]', course.courseName, '开始获取学习数据'); console.log('[API学习记录]', course.courseName, '课程信息:', { courseId: course.courseId, clazzId: course.clazzId, cpi: course.cpi, enc: enc, pEnc: pEnc }); return new Promise((resolve) => { if (typeof GM_xmlhttpRequest === 'undefined') { resolve({ ...course, totalTasks: 0, completedTasks: 0, completionRate: '点击查看', unfinishedTasks: [], unfinishedCount: 0, studyDataUrl: courseEntryUrl, isComplete: false, shouldFilter: false, progressTaskCountConfirmed: false, progressReadFailed: true, courseScore: '--', chapterQuiz: '--', ranking: '--', aiPractice: '--', groupTask: '--' }); return; } // 使用已获取的 pEnc if (!pEnc) { pEnc = course.enc || 'stuenc_' + course.clazzId; } console.log('[API学习记录]', course.courseName, '使用的 pEnc:', pEnc); const baseParams = `clazzid=${course.clazzId}&courseid=${course.courseId}&cpi=${course.cpi}&ut=s&pEnc=${pEnc}`; const jobUrl = `https://stat2-ans.chaoxing.com/stat2/study-data/job?${baseParams}`; const pointUrl = 'https://stat2-ans.chaoxing.com/stat2/study-data/point'; const studyDataIndexUrl = `https://stat2-ans.chaoxing.com/study-data/index?courseid=${course.courseId}&clazzid=${course.clazzId}&cpi=${course.cpi}&ut=s`; console.log('[API学习记录]', course.courseName, 'job API URL:', jobUrl); console.log('[API学习记录]', course.courseName, 'baseParams:', baseParams); console.log('[API学习记录]', course.courseName, 'studyDataIndexUrl:', studyDataIndexUrl); let completedTasks = 0; let totalTasks = 0; let completionRate = '点击查看'; let shouldFilter = false; let progressTaskCountConfirmed = false; let courseScore = '--'; let chapterQuiz = '--'; let ranking = '--'; let aiPractice = '--'; let groupTask = '--'; const finishResolve = () => { const unfinishedCount = Math.max(totalTasks - completedTasks, 0); resolve({ ...course, totalTasks, completedTasks, completionRate, unfinishedTasks: [], unfinishedCount, studyDataUrl: courseEntryUrl, isComplete: totalTasks > 0 && completedTasks >= totalTasks, shouldFilter, progressTaskCountConfirmed, progressReadFailed: !progressTaskCountConfirmed, courseScore, chapterQuiz, ranking, aiPractice, groupTask }); }; let successCount = 0; const checkAllDone = () => { successCount++; if (successCount >= 5) { console.log('[API学习记录]', course.courseName, '任务点:', `${completedTasks}/${totalTasks}`, '排名:', ranking, '积分:', courseScore, '章节测验:', chapterQuiz, 'AI实践:', aiPractice, '分组任务:', groupTask); finishResolve(); } }; const handleError = (errorMsg) => { console.error('[API学习记录]', course.courseName, errorMsg); resolve({ ...course, totalTasks: 0, completedTasks: 0, completionRate: '点击查看', unfinishedTasks: [], unfinishedCount: 0, studyDataUrl: courseEntryUrl, isComplete: false, shouldFilter: false, progressTaskCountConfirmed: false, progressReadFailed: true, courseScore: '--', chapterQuiz: '--', ranking: '--', aiPractice: '--', groupTask: '--' }); }; GM_xmlhttpRequest({ method: 'GET', url: jobUrl, timeout: 10000, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Referer': `https://stat2-ans.chaoxing.com/study-data/index?courseid=${course.courseId}&clazzid=${course.clazzId}&cpi=${course.cpi}&ut=s` }, onload: (response) => { console.log('[API学习记录]', course.courseName, 'job API响应状态:', response.status); console.log('[API学习记录]', course.courseName, 'job API响应内容前200字符:', response.responseText.substring(0, 200)); try { const data = JSON.parse(response.responseText); if (data.status && data.data) { const jobData = data.data; ranking = jobData.jobRank ? `第${jobData.jobRank}名` : '--'; chapterQuiz = jobData.job ? `${jobData.job}/${jobData.publishJobNum || jobData.job}` : '--'; totalTasks = jobData.publishJobNum || jobData.job || 0; completedTasks = jobData.job || 0; completionRate = jobData.jobPer ? `${jobData.jobPer}%` : '0%'; progressTaskCountConfirmed = true; // AI实践 const aiEvaluateReachCount = jobData.aiEvaluateReachCount !== undefined ? jobData.aiEvaluateReachCount : '--'; const publishLibraryNum = jobData.publishLibraryNum !== undefined ? jobData.publishLibraryNum : '--'; aiPractice = (aiEvaluateReachCount !== '--' && publishLibraryNum !== '--') ? `${aiEvaluateReachCount}/${publishLibraryNum}` : '--'; // 分组任务 const taskNum = jobData.taskNum !== undefined ? jobData.taskNum : '--'; const publishTaskNum = jobData.publishTaskNum !== undefined ? jobData.publishTaskNum : '--'; groupTask = (taskNum !== '--' && publishTaskNum !== '--') ? `${taskNum}/${publishTaskNum}` : '--'; console.log('[API学习记录]', course.courseName, '排名:', ranking, '章节测验:', chapterQuiz, 'AI实践:', aiPractice, '分组任务:', groupTask, 'jobData:', JSON.stringify(jobData).substring(0, 500)); } else { console.log('[API学习记录]', course.courseName, 'job API返回数据无效:', data); } } catch (e) { console.error('[API学习记录]', course.courseName, 'job API解析失败:', e); } checkAllDone(); }, onerror: () => { console.error('[API学习记录]', course.courseName, 'job API请求失败'); checkAllDone(); }, ontimeout: () => { console.error('[API学习记录]', course.courseName, 'job API请求超时'); checkAllDone(); } }); GM_xmlhttpRequest({ method: 'POST', url: pointUrl, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'Referer': `https://stat2-ans.chaoxing.com/study-data/index?courseid=${course.courseId}&clazzid=${course.clazzId}&cpi=${course.cpi}&ut=s` }, data: baseParams, timeout: 10000, onload: (response) => { console.log('[API学习记录]', course.courseName, 'point API响应状态:', response.status); console.log('[API学习记录]', course.courseName, 'point API响应内容:', response.responseText); try { const data = JSON.parse(response.responseText); console.log('[API学习记录]', course.courseName, 'point API响应数据:', data); if (data.ponits !== undefined) { courseScore = `${data.ponits}分`; console.log('[API学习记录]', course.courseName, '积分:', courseScore); } else { console.log('[API学习记录]', course.courseName, 'point API无有效数据'); } } catch (e) { console.error('[API学习记录]', course.courseName, 'point API解析失败:', e); } checkAllDone(); }, onerror: () => { console.error('[API学习记录]', course.courseName, 'point API请求失败'); checkAllDone(); }, ontimeout: () => { console.error('[API学习记录]', course.courseName, 'point API请求超时'); checkAllDone(); } }); // AI实践API const aiEvaluateUrl = `https://stat2-ans.chaoxing.com/stat2/study-data/ai-evaluate-stat?${baseParams}`; console.log('[API学习记录]', course.courseName, '请求AI实践API:', aiEvaluateUrl); GM_xmlhttpRequest({ method: 'GET', url: aiEvaluateUrl, timeout: 10000, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Referer': `https://stat2-ans.chaoxing.com/study-data/index?courseid=${course.courseId}&clazzid=${course.clazzId}&cpi=${course.cpi}&ut=s` }, onload: (response) => { console.log('[API学习记录]', course.courseName, 'AI实践API响应状态:', response.status); try { const data = JSON.parse(response.responseText); if (data.status && data.data) { const aiData = data.data; const aiEvaluateReachCount = aiData.aiEvaluateReachCount !== undefined ? aiData.aiEvaluateReachCount : '--'; const publishLibraryNum = aiData.publishLibraryNum !== undefined ? aiData.publishLibraryNum : '--'; aiPractice = (aiEvaluateReachCount !== '--' && publishLibraryNum !== '--') ? `${aiEvaluateReachCount}/${publishLibraryNum}` : '--'; console.log('[API学习记录]', course.courseName, 'AI实践数据:', aiPractice); } else { console.log('[API学习记录]', course.courseName, 'AI实践API返回数据无效:', data); } } catch (e) { console.error('[API学习记录]', course.courseName, 'AI实践API解析失败:', e); } checkAllDone(); }, onerror: (err) => { console.error('[API学习记录]', course.courseName, 'AI实践API请求失败:', err); checkAllDone(); }, ontimeout: () => { console.error('[API学习记录]', course.courseName, 'AI实践API请求超时'); checkAllDone(); } }); // 分组任务API const groupTaskUrl = `https://stat2-ans.chaoxing.com/stat2/study-data/groupTask?${baseParams}`; console.log('[API学习记录]', course.courseName, '请求分组任务API:', groupTaskUrl); GM_xmlhttpRequest({ method: 'GET', url: groupTaskUrl, timeout: 10000, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Referer': `https://stat2-ans.chaoxing.com/study-data/index?courseid=${course.courseId}&clazzid=${course.clazzId}&cpi=${course.cpi}&ut=s` }, onload: (response) => { console.log('[API学习记录]', course.courseName, '分组任务API响应状态:', response.status); try { const data = JSON.parse(response.responseText); if (data.status && data.data) { const taskData = data.data; const taskNum = taskData.taskNum !== undefined ? taskData.taskNum : '--'; const publishTaskNum = taskData.publishTaskNum !== undefined ? taskData.publishTaskNum : '--'; groupTask = (taskNum !== '--' && publishTaskNum !== '--') ? `${taskNum}/${publishTaskNum}` : '--'; console.log('[API学习记录]', course.courseName, '分组任务数据:', groupTask); } else { console.log('[API学习记录]', course.courseName, '分组任务API返回数据无效:', data); } } catch (e) { console.error('[API学习记录]', course.courseName, '分组任务API解析失败:', e); } checkAllDone(); }, onerror: (err) => { console.error('[API学习记录]', course.courseName, '分组任务API请求失败:', err); checkAllDone(); }, ontimeout: () => { console.error('[API学习记录]', course.courseName, '分组任务API请求超时'); checkAllDone(); } }); // 请求学习任务页面,获取AI实践和分组任务数据 const taskPageUrl = `https://mooc1.chaoxing.com/visit/stucoursemiddle?ismooc2=1&courseid=${course.courseId}&clazzid=${course.clazzId}&pageHeader=6`; console.log('[API学习记录]', course.courseName, '请求学习任务页面:', taskPageUrl); GM_xmlhttpRequest({ method: 'GET', url: taskPageUrl, timeout: 15000, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Referer': 'https://mooc1.chaoxing.com/' }, onload: (response) => { console.log('[API学习记录]', course.courseName, '学习任务页面响应状态:', response.status); try { const html = response.responseText; const taskData = extractTaskDataFromHTML(html, course.courseName); // 如果从job API没有获取到数据,使用从HTML提取的数据 if (aiPractice === '--' && taskData.aiPractice !== '--') { aiPractice = taskData.aiPractice; console.log('[API学习记录]', course.courseName, '使用HTML数据更新AI实践:', aiPractice); } if (groupTask === '--' && taskData.groupTask !== '--') { groupTask = taskData.groupTask; console.log('[API学习记录]', course.courseName, '使用HTML数据更新分组任务:', groupTask); } // 同时更新章节测验数据(如果API没有返回) if (chapterQuiz === '--' && taskData.chapterQuiz !== '--') { chapterQuiz = taskData.chapterQuiz; } console.log('[API学习记录]', course.courseName, '学习任务页面数据提取完成:', taskData); } catch (e) { console.error('[API学习记录]', course.courseName, '解析学习任务页面失败:', e); } checkAllDone(); }, onerror: (err) => { console.error('[API学习记录]', course.courseName, '请求学习任务页面失败:', err); checkAllDone(); }, ontimeout: () => { console.error('[API学习记录]', course.courseName, '请求学习任务页面超时'); checkAllDone(); } }); }); }; const syncActivitiesToTodo = (allActivities) => { const ongoingActivities = allActivities .filter(activity => activity.ongoing) .map(activity => ({ type: activity.type, title: activity.title, course: activity.courseName, info: activity.endTime || (activity.progressText ? `进度 ${activity.progressText}` : '进行中'), leftTime: activity.endTime || activity.leftTime || '', timeLeft: activity.endTime || activity.timeLeft || '', endTime: activity.endTime || '', endTimeTimestamp: activity.endTimeTimestamp ?? '', status: '进行中', courseId: activity.courseId, clazzId: activity.clazzId, activeId: activity.activeId, taskId: activity.taskId, planId: activity.planId, taskEngine: activity.taskEngine, taskEnginePlan: activity.taskEnginePlan, taskLink: activity.taskLink, isActivity: true, finished: activity.finished, expired: activity.expired, ongoing: activity.ongoing, uncommitted: activity.uncommitted })) .map(item => ({ ...item, isUrgent: isTodoItemUrgent(item) })); todoItems.value = [...todoItems.value.filter(item => !item.isActivity), ...ongoingActivities] .sort(compareTodoItemsByDeadline); scheduleDeadlineReminderEvaluation(); }; const hydrateShortTermCache = () => { if (!settings.value.shortTermCacheEnabled) return; const cache = cleanupDashboardCache(); if (Array.isArray(cache['activities-v2']?.data)) { activitiesItems.value = cache['activities-v2'].data; activitiesLoaded.value = true; activitiesFromCache.value = true; syncActivitiesToTodo(cache['activities-v2'].data); } if (Array.isArray(cache.progress?.data)) { courseProgressItems.value = cache.progress.data; progressLoaded.value = true; progressFromCache.value = true; progressLastUpdate.value = new Date(cache.progress.savedAt).toLocaleTimeString(); } }; // 加载所有课程进度(带延迟机制) const loadAllCourseProgress = async () => { if (loadingProgress.value) return; if (!isProgressEnabled()) { console.log('[课程进度] 查询功能已关闭,跳过加载'); courseProgressItems.value = []; progressLoaded.value = true; progressLoadFailed.value = false; return; } console.log('[课程进度] 开始加载课程进度...'); loadingProgress.value = true; progressLoadFailed.value = false; try { const courses = await getAllCourses(); const activeCourses = courses.filter(course => !isCourseIgnored(course)); console.log(`[课程进度] 获取到课程: ${courses.length} 个,已忽略: ${courses.length - activeCourses.length} 个,待查询: ${activeCourses.length} 个`); if (activeCourses.length > 0) { const requestDelay = getProgressDelay(); console.log('[课程进度] 使用请求延迟:', requestDelay, 'ms'); // 使用延迟机制逐个请求,避免触发验证码 const results = []; for (let i = 0; i < activeCourses.length; i++) { const course = activeCourses[i]; // 运行中若刚被忽略,则跳过尚未发出的进度 API 请求。 if (isCourseIgnored(course)) { console.log(`[课程进度] 跳过已忽略课程: ${course.courseName}`); continue; } console.log(`[课程进度] 正在获取第 ${i + 1}/${activeCourses.length} 个课程...`); const result = await getCourseProgress(course); results.push(result); // 如果不是最后一个课程,等待延迟时间 if (i < activeCourses.length - 1) { await delay(requestDelay); } } // 过滤后按完成率从低到高排列;没有有效完成率的课程放在末尾。 courseProgressItems.value = results .filter(item => !item.shouldFilter) // 过滤掉标记为需要过滤的课程 .sort(compareCourseProgress); progressLastUpdate.value = new Date().toLocaleTimeString(); } else { courseProgressItems.value = []; progressLastUpdate.value = new Date().toLocaleTimeString(); } progressLoaded.value = true; progressFromCache.value = false; if (settings.value.shortTermCacheEnabled) saveDashboardCache('progress', courseProgressItems.value); if (!settings.value.zeroTaskSuggestSeen && !tourActive.value) { triggerZeroTaskSuggestIfNeeded(false); } startProgressAutoRefresh(); } catch (e) { console.error('加载课程进度失败:', e); progressLoadFailed.value = true; progressLoaded.value = true; } loadingProgress.value = false; }; // 自动刷新课程进度(每1小时) let progressRefreshTimer = null; const startProgressAutoRefresh = () => { if (progressRefreshTimer) clearInterval(progressRefreshTimer); progressRefreshTimer = setInterval(() => { loadAllCourseProgress(); }, 60 * 60 * 1000); // 1小时 }; // 当前视图状态:'dashboard' | 'todo' | 'homework' | 'exam' | 'activities' | 'progress' const currentView = vue.ref('dashboard'); let dashboardSkeletonTimer = null; const dashboardSkeletonOverlay = vue.ref(false); const dashboardSkeletonFading = vue.ref(false); const settings = vue.ref(getSettings()); const settingsVersion = vue.ref(0); const progressDelay = vue.ref(getProgressDelay()); const settingsCourses = vue.ref([]); const settingsCoursesLoading = vue.ref(false); const showCourseIgnoreDialog = vue.ref(false); const showOtherTasksDialog = vue.ref(false); const showBulkIgnoreDialog = vue.ref(false); const bulkIgnoreSelection = vue.ref(new Set()); const bulkIgnoreOptions = [ { key: 'homework', label: '已完成作业(含 AI 实践)' }, { key: 'exam', label: '已完成或已过期考试' }, { key: 'activities', label: '已结束课程任务' }, { key: 'progress', label: '已完成课程进度' } ]; const settingsToast = vue.ref(''); let settingsToastTimer = null; const searchQuery = vue.ref(''); const detailSegment = vue.ref('all'); const activeDashboardTab = vue.ref('todo'); const dashboardTabFilter = vue.ref(settings.value.defaultTaskFilter || 'pending'); const activeActivityCategory = vue.ref('all'); const visibleListLimit = vue.ref(60); const progressSideFilter = vue.ref('ongoing'); const progressDetailSegment = vue.ref('ongoing'); const hoveredProgressCourse = vue.ref(null); const hoveredProgressRect = vue.ref(null); const showZeroTaskSuggestDialog = vue.ref(false); const zeroTaskSuggestCourses = vue.ref([]); const zeroTaskSelectedKeys = vue.ref(new Set()); const lastCourseIgnoreIdx = vue.ref(-1); const lastZeroTaskIdx = vue.ref(-1); const tourActive = vue.ref(false); const tourStepIndex = vue.ref(0); const tourSpotlightRect = vue.ref(null); const TOUR_STEPS = [ { selector: '.cx-topbar', title: '顶部命令栏与快捷键', desc: '右侧集中了主题切换、低风控轻量刷新与工作台设置;随时按 Ctrl+K 可快速聚焦中间搜索框。' }, { selector: '.cx-kpi-grid', title: '核心 KPI 指标卡', desc: '一眼掌握待交作业、进行中活动、待考考试与全部课程;点击前三张卡片可直接切换到对应未完成列表。' }, { selector: '.cx-primary-panel', title: '主任务工作台(默认未完成)', desc: '支持 4 大分类秒切,课程任务已对齐类别列并提供二级胶囊筛选;点击任意作业、讨论、问卷或考试即可直达。' }, { selector: '.cx-side-rail > .cx-side-panel:first-child', title: '24h 紧急焦点与顶部提醒', desc: '未来 24 小时内截止的任务会集中显示在这里,搭配顶部命令栏下方的琥珀提醒条,重要任务不再遗漏。' }, { selector: '.cx-side-rail > .cx-side-panel:last-child', title: '课程进度与 0 任务点清理', desc: '默认聚焦进行中课程,悬停即可查看活动明细;全屏进度页支持一键隐藏 0 任务点课程(支持 Shift 连选)。' }, { selector: '.cx-btn-primary', title: '设置中心与帮助指南', desc: '可配置默认筛选、定时同步与 JSON 跨端迁移;随时可在「设置 → 帮助与指南」查看 Q&A 或重看本教程。' } ]; const TOUR_DEMO_DATA = { todo: [ { type: '作业', title: '[演示] 实验报告四:数据结构综合实验', course: '数据结构与算法', leftTime: '剩余 4小时20分', isUrgent: true, uncommitted: true, courseId: '0', clazzId: '0' }, { type: '分组讨论', title: '[演示] 结合文献案例分析研究方法设计', course: '科技论文写作', leftTime: '剩余 11小时05分', isUrgent: true, isActivity: true, ongoing: true, status: '进行中', courseId: '0', clazzId: '0' }, { type: '考试', title: '[演示] 期中随堂在线测验', course: '高等数学(上)', timeLeft: '剩余 2天3小时', leftTime: '剩余 2天3小时', finished: false, expired: false, courseId: '0', classId: '0' } ], homework: [ { type: '作业', title: '[演示] 实验报告四:数据结构综合实验', course: '数据结构与算法', leftTime: '剩余 4小时20分', uncommitted: true, courseId: '0', clazzId: '0' }, { type: '作业', title: '[演示] 第三章课后习题提交', course: '大学英语精读', leftTime: '剩余 3天12小时', uncommitted: true, courseId: '0', clazzId: '0' } ], exam: [ { type: '考试', title: '[演示] 期中随堂在线测验', course: '高等数学(上)', timeLeft: '剩余 2天3小时', finished: false, expired: false, courseId: '0', classId: '0' } ], activities: [ { title: '[演示] 结合文献案例分析研究方法设计', type: '分组讨论', status: '进行中', ongoing: true, finished: false, courseName: '科技论文写作', leftTime: '剩余 11小时05分', isActivity: true }, { title: '[演示] 课程满意度与教学反馈问卷', type: '问卷', status: '进行中', ongoing: true, finished: false, courseName: '形势与政策', leftTime: '进行中', isActivity: true }, { title: '[演示] 第五讲课堂随堂练习', type: '随堂练习', status: '进行中', ongoing: true, finished: false, courseName: '线性代数', leftTime: '进行中', isActivity: true } ], progress: [ { courseName: '[演示] 数据结构与算法', completionRate: '78%', completedTasks: 31, totalTasks: 40, courseId: '0', clazzId: '0' }, { courseName: '[演示] 高等数学(上)', completionRate: '92%', completedTasks: 46, totalTasks: 50, courseId: '0', clazzId: '0' } ] }; const updateTourSpotlight = () => { if (!tourActive.value) { tourSpotlightRect.value = null; return; } const step = TOUR_STEPS[tourStepIndex.value]; if (!step) return; const el = document.querySelector(step.selector); if (!el) { tourSpotlightRect.value = null; return; } try { el.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } catch {} setTimeout(() => { const rect = el.getBoundingClientRect(); tourSpotlightRect.value = { top: Math.max(8, rect.top - 4), left: Math.max(8, rect.left - 4), width: Math.min(window.innerWidth - 16, rect.width + 8), height: Math.min(window.innerHeight - 16, rect.height + 8), bottom: rect.bottom + 4, right: rect.right + 4 }; }, 80); }; const startOnboardingTour = () => { currentView.value = 'dashboard'; activeDashboardTab.value = 'todo'; dashboardTabFilter.value = settings.value.defaultTaskFilter || 'pending'; tourStepIndex.value = 0; tourActive.value = true; setTimeout(updateTourSpotlight, 120); }; const finishOnboardingTour = () => { tourActive.value = false; tourSpotlightRect.value = null; if (!settings.value.onboardingTourSeen) { updateSetting('onboardingTourSeen', true); } }; const nextTourStep = () => { if (tourStepIndex.value >= TOUR_STEPS.length - 1) { finishOnboardingTour(); } else { tourStepIndex.value++; setTimeout(updateTourSpotlight, 60); } }; const prevTourStep = () => { if (tourStepIndex.value > 0) { tourStepIndex.value--; setTimeout(updateTourSpotlight, 60); } }; const isZeroTaskCourse = (course) => hasCourseProgressTaskCount(course) && Number(course.totalTasks) === 0 && course?.progressTaskCountConfirmed === true && course?.progressReadFailed !== true; const isOngoingProgressCourse = (course) => { if (isZeroTaskCourse(course)) return false; const rate = getCourseCompletionRate(course); return rate !== null && rate < 100; }; const isCompletedProgressCourse = (course) => { if (isZeroTaskCourse(course)) return false; const rate = getCourseCompletionRate(course); return course?.isComplete === true || (rate !== null && rate >= 100); }; const triggerZeroTaskSuggestIfNeeded = (isManual = false) => { const candidates = courseProgressItems.value.filter(c => isZeroTaskCourse(c) && !isCourseIgnored(c)); if (!candidates.length) { if (isManual) notifySettingsSaved('当前没有未忽略的 0 任务点课程'); return; } zeroTaskSuggestCourses.value = candidates; zeroTaskSelectedKeys.value = new Set(candidates.map(c => getCourseIgnoreKey(c))); lastZeroTaskIdx.value = -1; showZeroTaskSuggestDialog.value = true; }; const toggleZeroTaskSelection = (course, idx, e) => { const key = getCourseIgnoreKey(course); const next = new Set(zeroTaskSelectedKeys.value); const targetChecked = e?.target ? Boolean(e.target.checked) : !next.has(key); if (e?.shiftKey && lastZeroTaskIdx.value >= 0 && idx >= 0) { const start = Math.min(lastZeroTaskIdx.value, idx); const end = Math.max(lastZeroTaskIdx.value, idx); for (let i = start; i <= end; i++) { const c = zeroTaskSuggestCourses.value[i]; if (!c) continue; const k = getCourseIgnoreKey(c); if (targetChecked) next.add(k); else next.delete(k); } } else { if (targetChecked) next.add(key); else next.delete(key); } lastZeroTaskIdx.value = idx; zeroTaskSelectedKeys.value = next; }; const handleCourseIgnoreCheckboxClick = (course, idx, e) => { const targetChecked = Boolean(e?.target?.checked); if (e?.shiftKey && lastCourseIgnoreIdx.value >= 0 && idx >= 0) { const start = Math.min(lastCourseIgnoreIdx.value, idx); const end = Math.max(lastCourseIgnoreIdx.value, idx); for (let i = start; i <= end; i++) { const c = settingsCourses.value[i]; if (c) toggleCourseIgnored(c, targetChecked); } } else { toggleCourseIgnored(course, targetChecked); } lastCourseIgnoreIdx.value = idx; }; const applyZeroTaskIgnore = () => { const selected = zeroTaskSuggestCourses.value.filter(c => zeroTaskSelectedKeys.value.has(getCourseIgnoreKey(c))); selected.forEach(c => toggleCourseIgnored(c, true)); updateSetting('zeroTaskSuggestSeen', true); showZeroTaskSuggestDialog.value = false; if (selected.length > 0) { notifySettingsSaved(`已隐藏 ${selected.length} 门 0 任务点课程,可在「已忽略」随时恢复`); } }; const dismissZeroTaskSuggest = () => { updateSetting('zeroTaskSuggestSeen', true); showZeroTaskSuggestDialog.value = false; }; const activeSettingsTab = vue.ref('general'); const lightRefreshing = vue.ref(false); let lastLightRefreshAt = 0; const showConfigTransferDialog = vue.ref(false); const configTransferMode = vue.ref('export'); const configTransferText = vue.ref(''); const customSyncTimeInput = vue.ref(''); const notifySettingsSaved = (message = '设置已保存,已实时应用') => { settingsToast.value = message; if (settingsToastTimer) clearTimeout(settingsToastTimer); settingsToastTimer = setTimeout(() => { settingsToast.value = ''; }, 2600); }; const updateSetting = (key, value, event = null) => { settings.value = { ...settings.value, [key]: value }; saveSettings(settings.value); settingsVersion.value++; if (key === 'themeMode') applyThemeMode(value, event); if (key === 'defaultTaskFilter') dashboardTabFilter.value = value || 'pending'; if (key === 'deadlineReminderEnabled' || key === 'deadlineBrowserNotificationEnabled') evaluateDeadlineReminders(); }; const getThemeModeMeta = (mode = settings.value.themeMode) => { if (mode === 'dark') return { icon: 'moon', label: '深色' }; if (mode === 'light') return { icon: 'sun', label: '浅色' }; return { icon: 'contrast', label: '跟随系统' }; }; const cycleThemeMode = (event = null) => { const order = ['system', 'light', 'dark']; const current = settings.value.themeMode || 'system'; const next = order[(order.indexOf(current) + 1) % order.length]; updateSetting('themeMode', next, event); }; const toggleScheduledSyncTime = (timeStr) => { const current = Array.isArray(settings.value.scheduledSyncTimes) ? [...settings.value.scheduledSyncTimes] : [...DEFAULT_SETTINGS.scheduledSyncTimes]; if (current.includes(timeStr)) { if (current.length <= 1) return; updateSetting('scheduledSyncTimes', current.filter(t => t !== timeStr)); } else { updateSetting('scheduledSyncTimes', [...current, timeStr].sort()); } }; const addCustomScheduledSyncTime = () => { const val = String(customSyncTimeInput.value || '').trim(); if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(val)) { notifySettingsSaved('请输入 24 小时制 HH:mm(例如 09:30)'); return; } const current = Array.isArray(settings.value.scheduledSyncTimes) ? settings.value.scheduledSyncTimes : []; if (!current.includes(val)) { updateSetting('scheduledSyncTimes', [...current, val].sort()); } customSyncTimeInput.value = ''; notifySettingsSaved(`已添加定时同步时间 ${val}`); }; const openConfigExportDialog = () => { configTransferMode.value = 'export'; configTransferText.value = exportScriptConfigJson(); showConfigTransferDialog.value = true; }; const openConfigImportDialog = () => { configTransferMode.value = 'import'; configTransferText.value = ''; showConfigTransferDialog.value = true; }; const copyExportedConfig = async () => { try { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(configTransferText.value); notifySettingsSaved('配置 JSON 已复制到剪贴板'); } else { notifySettingsSaved('请手动全选复制文本框中的 JSON'); } } catch { notifySettingsSaved('复制失败,请手动全选复制'); } }; const applyImportedConfig = () => { try { const next = importScriptConfigJson(configTransferText.value); settings.value = next; progressDelay.value = getProgressDelay(); ignoredVersion.value++; settingsVersion.value++; applyThemeMode(next.themeMode); showConfigTransferDialog.value = false; notifySettingsSaved('配置已导入并实时生效'); } catch (err) { notifySettingsSaved(`导入失败:${err?.message || 'JSON 格式错误'}`); } }; const updateProgressDelay = (value) => { progressDelay.value = setProgressDelay(value); notifySettingsSaved(`课程进度请求间隔已设为 ${progressDelay.value}ms,下次查询生效`); }; const shouldDisplayItem = (item) => { settingsVersion.value; const section = item._sectionType || 'unknown'; return !isItemIgnored(item, section) && !isDynamicallyIgnored(item, section, settings.value) && isOtherTaskVisible(item, settings.value); }; const loadSettingsCourses = async () => { if (settingsCoursesLoading.value || settingsCourses.value.length) return; settingsCoursesLoading.value = true; try { settingsCourses.value = await fetchCourseList(); } catch (error) { console.error('[设置] 获取课程列表失败', error); } finally { settingsCoursesLoading.value = false; } }; const openSettings = async () => { currentView.value = 'settings'; }; const openCourseIgnoreDialog = async () => { lastCourseIgnoreIdx.value = -1; showCourseIgnoreDialog.value = true; await loadSettingsCourses(); }; const openCourseIgnoreFromHint = () => { updateSetting('courseIgnoreHintSeen', true); currentView.value = 'settings'; openCourseIgnoreDialog(); }; const toggleOtherTaskType = (type, checked) => { const selected = new Set(settings.value.otherTaskTypes || []); if (checked) selected.add(type); else selected.delete(type); updateSetting('otherTaskTypes', Array.from(selected)); }; const getOtherTasksSummary = () => { if (settings.value.showOtherTasks) return '显示全部其他任务'; const selected = settings.value.otherTaskTypes || []; return selected.length ? `已选 ${selected.length} 类` : '默认不显示'; }; const toggleCourseIgnored = (course, checked) => { if (checked) { ignoreCourse(course); } else { unignoreCourse(course); if (activitiesFetched.value) scheduleRestoredCourseActivities([course]); } ignoredVersion.value++; }; const toggleBulkIgnoreType = (key, checked) => { const selected = new Set(bulkIgnoreSelection.value); if (checked) selected.add(key); else selected.delete(key); bulkIgnoreSelection.value = selected; }; const openBulkIgnoreDialog = () => { const rules = settings.value.dynamicIgnoreRules || {}; bulkIgnoreSelection.value = new Set(bulkIgnoreOptions .filter(option => rules[option.key]) .map(option => option.key)); showBulkIgnoreDialog.value = true; }; const getCompletedItemsForBulkIgnore = (section) => { switch (section) { case 'homework': return [...homeworkItems.value, ...activitiesItems.value.filter(isRoutedToHomework)] .filter(isExplicitlyCompletedHomework); case 'exam': return [...examItems.value, ...activitiesItems.value.filter(isRoutedToExam)] .filter(isExplicitlyClosedExam); case 'activities': return activitiesItems.value .filter(item => !isRoutedToHomework(item) && !isRoutedToExam(item) && isExplicitlyEndedActivity(item)); case 'progress': return courseProgressItems.value.filter(isExplicitlyCompletedProgress); default: return []; } }; const getBulkIgnorePreviewItems = () => { const sectionLabels = { homework: '作业', exam: '考试', activities: '课程任务', progress: '课程进度' }; const seen = new Set(); const preview = []; bulkIgnoreSelection.value.forEach(section => { getCompletedItemsForBulkIgnore(section).forEach(item => { const key = `${section}__${item.courseId || ''}__${item.clazzId || item.classId || ''}__${item.workId || item.examId || item.id || item.title || item.courseName || ''}`; if (seen.has(key)) return; seen.add(key); preview.push({ item, section, label: sectionLabels[section] }); }); }); return preview; }; const runBulkIgnore = () => { const selected = bulkIgnoreSelection.value; const dynamicIgnoreRules = Object.fromEntries(bulkIgnoreOptions .map(option => [option.key, selected.has(option.key)])); updateSetting('dynamicIgnoreRules', dynamicIgnoreRules); showBulkIgnoreDialog.value = false; bulkIgnoreSelection.value = new Set(); notifySettingsSaved('动态忽略规则已保存,列表已实时更新'); }; // --- 忽略功能状态 --- const ignoredVersion = vue.ref(0); // 递增触发响应式更新 const showIgnoreConfirm = vue.ref(false); // 显示确认弹窗 const ignoreConfirmItems = vue.ref([]); // 待确认忽略的项 const ignoreConfirmSection = vue.ref('unknown'); // 待确认忽略的板块类型 const selectMode = vue.ref(false); // 多选模式 const selectedForIgnore = vue.ref(new Set()); // 多选忽略的 key 集合 const selectedItemsMap = vue.ref(new Map()); // key -> item 映射 const showIgnoredPanel = vue.ref(false); // 显示已忽略面板 const selectedForRestore = vue.ref(new Set()); // 多选恢复的 key 集合 // 执行忽略(弹出确认)- 需要传入 sectionType const requestIgnore = (items, sectionType) => { ignoreConfirmItems.value = Array.isArray(items) ? items : [items]; ignoreConfirmSection.value = sectionType || 'unknown'; showIgnoreConfirm.value = true; }; // 确认忽略 const confirmIgnore = () => { ignoreItems(ignoreConfirmItems.value, ignoreConfirmSection.value); ignoredVersion.value++; showIgnoreConfirm.value = false; ignoreConfirmItems.value = []; ignoreConfirmSection.value = 'unknown'; // 退出多选模式 selectMode.value = false; selectedForIgnore.value = new Set(); selectedItemsMap.value = new Map(); }; // 取消忽略 const cancelIgnore = () => { showIgnoreConfirm.value = false; ignoreConfirmItems.value = []; ignoreConfirmSection.value = 'unknown'; }; // 切换多选 const toggleSelectMode = () => { selectMode.value = !selectMode.value; if (!selectMode.value) { selectedForIgnore.value = new Set(); selectedItemsMap.value = new Map(); } }; // 多选操作(传入 sectionType 使 key 包含板块前缀) const toggleSelectItem = (item, sectionType) => { const key = getItemKey(item, sectionType); const newSet = new Set(selectedForIgnore.value); const newMap = new Map(selectedItemsMap.value); if (newSet.has(key)) { newSet.delete(key); newMap.delete(key); } else { newSet.add(key); newMap.set(key, item); } selectedForIgnore.value = newSet; selectedItemsMap.value = newMap; }; // 批量忽略所选 const batchIgnoreSelected = () => { const items = Array.from(selectedItemsMap.value.values()); if (items.length > 0) { requestIgnore(items, ignoreConfirmSection.value || currentView.value); } }; // 恢复忽略(多选) const toggleRestoreItem = (key) => { const newSet = new Set(selectedForRestore.value); if (newSet.has(key)) { newSet.delete(key); } else { newSet.add(key); } selectedForRestore.value = newSet; }; const batchRestore = () => { const keys = Array.from(selectedForRestore.value); unignoreByKeys(keys); selectedForRestore.value = new Set(); ignoredVersion.value++; if (activitiesFetched.value && keys.some(k => k.startsWith(COURSE_IGNORE_PREFIX))) { scheduleRestoredCourseActivitiesByKeys(keys); } }; const restoreSingle = (key) => { unignoreByKey(key); ignoredVersion.value++; if (activitiesFetched.value && String(key || '').startsWith(COURSE_IGNORE_PREFIX)) { scheduleRestoredCourseActivitiesByKeys([key]); } }; const matchesSearchQuery = (item) => { const q = String(searchQuery.value || '').trim().toLowerCase(); if (!q) return true; const fields = [item?.title, item?.course, item?.courseName, item?.type].filter(Boolean); return fields.some(f => String(f).toLowerCase().includes(q)); }; // 过滤已忽略项的计算属性(传入对应板块的 sectionType) const filteredTodoItems = vue.computed(() => { ignoredVersion.value; // 触发依赖 return todoItems.value.filter(item => shouldDisplayItem({ ...item, _sectionType: 'todo' }) && matchesSearchQuery(item)); }); const isRoutedToHomework = (item) => item.type === 'AI实践' || (item.taskEnginePlan && item.type === '作业'); const isRoutedToExam = (item) => item.taskEnginePlan && item.type === '考试'; const filteredHomeworkItems = vue.computed(() => { ignoredVersion.value; const routedItems = activitiesItems.value.filter(isRoutedToHomework); return [...homeworkItems.value, ...routedItems] .filter(item => shouldDisplayItem({ ...item, _sectionType: 'homework' }) && matchesSearchQuery(item)); }); const filteredExamItems = vue.computed(() => { ignoredVersion.value; const routedItems = activitiesItems.value.filter(isRoutedToExam); return [...examItems.value, ...routedItems] .filter(item => shouldDisplayItem({ ...item, _sectionType: 'exam' }) && matchesSearchQuery(item)); }); const filteredActivitiesItems = vue.computed(() => { ignoredVersion.value; return activitiesItems.value .filter(item => !isRoutedToHomework(item) && !isRoutedToExam(item)) .filter(item => shouldDisplayItem({ ...item, _sectionType: 'activities' }) && matchesSearchQuery(item)); }); const filteredCourseProgressItems = vue.computed(() => { ignoredVersion.value; return courseProgressItems.value.filter(item => shouldDisplayItem({ ...item, _sectionType: 'progress' }) && matchesSearchQuery(item)); }); const sortedTodoItems = vue.computed(() => sortItems(filteredTodoItems.value, 'todo', 'urgent')); const sortedHomeworkItems = vue.computed(() => sortItems(filteredHomeworkItems.value, 'homework', 'urgent')); const sortedExamItems = vue.computed(() => sortItems(filteredExamItems.value, 'exam', 'urgent')); const sortedActivitiesItems = vue.computed(() => sortItems(filteredActivitiesItems.value, 'activities', 'urgent')); const deadlineReminderItems = vue.ref([]); const deadlineReminderBannerItems = vue.ref([]); const showDeadlineReminderDialog = vue.ref(false); const deadlineReminderDiagnostics = vue.ref([]); const showDeadlineReminderDiagnostics = vue.ref(false); let deadlineReminderState = getDeadlineReminderState(); let deadlineReminderTimer = null; let deadlineReminderEvaluationTimer = null; let scheduledSyncTimer = null; let cacheCleanupTimer = null; let restoredCourseSyncTimer = null; const pendingRestoredCourses = new Map(); const queriedActivityCourseKeys = new Set(); let deadlineReminderEvaluationInProgress = false; let deadlineReminderEvaluationQueued = false; const systemNotifiedReminderIds = new Set(); const reminderDiagnosticSignatures = new Map(); const DEADLINE_REMINDER_DIAGNOSTIC_LIMIT = 30; const DEADLINE_REMINDER_EVALUATION_DEBOUNCE_MS = 50; const REMINDER_SOURCE_LABELS = { todo: '待办', homework: '作业', exam: '考试' }; const getReminderStatusTexts = (item) => [ item?.status, item?.answerStatus, item?.examStatus, item?.completionStatus, item?.taskStatus ].filter(value => value !== null && value !== undefined && value !== '') .map(value => String(value).trim()) .filter(Boolean); const isReminderSourceCompleted = (item) => { const statusTexts = getReminderStatusTexts(item); const status = statusTexts.join(' '); const homeworkHasExplicitStatus = item?.type === '作业' && item?.statusKnown === true && item?.uncommitted === false && statusTexts.length > 0 && !/未完成|未提交|待提交|进行中/.test(status); return item?.finished === true || item?.expired === true || homeworkHasExplicitStatus || /已完成|已提交|待批阅|已结束|已截止|已过期|已批阅/.test(status); }; const isReminderItemIncomplete = (item) => { return item?._reminderExplicitlyCompleted !== true && !isReminderSourceCompleted(item) && !(item?._reminderStatusTexts || []).some(status => /已完成|已提交|待批阅|已结束|已截止|已过期/.test(status)); }; const getReminderSections = (item, sources = []) => { const sections = new Set(['todo']); if (item?.type === '作业') sections.add('homework'); if (item?.type === '考试') sections.add('exam'); if (item?.isActivity) sections.add(getTaskEnginePlanSection(item)); sources.forEach(source => { if (source === 'homework' || source === 'exam') sections.add(source); }); return [...sections]; }; const getReminderItems = () => { const itemsByTaskKey = new Map(); const sourceLists = [ ['todo', todoItems.value], ['homework', homeworkItems.value], ['exam', examItems.value] ]; sourceLists.forEach(([source, items]) => { items.forEach(sourceItem => { if (!sourceItem || typeof sourceItem !== 'object') return; const item = { ...sourceItem }; if (!item.type) item.type = source === 'homework' ? '作业' : (source === 'exam' ? '考试' : '任务'); if (!item.course && item.courseName) item.course = item.courseName; const taskKey = getTaskReminderKey(item); const existing = itemsByTaskKey.get(taskKey); const sourceStatusTexts = getReminderStatusTexts(item); const sourceDeadlineAt = getTaskDeadlineTimestamp(item); const relativeText = `${item.leftTime || item.timeLeft || item.info || ''}`.trim(); const sourceRemainingMinutes = parseTaskRemainingMinutes(relativeText); const merged = existing ? { ...existing } : {}; Object.entries(item).forEach(([key, value]) => { if (value !== null && value !== undefined && value !== '') merged[key] = value; }); const sources = [...new Set([...(existing?._reminderSources || []), source])]; const statuses = [...new Set([...(existing?._reminderStatusTexts || []), ...sourceStatusTexts])]; merged._reminderSources = sources; merged._reminderSections = getReminderSections(merged, sources); merged._reminderStatusTexts = statuses; merged._reminderExplicitlyCompleted = existing?._reminderExplicitlyCompleted === true || isReminderSourceCompleted(item); if (Number.isFinite(sourceDeadlineAt)) { merged._reminderDeadlineAt = sourceDeadlineAt; merged._reminderDeadlineSource = source; merged._reminderRelativeText = ''; } else if (!Number.isFinite(existing?._reminderDeadlineAt) && Number.isFinite(sourceRemainingMinutes)) { merged._reminderRelativeText = relativeText; merged._reminderDeadlineSource = source; } itemsByTaskKey.set(taskKey, merged); }); }); return itemsByTaskKey; }; const getReminderDeadlineDescription = (item, deadlineAt = NaN) => { if (Number.isFinite(deadlineAt)) return new Date(deadlineAt).toLocaleString(); return `${item?._reminderRelativeText || item?.timeRange || item?.endTime || item?.timeLeft || item?.leftTime || item?.info || '未提供截止时间'}`.slice(0, 120); }; const recordReminderSkip = (item, taskKey, reason, deadlineAt = NaN) => { const deadlineText = getReminderDeadlineDescription(item, deadlineAt); const sources = item?._reminderSources || []; const signature = `${reason}|${sources.join(',')}`; if (reminderDiagnosticSignatures.get(taskKey) === signature) return; reminderDiagnosticSignatures.set(taskKey, signature); const entry = { taskKey, title: item?.title || '未命名任务', type: item?.type || '任务', reason, deadlineText, sources: sources.map(source => REMINDER_SOURCE_LABELS[source] || source).join('、') || '待办', checkedAt: new Date().toLocaleTimeString() }; deadlineReminderDiagnostics.value = [ entry, ...deadlineReminderDiagnostics.value.filter(previous => previous.taskKey !== taskKey) ].slice(0, DEADLINE_REMINDER_DIAGNOSTIC_LIMIT); console.info('[临近提醒][跳过原因]', { title: entry.title, type: entry.type, reason: entry.reason, deadline: entry.deadlineText, sources: entry.sources }); }; const clearReminderSkip = (taskKey) => { reminderDiagnosticSignatures.delete(taskKey); deadlineReminderDiagnostics.value = deadlineReminderDiagnostics.value .filter(entry => entry.taskKey !== taskKey); }; const clearReminderDiagnostics = () => { reminderDiagnosticSignatures.clear(); deadlineReminderDiagnostics.value = []; }; const resolveReminderDeadline = (item, entry, now) => { const absoluteDeadline = Number.isFinite(item?._reminderDeadlineAt) ? item._reminderDeadlineAt : getTaskDeadlineTimestamp(item); if (Number.isFinite(absoluteDeadline)) { if (entry.deadlineSource === 'absolute' && Number.isFinite(entry.deadlineAt) && Math.abs(entry.deadlineAt - absoluteDeadline) > 60 * 1000) { entry.stages = {}; entry.acknowledgedStages = {}; entry.bannerDismissedStages = {}; } entry.deadlineAt = absoluteDeadline; entry.deadlineSource = 'absolute'; entry.relativeText = ''; return absoluteDeadline; } const relativeText = `${item?._reminderRelativeText || item?.leftTime || item?.timeLeft || item?.info || ''}`.trim(); const remainingMinutes = parseTaskRemainingMinutes(relativeText); if (!Number.isFinite(remainingMinutes) || remainingMinutes < 0) return NaN; const relativeInputMatches = entry.deadlineSource === 'relative' && entry.relativeText === relativeText && Number.isFinite(entry.deadlineAt); if (relativeInputMatches) return entry.deadlineAt; const nextDeadline = now + remainingMinutes * 60000; if (Number.isFinite(entry.deadlineAt) && entry.relativeText !== relativeText && Math.abs(entry.deadlineAt - nextDeadline) > 2 * 60 * 1000) { entry.stages = {}; entry.acknowledgedStages = {}; entry.bannerDismissedStages = {}; } entry.deadlineAt = nextDeadline; entry.deadlineSource = 'relative'; entry.relativeText = relativeText; return nextDeadline; }; const formatReminderRemaining = (milliseconds) => { const totalMinutes = Math.max(1, Math.ceil(milliseconds / 60000)); const days = Math.floor(totalMinutes / (24 * 60)); const hours = Math.floor((totalMinutes % (24 * 60)) / 60); const minutes = totalMinutes % 60; if (days) return `${days}天${hours ? `${hours}小时` : ''}`; if (hours) return `${hours}小时${minutes ? `${minutes}分钟` : ''}`; return `${minutes}分钟`; }; const acknowledgeDeadlineReminderBatch = () => { deadlineReminderState = getDeadlineReminderState(); deadlineReminderItems.value.forEach(alert => { const entry = deadlineReminderState.tasks[alert.taskKey]; if (!entry) return; entry.acknowledgedStages = entry.acknowledgedStages && typeof entry.acknowledgedStages === 'object' ? entry.acknowledgedStages : {}; Object.keys(entry.stages || {}).forEach(stage => { entry.acknowledgedStages[stage] = true; }); entry.updatedAt = Date.now(); }); saveDeadlineReminderState(deadlineReminderState); deadlineReminderItems.value = []; showDeadlineReminderDialog.value = false; }; const dismissDeadlineReminderBanner = () => { deadlineReminderState = getDeadlineReminderState(); deadlineReminderBannerItems.value.forEach(alert => { const entry = deadlineReminderState.tasks[alert.taskKey]; if (!entry) return; entry.bannerDismissedStages = entry.bannerDismissedStages && typeof entry.bannerDismissedStages === 'object' ? entry.bannerDismissedStages : {}; Object.keys(entry.stages || {}).forEach(stage => { entry.bannerDismissedStages[stage] = true; }); entry.updatedAt = Date.now(); }); saveDeadlineReminderState(deadlineReminderState); deadlineReminderBannerItems.value = []; }; const openDeadlineReminderDialog = () => { const alertsById = new Map(); deadlineReminderItems.value.forEach(alert => alertsById.set(alert.id, alert)); deadlineReminderBannerItems.value.forEach(alert => alertsById.set(alert.id, { ...alert, _openedFromBanner: true })); deadlineReminderItems.value = [...alertsById.values()].sort((a, b) => a.deadlineAt - b.deadlineAt); showDeadlineReminderDialog.value = true; }; const dismissDeadlineReminderTask = (taskKey) => { deadlineReminderState = getDeadlineReminderState(); const entry = deadlineReminderState.tasks[taskKey] || { stages: {} }; entry.muted = true; entry.updatedAt = Date.now(); deadlineReminderState.tasks[taskKey] = entry; saveDeadlineReminderState(deadlineReminderState); deadlineReminderItems.value = deadlineReminderItems.value.filter(item => item.taskKey !== taskKey); deadlineReminderBannerItems.value = deadlineReminderBannerItems.value.filter(item => item.taskKey !== taskKey); if (!deadlineReminderItems.value.length) showDeadlineReminderDialog.value = false; }; const acknowledgeDeadlineReminderTask = (taskKey) => { deadlineReminderState = getDeadlineReminderState(); const entry = deadlineReminderState.tasks[taskKey]; if (entry) { entry.acknowledgedStages = entry.acknowledgedStages && typeof entry.acknowledgedStages === 'object' ? entry.acknowledgedStages : {}; Object.keys(entry.stages || {}).forEach(stage => { entry.acknowledgedStages[stage] = true; }); entry.updatedAt = Date.now(); saveDeadlineReminderState(deadlineReminderState); } deadlineReminderItems.value = deadlineReminderItems.value.filter(item => item.taskKey !== taskKey); if (!deadlineReminderItems.value.length) showDeadlineReminderDialog.value = false; }; const openDeadlineReminderTask = (alert) => { if (!alert?.item) return; const sectionType = alert.source === 'homework' ? 'homework' : (alert.source === 'exam' ? 'exam' : 'todo'); openTaskLink(alert.item, sectionType); acknowledgeDeadlineReminderTask(alert.taskKey); }; const requestDeadlineBrowserNotifications = async () => { const notificationApi = window.Notification; if (!notificationApi) { updateSetting('deadlineBrowserNotificationEnabled', false); notifySettingsSaved('当前浏览器不支持系统通知,页面内提醒仍可使用'); return; } if (notificationApi.permission === 'denied') { updateSetting('deadlineBrowserNotificationEnabled', false); notifySettingsSaved('浏览器已禁止通知,请在站点权限中允许后重试'); return; } try { const permission = notificationApi.permission === 'granted' ? 'granted' : await notificationApi.requestPermission(); const enabled = permission === 'granted'; updateSetting('deadlineBrowserNotificationEnabled', enabled); notifySettingsSaved(enabled ? '系统通知已开启' : '未获得系统通知权限,页面内提醒仍可使用'); } catch (error) { updateSetting('deadlineBrowserNotificationEnabled', false); notifySettingsSaved('无法开启系统通知,页面内提醒仍可使用'); console.warn('[临近提醒] 浏览器通知授权失败:', error); } }; const sendDeadlineBrowserNotification = (items) => { const notificationApi = window.Notification; if (!settings.value.deadlineBrowserNotificationEnabled || !notificationApi || notificationApi.permission !== 'granted' || !items.length) return []; const first = items[0]; const body = `${first.item.course || first.item.courseName || '课程'} · ${first.item.title || '待办任务'}(${formatReminderRemaining(first.deadlineAt - Date.now())}后截止)${items.length > 1 ? `,另有 ${items.length - 1} 项` : ''}`; try { const notification = new notificationApi('临近任务提醒', { body, tag: 'chaoxing-deadline-reminder' }); notification.onclick = () => { window.focus(); openDeadlineReminderTask(first); notification.close(); }; return items.map(item => item.id); } catch (error) { console.warn('[临近提醒] 系统通知发送失败:', error); return []; } }; const runDeadlineReminderEvaluation = () => { const reminderItemsByTaskKey = getReminderItems(); if (!settings.value.deadlineReminderEnabled) { deadlineReminderItems.value = []; deadlineReminderBannerItems.value = []; showDeadlineReminderDialog.value = false; reminderItemsByTaskKey.forEach((item, taskKey) => { recordReminderSkip(item, taskKey, '全局临近提醒已关闭'); }); return; } const now = Date.now(); deadlineReminderState = getDeadlineReminderState(); const taskStates = deadlineReminderState.tasks; const eligibleItems = new Map(); reminderItemsByTaskKey.forEach((item, taskKey) => { if (!isReminderItemIncomplete(item)) { const status = (item._reminderStatusTexts || getReminderStatusTexts(item)).join('、'); recordReminderSkip(item, taskKey, status ? `任务状态已完成或关闭:${status}` : '任务已完成或关闭'); return; } const sections = item._reminderSections || ['todo']; const ignored = sections.some(section => { const sectionItem = { ...item, _sectionType: section }; return isItemIgnored(sectionItem, section) || isDynamicallyIgnored(sectionItem, section, settings.value); }); if (ignored) { recordReminderSkip(item, taskKey, '任务或所属课程已忽略'); return; } eligibleItems.set(taskKey, item); }); const rawItems = reminderItemsByTaskKey; const newAlerts = []; const newBannerAlerts = []; let stateChanged = false; Object.entries(taskStates).forEach(([taskKey, entry]) => { if (Number.isFinite(entry.deadlineAt) && entry.deadlineAt < now - 7 * 24 * 60 * 60 * 1000) { delete taskStates[taskKey]; stateChanged = true; } }); eligibleItems.forEach((item, taskKey) => { const previousEntry = taskStates[taskKey]; const entry = previousEntry || { stages: {} }; const previousEntryJson = JSON.stringify(entry); entry.stages = entry.stages && typeof entry.stages === 'object' ? entry.stages : {}; entry.acknowledgedStages = entry.acknowledgedStages && typeof entry.acknowledgedStages === 'object' ? entry.acknowledgedStages : {}; entry.bannerDismissedStages = entry.bannerDismissedStages && typeof entry.bannerDismissedStages === 'object' ? entry.bannerDismissedStages : {}; if (entry.muted) { recordReminderSkip(item, taskKey, '已关闭此任务提醒'); taskStates[taskKey] = entry; return; } const deadlineAt = resolveReminderDeadline(item, entry, now); if (!Number.isFinite(deadlineAt)) { recordReminderSkip(item, taskKey, '截止时间解析失败'); taskStates[taskKey] = entry; if (!previousEntry || previousEntryJson !== JSON.stringify(entry)) stateChanged = true; return; } if (deadlineAt <= now) { recordReminderSkip(item, taskKey, '截止时间已过'); taskStates[taskKey] = entry; if (!previousEntry || previousEntryJson !== JSON.stringify(entry)) stateChanged = true; return; } taskStates[taskKey] = entry; if (!previousEntry || previousEntryJson !== JSON.stringify(entry)) stateChanged = true; const remainingMs = deadlineAt - now; const reachedThresholds = DEADLINE_REMINDER_THRESHOLDS.filter(threshold => remainingMs <= threshold.milliseconds); const currentThreshold = reachedThresholds[reachedThresholds.length - 1]; if (currentThreshold && !entry.stages[currentThreshold.key]) { entry.stages[currentThreshold.key] = now; entry.updatedAt = now; stateChanged = true; } const pendingThresholds = DEADLINE_REMINDER_THRESHOLDS.filter(threshold => entry.stages[threshold.key] && !entry.acknowledgedStages[threshold.key]); const pendingThreshold = pendingThresholds[pendingThresholds.length - 1]; if (pendingThreshold) { clearReminderSkip(taskKey); newAlerts.push({ id: `${taskKey}:${Math.round(deadlineAt)}:${pendingThreshold.key}`, taskKey, threshold: pendingThreshold, deadlineAt, item }); } else if (currentThreshold && entry.acknowledgedStages[currentThreshold.key]) { recordReminderSkip(item, taskKey, `已确认当前提醒阶段(${currentThreshold.label})`, deadlineAt); } else { recordReminderSkip(item, taskKey, '尚未进入 12 小时提醒范围', deadlineAt); } const pendingBannerThresholds = DEADLINE_REMINDER_THRESHOLDS.filter(threshold => entry.stages[threshold.key] && !entry.bannerDismissedStages[threshold.key]); const pendingBannerThreshold = pendingBannerThresholds[pendingBannerThresholds.length - 1]; if (pendingBannerThreshold) { newBannerAlerts.push({ id: `${taskKey}:${Math.round(deadlineAt)}:${pendingBannerThreshold.key}`, taskKey, threshold: pendingBannerThreshold, deadlineAt, item }); } }); const alertsByTaskKey = new Map(); deadlineReminderItems.value .filter(alert => { const currentItem = rawItems.get(alert.taskKey); const isVisible = eligibleItems.has(alert.taskKey); const currentDeadline = taskStates[alert.taskKey]?.deadlineAt; return isVisible && (!currentItem || isReminderItemIncomplete(currentItem)) && alert.deadlineAt > now && (!taskStates[alert.taskKey]?.acknowledgedStages?.[alert.threshold.key] || alert._openedFromBanner) && (!Number.isFinite(currentDeadline) || Math.abs(currentDeadline - alert.deadlineAt) <= 60 * 1000); }) .forEach(alert => alertsByTaskKey.set(alert.taskKey, alert)); // 同一任务只保留最新待处理阶段,避免旧阶段与新阶段同时显示。 newAlerts.forEach(alert => alertsByTaskKey.set(alert.taskKey, alert)); deadlineReminderItems.value = [...alertsByTaskKey.values()].sort((a, b) => a.deadlineAt - b.deadlineAt); deadlineReminderBannerItems.value = newBannerAlerts.sort((a, b) => a.deadlineAt - b.deadlineAt); if (stateChanged) saveDeadlineReminderState(deadlineReminderState); if (newAlerts.length) { if (!showDeadlineReminderDialog.value) showDeadlineReminderDialog.value = true; const notificationsToSend = newAlerts .filter(alert => !systemNotifiedReminderIds.has(alert.id)) .sort((a, b) => a.deadlineAt - b.deadlineAt); sendDeadlineBrowserNotification(notificationsToSend) .forEach(id => systemNotifiedReminderIds.add(id)); } if (!deadlineReminderItems.value.length) showDeadlineReminderDialog.value = false; }; const evaluateDeadlineReminders = () => { if (deadlineReminderEvaluationInProgress) { deadlineReminderEvaluationQueued = true; return; } deadlineReminderEvaluationInProgress = true; try { runDeadlineReminderEvaluation(); } catch (error) { console.error('[临近提醒] 检查失败:', error); } finally { deadlineReminderEvaluationInProgress = false; if (deadlineReminderEvaluationQueued) { deadlineReminderEvaluationQueued = false; scheduleDeadlineReminderEvaluation(); } } }; const scheduleDeadlineReminderEvaluation = () => { if (deadlineReminderEvaluationTimer !== null) return; deadlineReminderEvaluationTimer = setTimeout(() => { deadlineReminderEvaluationTimer = null; evaluateDeadlineReminders(); }, DEADLINE_REMINDER_EVALUATION_DEBOUNCE_MS); }; const startDeadlineReminderMonitoring = () => { if (deadlineReminderTimer) clearInterval(deadlineReminderTimer); evaluateDeadlineReminders(); deadlineReminderTimer = setInterval(evaluateDeadlineReminders, DEADLINE_REMINDER_CHECK_INTERVAL); }; const handleReminderPageVisibility = () => { if (document.visibilityState === 'visible') scheduleDeadlineReminderEvaluation(); }; // 各板块已忽略数量 const getSectionIgnoredCount = (sectionType) => { ignoredVersion.value; return getIgnoredItemsBySection(sectionType).length; }; // 课程进度板块的已忽略面板状态 const showProgressIgnoredPanel = vue.ref(false); const progressIgnoredForRestore = vue.ref(new Set()); // 悬浮窗活动数据缓存 const courseActivitiesCache = vue.ref({}); // { courseId_clazzId: { activities: [], loading: boolean, fetched: boolean } } const hoveredCourseKey = vue.ref(null); // 当前悬停的课程标识 const getCourseActivitiesKey = (course) => `${course.courseId}_${course.clazzId}`; const fetchCourseActivitiesOnHover = async (course) => { const cacheKey = getCourseActivitiesKey(course); // 如果已经获取过,直接返回缓存数据 if (courseActivitiesCache.value[cacheKey]?.fetched) { return courseActivitiesCache.value[cacheKey].activities; } // 如果正在加载,返回空 if (courseActivitiesCache.value[cacheKey]?.loading) { return []; } // 设置加载状态 courseActivitiesCache.value = { ...courseActivitiesCache.value, [cacheKey]: { activities: [], loading: true, fetched: false } }; try { const activities = await fetchCourseActivities(course); // 过滤出有用的活动类型(作业、测验、考试等) const filteredActivities = activities.filter(act => { const type = act.type; return type && !['签到', '投票', '直播', '笔记', '拍照'].includes(type); }); // 更新缓存 courseActivitiesCache.value = { ...courseActivitiesCache.value, [cacheKey]: { activities: filteredActivities, loading: false, fetched: true } }; return filteredActivities; } catch (error) { console.error('[悬浮窗] 获取课程活动失败:', error); courseActivitiesCache.value = { ...courseActivitiesCache.value, [cacheKey]: { activities: [], loading: false, fetched: true } }; return []; } }; let progressTooltipPortal = null; const clearProgressTooltipPortal = () => { if (!progressTooltipPortal) return; progressTooltipPortal.item.classList.remove('tooltip-portal-active'); progressTooltipPortal.element.remove(); progressTooltipPortal = null; }; const showProgressTooltipPortal = (itemElement) => { clearProgressTooltipPortal(); const source = itemElement.querySelector('.progress-tooltip'); if (!source) return; const portal = source.cloneNode(true); portal.classList.add('progress-tooltip-portal'); document.body.appendChild(portal); const rect = itemElement.getBoundingClientRect(); const isLeftSide = rect.left > window.innerWidth / 2; const width = portal.offsetWidth; const height = portal.offsetHeight; const left = isLeftSide ? Math.max(16, rect.left - width - 12) : Math.min(window.innerWidth - width - 16, rect.right + 12); const top = Math.max(16, Math.min(rect.bottom - height, window.innerHeight - height - 16)); portal.style.left = `${left}px`; portal.style.top = `${top}px`; itemElement.classList.add('tooltip-portal-active'); progressTooltipPortal = { item: itemElement, element: portal }; }; const handleProgressItemHover = async (event, course) => { const cacheKey = getCourseActivitiesKey(course); hoveredCourseKey.value = cacheKey; hoveredProgressCourse.value = course; const rect = event?.currentTarget?.getBoundingClientRect?.(); if (rect) { hoveredProgressRect.value = { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom }; } await fetchCourseActivitiesOnHover(course); }; const handleProgressItemLeave = () => { hoveredCourseKey.value = null; hoveredProgressCourse.value = null; hoveredProgressRect.value = null; }; const toggleProgressRestoreItem = (key) => { const newSet = new Set(progressIgnoredForRestore.value); if (newSet.has(key)) newSet.delete(key); else newSet.add(key); progressIgnoredForRestore.value = newSet; }; const batchProgressRestore = () => { const keys = Array.from(progressIgnoredForRestore.value); unignoreByKeys(keys); progressIgnoredForRestore.value = new Set(); ignoredVersion.value++; if (activitiesFetched.value && keys.some(k => k.startsWith(COURSE_IGNORE_PREFIX))) { scheduleRestoredCourseActivitiesByKeys(keys); } }; // 排序选项 const sortOptions = [ { value: 'urgent', label: '紧急优先(默认)' }, { value: 'time-asc', label: '剩余时间升序' }, { value: 'time-desc', label: '剩余时间降序' }, { value: 'status', label: '按状态分组' }, { value: 'name', label: '按名称排序' } ]; const currentSort = vue.ref('urgent'); // 解析剩余时间为分钟数用于排序 const parseTimeToMinutes = (timeStr) => { return getTaskRemainingMinutes({ leftTime: timeStr }); }; const isTodoItemUrgent = (item) => { const remainingMinutes = getTaskRemainingMinutes(item); if (Number.isFinite(remainingMinutes)) return remainingMinutes >= 0 && remainingMinutes <= 24 * 60; return item.isActivity && item.status === '进行中'; }; const isIncompleteForUrgentSort = (item, type) => { switch (type) { case 'homework': return item.isActivity ? item.uncommitted !== false && isReminderItemIncomplete(item) : item.uncommitted === true && !isExplicitlyCompletedHomework(item); case 'exam': return !isExplicitlyClosedExam(item); case 'activities': return isReminderItemIncomplete(item); default: return true; } }; // 智能排序函数:未完成+剩余时间短的在最上面 const sortItems = (items, type, sortType = 'urgent') => { const arr = [...items]; // 课程进度特殊排序 if (type === 'progress') { switch (sortType) { case 'urgent': case 'status': return arr.sort(compareCourseProgress); case 'time-asc': return arr.sort(compareCourseProgress); case 'time-desc': return arr.sort((a, b) => compareCourseProgress(a, b, -1)); case 'name': return arr.sort(compareCourseProgressByName); default: return arr; } } switch (sortType) { case 'urgent': return arr.sort((a, b) => { if (type !== 'todo') { const aIncomplete = isIncompleteForUrgentSort(a, type); const bIncomplete = isIncompleteForUrgentSort(b, type); if (aIncomplete !== bIncomplete) return aIncomplete ? -1 : 1; } return compareTodoItemsByDeadline(a, b); }); case 'time-asc': return arr.sort(compareTodoItemsByDeadline); case 'time-desc': return arr.sort((a, b) => compareTodoItemsByDeadline(a, b, -1)); case 'status': return arr.sort((a, b) => { if (a.uncommitted && !b.uncommitted) return -1; if (!a.uncommitted && b.uncommitted) return 1; if (a.finished && !b.finished) return 1; if (!a.finished && b.finished) return -1; return 0; }); case 'name': return arr.sort((a, b) => (a.title || '').localeCompare(b.title || '')); default: return arr; } }; const getDashboardTodoPreviewItems = () => sortItems(filteredTodoItems.value, 'todo', 'urgent').slice(0, 2); const getActivityMergeKey = (item) => { if (!item) return ''; const courseKey = String(item.courseId || ''); const classKey = String(item.clazzId || item.classId || ''); const normalizedId = item.activeId ?? item.id ?? item.planId ?? item.taskId ?? item.workId ?? item.examId; if (normalizedId !== undefined && normalizedId !== null && String(normalizedId).trim() !== '') { return `id:${courseKey}|${classKey}|${item.source || ''}|${String(normalizedId).trim()}`; } if (item.url) { return `url:${courseKey}|${classKey}|${item.url}`; } return `fallback:${courseKey}|${classKey}|${item.type || ''}|${item.title || ''}|${item.startTime || ''}|${item.endTime || ''}`; }; const mergePreservingPreviousActivities = (freshList, prevList) => { const merged = []; const seenKeys = new Set(); for (const item of (Array.isArray(freshList) ? freshList : [])) { const key = getActivityMergeKey(item); if (key && seenKeys.has(key)) continue; if (key) seenKeys.add(key); merged.push(item); } for (const item of (Array.isArray(prevList) ? prevList : [])) { const key = getActivityMergeKey(item); if (key && seenKeys.has(key)) continue; if (key) seenKeys.add(key); merged.push(item); } return merged; }; const syncHomeworkToTodo = (tasks) => { const list = Array.isArray(tasks) ? tasks : []; const pendingHomework = list.filter(t => t.uncommitted).map(t => ({ ...t, info: t.leftTime, isUrgent: isTodoItemUrgent({ ...t, info: t.leftTime }) })); todoItems.value = [...pendingHomework, ...todoItems.value.filter(item => item.isActivity || item.type !== '作业')] .sort(compareTodoItemsByDeadline); scheduleDeadlineReminderEvaluation(); }; // 获取待办任务数据 const loadTodoData = async (refreshedHomeworkTasks = null) => { loading.value.todo = true; const baseHomework = Array.isArray(refreshedHomeworkTasks) ? refreshedHomeworkTasks : (homeworkItems.value.length > 0 ? homeworkItems.value : extractTasks()); const pendingTasks = baseHomework.filter(t => t.uncommitted).map(t => ({ ...t, info: t.leftTime })); let pendingExams = []; const seenExamIds = new Set(); // 先发布已读到的作业,避免等待考试接口期间漏掉临近截止提醒。 todoItems.value = [...pendingTasks, ...todoItems.value.filter(item => item.isActivity || item.type === '考试')] .sort(compareTodoItemsByDeadline); scheduleDeadlineReminderEvaluation(); try { const res1 = await fetch('https://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode'); const text1 = await res1.text(); const parser1 = new DOMParser(); const doc1 = parser1.parseFromString(text1, 'text/html'); const exams1 = extractExams(doc1); exams1.filter(e => !e.finished && !e.expired).forEach(e => { const key = e.examId || e.title; if (!seenExamIds.has(key)) { seenExamIds.add(key); pendingExams.push({ ...e, course: "考试课程", info: e.timeLeft }); } }); } catch (e) { console.error("Fetch exams failed", e); } try { const res2 = await fetch(API_EXAM_LIST); const text2 = await res2.text(); const parser2 = new DOMParser(); const doc2 = parser2.parseFromString(text2, 'text/html'); const exams2 = extractExamsFromTable(doc2); exams2.filter(e => !e.finished && !e.expired).forEach(e => { const key = e.examId || e.title; if (!seenExamIds.has(key)) { seenExamIds.add(key); pendingExams.push({ ...e, course: "考试课程", info: e.timeLeft }); } }); } catch (e) { console.error("Fetch exams from table failed", e); } const latestHomeworkSource = Array.isArray(refreshedHomeworkTasks) ? refreshedHomeworkTasks : (homeworkItems.value.length > 0 ? homeworkItems.value : baseHomework); const latestPendingTasks = latestHomeworkSource.filter(t => t.uncommitted).map(t => ({ ...t, info: t.leftTime })); // 课程任务由 loadActivitiesData 统一读取;保留已先完成加载的活动,避免并发请求覆盖首页待办。 todoItems.value = [...latestPendingTasks, ...pendingExams, ...todoItems.value.filter(item => item.isActivity)] .sort(compareTodoItemsByDeadline); // 计算紧急任务 todoItems.value = todoItems.value.map(item => ({ ...item, isUrgent: isTodoItemUrgent(item) })); loading.value.todo = false; scheduleDeadlineReminderEvaluation(); }; // 获取作业数据 const loadHomeworkData = async () => { loading.value.homework = true; let freshTasks = homeworkItems.value; try { const res = await fetch('https://mooc1-api.chaoxing.com/work/stu-work'); const text = await res.text(); const parser = new DOMParser(); const doc = parser.parseFromString(text, 'text/html'); freshTasks = extractTasks(doc); homeworkItems.value = freshTasks; syncHomeworkToTodo(freshTasks); } catch (e) { console.error('[仪表盘] 获取作业失败:', e); } loading.value.homework = false; return freshTasks; }; const syncExamsToTodo = (exams) => { const list = Array.isArray(exams) ? exams : []; const seenKeys = new Set(); const pendingExams = []; for (const e of list) { if (e.finished || e.expired) continue; const key = e.examId || e.title; if (key && seenKeys.has(key)) continue; if (key) seenKeys.add(key); const info = e.timeLeft || ''; pendingExams.push({ ...e, course: e.course || '考试课程', info, isUrgent: isTodoItemUrgent({ ...e, info }) }); } todoItems.value = [...todoItems.value.filter(item => item.isActivity || item.type !== '考试'), ...pendingExams] .sort(compareTodoItemsByDeadline); scheduleDeadlineReminderEvaluation(); }; // 获取考试数据 const loadExamData = async () => { loading.value.exam = true; let freshExams = []; const seenExamKeys = new Set(); let anySucceeded = false; try { const res = await fetch('https://mooc1-api.chaoxing.com/exam-ans/exam/phone/examcode'); const text = await res.text(); const parser = new DOMParser(); const doc = parser.parseFromString(text, 'text/html'); for (const e of extractExams(doc)) { const key = e.examId || e.title; if (key && seenExamKeys.has(key)) continue; if (key) seenExamKeys.add(key); freshExams.push(e); } anySucceeded = true; } catch (e) { console.error('[仪表盘] 获取考试失败:', e); } try { const res2 = await fetch(API_EXAM_LIST); const text2 = await res2.text(); const parser2 = new DOMParser(); const doc2 = parser2.parseFromString(text2, 'text/html'); for (const e of extractExamsFromTable(doc2)) { const key = e.examId || e.title; if (key && seenExamKeys.has(key)) continue; if (key) seenExamKeys.add(key); freshExams.push(e); } anySucceeded = true; } catch (e) { console.error('[仪表盘] 获取考试列表补充失败:', e); } if (anySucceeded) { examItems.value = freshExams; syncExamsToTodo(freshExams); } loading.value.exam = false; }; // 获取课程任务数据(两阶段节流:先秒出课堂活动,再后台缓速补齐任务引擎,兼顾 429 风控) const loadActivitiesData = async () => { if (loading.value.activities || activitiesFetched.value) return; const previousActivities = Array.isArray(activitiesItems.value) ? [...activitiesItems.value] : []; const hadExistingActivities = activitiesLoaded.value && previousActivities.length > 0; loading.value.activities = true; activitiesLoadFailed.value = false; activitiesLoadIssues.value = []; clearCourseActivityIssues(); try { const allCourses = await fetchCourseList(); const targetCourses = allCourses.filter(course => !isCourseIgnored(course)); const classroomActivities = []; let consecutiveRateLimits = 0; let currentDelayMs = 180; let rateLimitAborted = false; // 阶段一:快速拉取课堂活动(讨论 / 分组 / 问卷 / 随堂练习) for (let i = 0; i < targetCourses.length; i += 2) { const batch = targetCourses.slice(i, i + 2).filter(course => !isCourseIgnored(course)); if (batch.length === 0) continue; if (i > 0) await delay(currentDelayMs + Math.floor(Math.random() * 60)); const results = await Promise.all(batch.map(course => fetchCourseClassroomActivities(course))); let batchHitLimit = false; for (const r of results) { classroomActivities.push(...(r.items || [])); if (r.rateLimited) batchHitLimit = true; } batch.forEach(c => queriedActivityCourseKeys.add(getCourseActivityKey(c))); if (batchHitLimit) { consecutiveRateLimits++; currentDelayMs = 1200; if (consecutiveRateLimits >= 2) { rateLimitAborted = true; break; } } else { consecutiveRateLimits = 0; } } // 阶段一完成,仅在冷启动无旧数据时提前渲染课堂活动,避免刷新中途丢失任务引擎旧项 if (!hadExistingActivities && (classroomActivities.length > 0 || !activitiesLoaded.value)) { activitiesItems.value = [...classroomActivities]; syncActivitiesToTodo(activitiesItems.value); } activitiesLoaded.value = true; // 阶段二:若未触及限流熔断,继续以低速补齐任务引擎明细 const taskEngineActivities = []; if (!rateLimitAborted) { currentDelayMs = 280; consecutiveRateLimits = 0; for (let i = 0; i < targetCourses.length; i += 2) { const batch = targetCourses.slice(i, i + 2).filter(course => !isCourseIgnored(course)); if (batch.length === 0) continue; if (i > 0) await delay(currentDelayMs + Math.floor(Math.random() * 80)); const results = await Promise.all(batch.map(course => fetchCourseTaskEngineActivities(course))); let batchHitLimit = false; for (const r of results) { taskEngineActivities.push(...(r.items || [])); if (r.rateLimited) batchHitLimit = true; } if (batchHitLimit) { consecutiveRateLimits++; currentDelayMs = 1200; if (consecutiveRateLimits >= 2) { rateLimitAborted = true; break; } } else { consecutiveRateLimits = 0; } } } const mergedActivities = [...classroomActivities, ...taskEngineActivities]; const rawIssues = getCourseActivityIssues(targetCourses, allCourses); if (rateLimitAborted) { rawIssues.unshift({ courseName: '平台风控保护', sources: ['检测到 429/验证码限流,已自动降速并保留已读取内容'] }); } activitiesLoadIssues.value = rawIssues; const hasReadIssues = rawIssues.length > 0; if (!hasReadIssues) { activitiesItems.value = mergedActivities; syncActivitiesToTodo(mergedActivities); } else if (hadExistingActivities) { const preserved = mergePreservingPreviousActivities(mergedActivities, previousActivities); activitiesItems.value = preserved; syncActivitiesToTodo(preserved); } else if (mergedActivities.length > 0) { activitiesItems.value = mergedActivities; syncActivitiesToTodo(mergedActivities); } activitiesFetched.value = true; if (!hasReadIssues) { activitiesFromCache.value = false; if (settings.value.shortTermCacheEnabled) saveDashboardCache('activities-v2', mergedActivities); } } catch (error) { console.error('[仪表盘] 加载课程任务失败:', error); activitiesLoadFailed.value = true; } loading.value.activities = false; }; const refreshActivitiesForSpecificCourses = async (coursesList, { taskEngineOnly = false } = {}) => { const uniqueCourses = []; const targetKeys = new Set(); for (const c of (Array.isArray(coursesList) ? coursesList : [])) { if (!c?.courseId || !c?.clazzId || isCourseIgnored(c)) continue; const k = getCourseActivityKey(c); if (targetKeys.has(k)) continue; targetKeys.add(k); uniqueCourses.push(c); } if (uniqueCourses.length === 0) return; const fetchedItems = []; const succeededClassroomKeys = new Set(); const succeededTaskEngineKeys = new Set(); let anyTargetedIssue = false; for (let i = 0; i < uniqueCourses.length; i++) { const course = uniqueCourses[i]; if (isCourseIgnored(course)) continue; const k = getCourseActivityKey(course); courseActivityIssues.delete(k); if (i > 0) await delay(180 + Math.floor(Math.random() * 60)); if (!taskEngineOnly) { const clsRes = await fetchCourseClassroomActivities(course); const clsFailed = clsRes.rateLimited || courseActivityIssues.get(k)?.has('课堂活动'); if (!clsFailed) { succeededClassroomKeys.add(k); fetchedItems.push(...(clsRes.items || [])); queriedActivityCourseKeys.add(k); } else { anyTargetedIssue = true; } } const teRes = await fetchCourseTaskEngineActivities(course); const teFailed = teRes.rateLimited || courseActivityIssues.get(k)?.has('任务引擎'); if (!teFailed) { succeededTaskEngineKeys.add(k); fetchedItems.push(...(teRes.items || [])); } else { anyTargetedIssue = true; } } const keptExisting = (activitiesItems.value || []).filter(item => { const itemCourseKey = getCourseActivityKey(item); if (!targetKeys.has(itemCourseKey)) return true; if (item.source === 'task_engine') { return !succeededTaskEngineKeys.has(itemCourseKey); } if (taskEngineOnly) return true; return !succeededClassroomKeys.has(itemCourseKey); }); const nextActivities = mergePreservingPreviousActivities(keptExisting, fetchedItems); activitiesItems.value = nextActivities; activitiesLoaded.value = true; syncActivitiesToTodo(nextActivities); const targetCourseNames = new Set(uniqueCourses.map(c => c.courseName).filter(Boolean)); const untouchedIssues = (activitiesLoadIssues.value || []).filter(issue => !targetCourseNames.has(issue.courseName)); const refreshedIssues = getCourseActivityIssues(uniqueCourses); activitiesLoadIssues.value = [...untouchedIssues, ...refreshedIssues]; if (settings.value.shortTermCacheEnabled && !anyTargetedIssue && activitiesLoadIssues.value.length === 0) { saveDashboardCache('activities-v2', nextActivities); } }; const scheduleRestoredCourseActivities = (courses) => { for (const c of (courses || [])) { if (!c?.courseId) continue; const k = getCourseActivityKey(c); if (!queriedActivityCourseKeys.has(k) && !isCourseIgnored(c)) { pendingRestoredCourses.set(k, c); } } if (pendingRestoredCourses.size === 0) return; if (restoredCourseSyncTimer) clearTimeout(restoredCourseSyncTimer); restoredCourseSyncTimer = setTimeout(() => { restoredCourseSyncTimer = null; const batch = Array.from(pendingRestoredCourses.values()); pendingRestoredCourses.clear(); if (batch.length > 0) refreshActivitiesForSpecificCourses(batch); }, 250); }; const scheduleRestoredCourseActivitiesByKeys = async (keys) => { const courseKeys = (keys || []).filter(k => String(k).startsWith(COURSE_IGNORE_PREFIX)); if (courseKeys.length === 0) return; const knownCourses = courseProgressItems.value.length > 0 ? courseProgressItems.value : (settingsCourses.value.length > 0 ? settingsCourses.value : await fetchCourseList()); const keySet = new Set(courseKeys); const matched = knownCourses.filter(c => keySet.has(getCourseIgnoreKey(c))); if (matched.length > 0) { scheduleRestoredCourseActivities(matched); } else { retryActivitiesData(); } }; const retryActivitiesData = () => { if (loading.value.activities) return; activitiesFetched.value = false; activitiesLoadFailed.value = false; activitiesLoadIssues.value = []; clearCourseActivityIssues(); loadActivitiesData(); }; // 链接生成函数 const buildActivityDirectLink = (item) => { if (!item) return ''; if (item.taskLink) return normalizeChaoxingUrl(item.taskLink, 'https://task.chaoxing.com'); if (item.url && /^https?:\/\/|^\/\//i.test(String(item.url))) { return normalizeChaoxingUrl(item.url, 'https://mobilelearn.chaoxing.com'); } const courseId = String(item.courseId || '').trim(); const classId = String(item.clazzId || item.classId || '').trim(); const activeId = String(item.activeId || '').trim(); if (!courseId || !classId) return ''; if (activeId && !activeId.startsWith('task-engine')) { const isQuizType = item.activeType === 42 || item.activeType === 23 || item.type === '随堂练习'; if (isQuizType) { if (item.finished || item.status === '已结束') { return `https://mobilelearn.chaoxing.com/page/quiz/stu/quizStudentQuestion?activeId=${encodeURIComponent(activeId)}&classId=${encodeURIComponent(classId)}&courseId=${encodeURIComponent(courseId)}&returnType=0&viewType=1&timetable=0`; } return `https://mobilelearn.chaoxing.com/page/quiz/stu/answerQuestion2?courseId=${encodeURIComponent(courseId)}&classId=${encodeURIComponent(classId)}&activeId=${encodeURIComponent(activeId)}&timetable=0`; } return `https://mobilelearn.chaoxing.com/widget/pcpick/stu/index?courseId=${encodeURIComponent(courseId)}&jclassId=${encodeURIComponent(classId)}#active_${encodeURIComponent(activeId)}`; } return ''; }; const buildExamDirectLink = (item) => { const courseId = String(item?.courseId || '').trim(); const classId = String(item?.classId || item?.clazzId || '').trim(); const examId = String(item?.examId || '').trim(); if (courseId && classId && examId) { const url = new URL(API_OPEN_EXAM); url.searchParams.append('courseId', courseId); url.searchParams.append('classId', classId); url.searchParams.append('examId', examId); return url.href; } if (item?.raw) return normalizeChaoxingUrl(item.raw, 'https://mooc1-api.chaoxing.com'); if (courseId && classId) { const url = new URL(API_VISIT_COURSE); url.searchParams.append('courseid', courseId); url.searchParams.append('clazzid', classId); return url.href; } return ''; }; const getTodoLink = (item) => { if (!item) return '#'; if (item.isActivity) { return getActivityLink(item); } if (item.type === '作业') { if (item.courseId && (item.clazzId || item.classId)) { const url = new URL(API_VISIT_COURSE); url.searchParams.append('courseid', item.courseId); url.searchParams.append('clazzid', item.clazzId || item.classId); url.searchParams.append('pageHeader', '8'); return url.href; } return item.raw ? normalizeChaoxingUrl(item.raw, 'https://mooc1-api.chaoxing.com') : '#'; } return buildExamDirectLink(item) || '#'; }; const getHomeworkLink = (item) => { if (!item) return '#'; if (item.isActivity) return getActivityLink(item); if (item.courseId && (item.clazzId || item.classId)) { const url = new URL(API_VISIT_COURSE); url.searchParams.append('courseid', item.courseId); url.searchParams.append('clazzid', item.clazzId || item.classId); url.searchParams.append('pageHeader', '8'); return url.href; } return item.raw ? normalizeChaoxingUrl(item.raw, 'https://mooc1-api.chaoxing.com') : '#'; }; const getExamLink = (item) => { if (!item) return '#'; if (item.isActivity) return getActivityLink(item); return buildExamDirectLink(item) || '#'; }; const getActivityLink = (item) => { if (!item) return '#'; const direct = buildActivityDirectLink(item); if (direct) return direct; if (item.courseId && (item.clazzId || item.classId)) { const url = new URL(API_VISIT_COURSE); url.searchParams.append('courseid', item.courseId); url.searchParams.append('clazzid', item.clazzId || item.classId); return url.href; } return '#'; }; const resolvingTaskKey = vue.ref(''); const getResolvingKey = (item, section = 'task') => `${section}_${getItemKey(item, section)}`; const openTaskLink = async (item, sectionType) => { if (!item) return; const fallbackUrl = sectionType === 'todo' ? getTodoLink(item) : sectionType === 'homework' ? getHomeworkLink(item) : sectionType === 'exam' ? getExamLink(item) : getActivityLink(item); const isHomeworkDirect = !item?.isActivity && (sectionType === 'homework' || (sectionType === 'todo' && item?.type === '作业')) && settings.value.directHomeworkJumpEnabled; if (!isHomeworkDirect) { if (fallbackUrl && fallbackUrl !== '#') { const opened = window.open(fallbackUrl, '_blank'); if (!opened) notifySettingsSaved('弹出窗口被浏览器拦截,请允许学习通站点的弹出式窗口'); } return; } const taskKey = getResolvingKey(item, sectionType); if (resolvingTaskKey.value) return; resolvingTaskKey.value = taskKey; const popupWin = window.open('about:blank', '_blank'); try { const directUrl = await Promise.race([ resolveDirectHomeworkUrl(item, fallbackUrl), new Promise((resolve) => setTimeout(() => resolve(fallbackUrl), 9000)) ]); const finalUrl = directUrl && directUrl !== '#' ? directUrl : fallbackUrl; if (popupWin && !popupWin.closed) { popupWin.location.href = finalUrl; } else if (finalUrl && finalUrl !== '#') { window.open(finalUrl, '_blank'); } } catch { if (popupWin && !popupWin.closed) { popupWin.location.href = fallbackUrl; } else if (fallbackUrl && fallbackUrl !== '#') { window.open(fallbackUrl, '_blank'); } } finally { resolvingTaskKey.value = ''; } }; const getHomeworkStatus = (item) => item.isActivity ? (item.status || (item.finished ? '已完成' : '进行中')) : (item.uncommitted ? '待提交' : '已提交'); const getHomeworkBadgeClass = (item) => item.isActivity ? (item.finished ? 'status-done' : (item.expired ? 'status-gray' : 'status-warning')) : (item.uncommitted ? 'status-warning' : 'status-done'); // 切换视图函数(不跳转外部页面,在内部切换视图) const openFullScreen = (type) => { currentView.value = type; if (type === 'activities') loadActivitiesData(); // 首页已经加载过课程进度时,详情页直接复用当前数据,避免再次查询。 if (type === 'progress' && !progressLoaded.value && !loadingProgress.value) { loadAllCourseProgress(); } }; // 返回仪表盘 const backToDashboard = () => { // 先独立绘制骨架页,再进入列表页,避免两页同时重排造成可感知卡顿。 currentView.value = 'dashboard-loading'; dashboardSkeletonOverlay.value = false; dashboardSkeletonFading.value = false; if (dashboardSkeletonTimer) clearTimeout(dashboardSkeletonTimer); requestAnimationFrame(() => { dashboardSkeletonTimer = setTimeout(() => { currentView.value = 'dashboard'; dashboardSkeletonOverlay.value = true; requestAnimationFrame(() => { dashboardSkeletonFading.value = true; dashboardSkeletonTimer = setTimeout(() => { dashboardSkeletonOverlay.value = false; dashboardSkeletonFading.value = false; dashboardSkeletonTimer = null; }, 340); }); }, 160); }); }; const renderDashboardSkeletonContent = () => vue.createVNode('div', { class: 'main-content' }, [ vue.createVNode('div', { class: 'dashboard-skeleton-refresh' }, [ vue.createVNode('span', { class: 'dashboard-skeleton-spinner' }), vue.createVNode('span', null, '正在整理学习清单') ]), vue.createVNode('div', { class: 'dashboard-header dashboard-skeleton-header' }, [ vue.createVNode('div', { class: 'dashboard-skeleton-block dashboard-skeleton-title' }), vue.createVNode('div', { class: 'dashboard-skeleton-block dashboard-skeleton-text' }) ]), vue.createVNode('div', { class: 'dashboard-skeleton-alert' }, [ vue.createVNode('i', { class: 'dashboard-skeleton-dot' }), vue.createVNode('div', { class: 'dashboard-skeleton-block dashboard-skeleton-alert-line' }) ]), vue.createVNode('div', { class: 'dashboard-grid' }, [ vue.createVNode('div', { class: 'card dashboard-skeleton-card' }), vue.createVNode('div', { class: 'card dashboard-skeleton-card' }), vue.createVNode('div', { class: 'card dashboard-skeleton-card' }) ]) ]); const renderDashboardSkeleton = () => vue.createVNode('div', { class: 'dashboard-wrapper dashboard-skeleton-page' }, [ renderDashboardSkeletonContent() ]); const renderDashboardSkeletonOverlay = () => vue.createVNode('div', { class: dashboardSkeletonFading.value ? 'dashboard-skeleton-overlay is-leaving' : 'dashboard-skeleton-overlay' }, [ renderDashboardSkeletonContent() ]); const renderLoadingSkeleton = (message) => vue.createVNode('div', { class: 'content-skeleton', role: 'status' }, [ vue.createVNode('div', { class: 'content-skeleton-lines' }, [ vue.createVNode('i', { class: 'content-skeleton-line wide' }), vue.createVNode('i', { class: 'content-skeleton-line medium' }), vue.createVNode('i', { class: 'content-skeleton-line short' }) ]), vue.createVNode('div', { class: 'content-skeleton-message' }, [ vue.createVNode('span', { class: 'content-skeleton-spinner' }), vue.createVNode('span', null, message) ]) ]); const renderSettingsToggle = (checked, ariaLabel, onChange) => vue.createVNode('label', { class: 'settings-toggle-row cx-switch-only' }, [ vue.createVNode('input', { class: 'settings-toggle-input', type: 'checkbox', checked, 'aria-label': ariaLabel, onChange }), vue.createVNode('span', { class: 'settings-toggle-track', 'aria-hidden': 'true' }, [ vue.createVNode('span', { class: 'settings-toggle-knob' }) ]) ]); const renderSettingsRow = (title, desc, controlVNode) => vue.createVNode('div', { class: 'cx-setting-row' }, [ vue.createVNode('div', { class: 'cx-setting-meta' }, [ vue.createVNode('div', { class: 'cx-setting-title' }, title), desc ? vue.createVNode('div', { class: 'cx-setting-desc' }, desc) : null ]), vue.createVNode('div', { class: 'cx-setting-control' }, [controlVNode]) ]); const renderSettingsView = (reminderBannerVNode = null) => { ignoredVersion.value; const navItems = [ { key: 'general', icon: 'settings', label: '常规与外观' }, { key: 'display', icon: 'bell', label: '展示与提醒' }, { key: 'filter', icon: 'shield', label: '筛选与忽略' }, { key: 'sync', icon: 'refreshCw', label: '同步与备份' }, { key: 'help', icon: 'bookOpen', label: '帮助与指南' } ]; const tab = activeSettingsTab.value || 'general'; return vue.createVNode('div', { class: 'cx-settings-page' }, [ vue.createVNode('div', { class: 'cx-topbar cx-settings-topbar' }, [ vue.createVNode('div', { class: 'cx-topbar-left' }, [ vue.createVNode('button', { class: 'back-btn', onClick: backToDashboard }, '← 返回工作台'), vue.createVNode('div', { class: 'cx-topbar-title' }, [ '工作台设置', vue.createVNode('span', { class: 'cx-version-pill' }, 'v2.6.0') ]) ]), vue.createVNode('div', { class: 'cx-topbar-actions' }, [ vue.createVNode('button', { class: 'external-link-btn', onClick: openConfigExportDialog }, [cxIcon('upload', 14), '导出配置']), vue.createVNode('button', { class: 'external-link-btn', onClick: openConfigImportDialog }, [cxIcon('download', 14), '导入配置']) ]) ]), reminderBannerVNode, vue.createVNode('div', { class: 'cx-settings-shell' }, [ vue.createVNode('aside', { class: 'cx-settings-nav' }, navItems.map(item => vue.createVNode('button', { type: 'button', class: `cx-settings-nav-item ${tab === item.key ? 'active' : ''}`, onClick: () => { activeSettingsTab.value = item.key; } }, [cxIcon(item.icon, 15), vue.createVNode('span', null, item.label)]) )), vue.createVNode('div', { class: 'cx-settings-content' }, [ tab === 'general' ? [ vue.createVNode('div', { class: 'cx-settings-section-head' }, [ vue.createVNode('h3', null, '常规与外观'), vue.createVNode('p', null, '调整主题配色、作业直达与考试整卷预览体验。') ]), vue.createVNode('section', { class: 'cx-settings-card' }, [ renderSettingsRow( '主题外观', '支持浅色、深色以及跟随浏览器/系统偏好自动切换。', vue.createVNode('div', { class: 'cx-segmented-control' }, [ { key: 'system', icon: 'contrast', label: '跟随系统' }, { key: 'light', icon: 'sun', label: '浅色' }, { key: 'dark', icon: 'moon', label: '深色' } ].map(opt => vue.createVNode('button', { type: 'button', class: `cx-segment-btn ${(settings.value.themeMode || 'system') === opt.key ? 'active' : ''}`, onClick: (e) => updateSetting('themeMode', opt.key, e) }, [cxIcon(opt.icon, 14), opt.label]))) ), renderSettingsRow( '作业直达答题页', settings.value.directHomeworkJumpEnabled ? '点击作业直接解析并打开做题/查看页(失败自动回退课程页)。' : '已关闭,点击作业打开课程作业中转页。', renderSettingsToggle(settings.value.directHomeworkJumpEnabled, '作业直达答题页', e => updateSetting('directHomeworkJumpEnabled', e.target.checked)) ), renderSettingsRow( '考试自动切换「整卷预览」', settings.value.examAutoFullPreviewEnabled ? '进入考试答题页后自动尝试切换整卷预览。' : '已关闭,保持考试页面默认分页视图。', renderSettingsToggle(settings.value.examAutoFullPreviewEnabled, '考试自动整卷预览', e => updateSetting('examAutoFullPreviewEnabled', e.target.checked)) ) ]) ] : null, tab === 'display' ? [ vue.createVNode('div', { class: 'cx-settings-section-head' }, [ vue.createVNode('h3', null, '展示与提醒'), vue.createVNode('p', null, '管理待办分类展示与临近截止提醒方式。') ]), vue.createVNode('section', { class: 'cx-settings-card' }, [ renderSettingsRow( '作业/考试/课程任务默认筛选', (settings.value.defaultTaskFilter || 'pending') === 'pending' ? '切换 Tab 时默认优先展示未完成任务(推荐,切换更流畅)。' : '切换 Tab 时默认展示全部任务(含已完成)。', vue.createVNode('div', { class: 'cx-segmented-control' }, [ { key: 'pending', label: '未完成' }, { key: 'all', label: '全部' } ].map(opt => vue.createVNode('button', { type: 'button', class: `cx-segment-btn ${(settings.value.defaultTaskFilter || 'pending') === opt.key ? 'active' : ''}`, onClick: () => updateSetting('defaultTaskFilter', opt.key) }, opt.label))) ), renderSettingsRow( '首页 Tab 数量徽标', (settings.value.tabBadgeCountMode || 'pending') === 'pending' ? '默认仅统计待办/未完成任务数,与顶部 KPI 保持一致。' : '显示各分类下的全部任务总数(含已完成与已结束)。', vue.createVNode('div', { class: 'cx-segmented-control' }, [ { key: 'pending', label: '仅未完成' }, { key: 'all', label: '全部任务' } ].map(opt => vue.createVNode('button', { type: 'button', class: `cx-segment-btn ${(settings.value.tabBadgeCountMode || 'pending') === opt.key ? 'active' : ''}`, onClick: () => updateSetting('tabBadgeCountMode', opt.key) }, opt.label))) ), renderSettingsRow( '展示分类', `当前策略:${getOtherTasksSummary()}(隐藏类型仍会触发临近提醒)`, vue.createVNode('button', { class: 'external-link-btn', onClick: () => { showOtherTasksDialog.value = true; } }, '配置其他任务') ), renderSettingsRow( '页面内临近提醒', settings.value.deadlineReminderEnabled ? '已开启:截止前 12 小时、6 小时、3 小时和 30 分钟各提醒一次。' : '已关闭:右下角提醒浮条与弹窗都不会显示。', renderSettingsToggle(settings.value.deadlineReminderEnabled, '开启临近任务提醒', e => updateSetting('deadlineReminderEnabled', e.target.checked)) ), renderSettingsRow( '浏览器系统通知', window.Notification?.permission === 'granted' ? '浏览器已授权;通知可能显示在系统锁屏或通知中心。' : '需先授权;未授权时页面内提醒仍可用。', vue.createVNode('div', { style: 'display:flex;align-items:center;gap:10px;' }, [ vue.createVNode('button', { class: 'external-link-btn', disabled: !window.Notification, onClick: requestDeadlineBrowserNotifications }, window.Notification?.permission === 'denied' ? '查看权限说明' : (window.Notification?.permission === 'granted' ? '检查授权' : '授权通知')), renderSettingsToggle(settings.value.deadlineBrowserNotificationEnabled, '使用浏览器系统通知', e => e.target.checked ? requestDeadlineBrowserNotifications() : updateSetting('deadlineBrowserNotificationEnabled', false)) ]) ) ]), vue.createVNode('section', { class: 'cx-settings-card', style: 'margin-top:12px;' }, [ renderSettingsRow( '提醒跳过原因诊断', '“去完成”关闭当前提醒,“我知道了”关闭当前批次,“不再提醒”永久屏蔽该任务。', vue.createVNode('button', { class: 'external-link-btn', onClick: () => { showDeadlineReminderDiagnostics.value = !showDeadlineReminderDiagnostics.value; } }, `${showDeadlineReminderDiagnostics.value ? '隐藏' : '查看'}跳过记录(${deadlineReminderDiagnostics.value.length})`) ), showDeadlineReminderDiagnostics.value ? vue.createVNode('div', { class: 'reminder-diagnostic-list', style: 'padding:0 16px 14px;' }, deadlineReminderDiagnostics.value.length ? [ ...deadlineReminderDiagnostics.value.map(diagnostic => vue.createVNode('article', { class: 'reminder-diagnostic-item' }, [ vue.createVNode('div', { class: 'reminder-diagnostic-heading' }, [ vue.createVNode('strong', null, `${diagnostic.title} · ${diagnostic.type}`), vue.createVNode('span', null, diagnostic.checkedAt) ]), vue.createVNode('div', { class: 'reminder-diagnostic-reason' }, diagnostic.reason), vue.createVNode('div', { class: 'reminder-diagnostic-meta' }, `来源:${diagnostic.sources};截止信息:${diagnostic.deadlineText}`) ])), vue.createVNode('button', { class: 'external-link-btn reminder-diagnostics-clear', onClick: clearReminderDiagnostics }, '清空记录') ] : [vue.createVNode('div', { class: 'empty-state' }, '暂未记录跳过原因')]) : null ]) ] : null, tab === 'filter' ? [ vue.createVNode('div', { class: 'cx-settings-section-head' }, [ vue.createVNode('h3', null, '筛选与忽略'), vue.createVNode('p', null, '忽略任务或课程后会停止提醒;仅隐藏分类不会屏蔽提醒。') ]), vue.createVNode('section', { class: 'cx-settings-card' }, [ renderSettingsRow( '显示列表忽略操作', settings.value.ignoreEnabled ? '已开启,可在列表悬停或右侧点击忽略按钮。' : '默认关闭,不影响已有忽略记录。', renderSettingsToggle(settings.value.ignoreEnabled, '开启忽略按钮', e => updateSetting('ignoreEnabled', e.target.checked)) ), renderSettingsRow( '按课程忽略', `已忽略 ${getIgnoredItemsBySection('course').length} 门课程;被忽略课程的任务将从所有栏目隐藏。`, vue.createVNode('button', { class: 'external-link-btn', onClick: openCourseIgnoreDialog }, '选择要忽略的课程') ), renderSettingsRow( '动态忽略已完成或已过期内容', '规则会持续过滤之后加载的匹配内容;停用规则不会恢复手动忽略项。', vue.createVNode('button', { class: 'external-link-btn', onClick: openBulkIgnoreDialog }, '配置动态忽略规则') ) ]) ] : null, tab === 'sync' ? [ vue.createVNode('div', { class: 'cx-settings-section-head' }, [ vue.createVNode('h3', null, '同步与备份'), vue.createVNode('p', null, '配置轻量刷新、每日定时同步、请求节流与配置导入导出。') ]), vue.createVNode('section', { class: 'cx-settings-card' }, [ renderSettingsRow( '切回标签页轻量刷新(2 分钟防抖)', settings.value.lightRefreshEnabled ? '切回工作台标签页时仅静默刷新作业与考试,降低风控风险。' : '已关闭,仅手动触发刷新。', renderSettingsToggle(settings.value.lightRefreshEnabled, '切回标签页轻量刷新', e => updateSetting('lightRefreshEnabled', e.target.checked)) ), renderSettingsRow( '每日定时自动同步', settings.value.scheduledSyncEnabled ? `已开启:${(settings.value.scheduledSyncTimes || []).join('、')}` : '已关闭,不按固定时间点自动全量同步。', renderSettingsToggle(settings.value.scheduledSyncEnabled, '每日定时自动同步', e => updateSetting('scheduledSyncEnabled', e.target.checked)) ), settings.value.scheduledSyncEnabled ? vue.createVNode('div', { class: 'cx-sync-times-box', style: 'margin:0 16px 14px;' }, [ vue.createVNode('div', { class: 'cx-sync-chips' }, Array.from(new Set([...PRESET_SYNC_TIMES, ...(settings.value.scheduledSyncTimes || [])])).sort().map(timeStr => { const active = (settings.value.scheduledSyncTimes || []).includes(timeStr); return vue.createVNode('button', { type: 'button', class: `cx-time-chip ${active ? 'active' : ''}`, onClick: () => toggleScheduledSyncTime(timeStr) }, timeStr); }) ), vue.createVNode('div', { class: 'cx-sync-custom-row' }, [ vue.createVNode('input', { type: 'text', class: 'cx-sync-input', placeholder: '自定义 HH:mm(如 09:30)', value: customSyncTimeInput.value, onInput: e => { customSyncTimeInput.value = e.target.value; } }), vue.createVNode('button', { type: 'button', class: 'external-link-btn', onClick: addCustomScheduledSyncTime }, '添加时间') ]) ]) : null, renderSettingsRow( '课程进度请求间隔(毫秒)', `可设置 ${MIN_PROGRESS_DELAY}–${MAX_PROGRESS_DELAY}ms,默认 ${DEFAULT_PROGRESS_DELAY}ms;适当增大可降低风控概率。`, vue.createVNode('div', { style: 'display:flex;align-items:center;gap:6px;' }, [ vue.createVNode('input', { class: 'progress-delay-input', type: 'number', min: MIN_PROGRESS_DELAY, max: MAX_PROGRESS_DELAY, step: 100, value: progressDelay.value, 'aria-label': '课程进度请求间隔(毫秒)', onChange: e => updateProgressDelay(e.target.value) }), vue.createVNode('span', { class: 'progress-delay-unit' }, 'ms') ]) ), renderSettingsRow( '短时缓存(5 分钟)', settings.value.shortTermCacheEnabled ? '已开启,刷新时先展示缓存内容并在后台更新。' : '已关闭,每次直接读取最新数据。', renderSettingsToggle(settings.value.shortTermCacheEnabled, '开启短时缓存', e => updateSetting('shortTermCacheEnabled', e.target.checked)) ) ]), vue.createVNode('section', { class: 'cx-settings-card', style: 'margin-top:12px;' }, [ renderSettingsRow( '配置备份与跨端迁移', '导出或导入忽略课程列表、过滤规则与全部脚本设置(JSON)。', vue.createVNode('div', { style: 'display:flex;gap:8px;flex-wrap:wrap;' }, [ vue.createVNode('button', { type: 'button', class: 'external-link-btn', onClick: openConfigExportDialog }, [cxIcon('upload', 14), '导出 JSON']), vue.createVNode('button', { type: 'button', class: 'external-link-btn', onClick: openConfigImportDialog }, [cxIcon('download', 14), '导入 JSON']) ]) ) ]) ] : null, tab === 'help' ? [ vue.createVNode('div', { class: 'cx-settings-section-head' }, [ vue.createVNode('h3', null, '帮助与指南'), vue.createVNode('p', null, '了解新版工作台操作技巧、重看交互式新手引导与常见问题解答。') ]), vue.createVNode('section', { class: 'cx-settings-card' }, [ renderSettingsRow( '交互式新手引导(模拟数据演示)', '通过 6 步高亮引导与演示数据快速熟悉顶部命令栏、KPI 卡片、任务工作台与课程进度功能。', vue.createVNode('button', { type: 'button', class: 'cx-btn-primary', onClick: startOnboardingTour }, [cxIcon('sparkles', 14), '重看新手引导']) ), renderSettingsRow( '高效操作速览', 'Ctrl+K 快速聚焦搜索;弹窗列表支持按住 Shift 区间连选;作业/讨论/问卷支持点击直达;考试页自动切换整卷预览。', vue.createVNode('span', { class: 'badge status-normal' }, '快捷键 & 技巧') ) ]), vue.createVNode('section', { class: 'cx-settings-card', style: 'margin-top:12px;' }, [ vue.createVNode('div', { class: 'cx-qa-list' }, [ { q: 'Q1:为什么首次点击某些作业或活动会提示允许弹出窗口?', a: '浏览器会拦截异步请求后打开的新标签页。建议在浏览器地址栏右侧点击「始终允许 chaoxing.com 的弹出式窗口」;讨论/分组/问卷已支持在打开的新标签页内自动跳转,无需二次弹窗。' }, { q: 'Q2:如何减少触发学习通 429 限流或验证码?', a: '脚本已内置两阶段节流加载与 429 自动降速熔断。强烈建议在「筛选与忽略 → 按课程忽略」或「课程进度 → 清理 0 任务点」中隐藏往期结课与 0 任务点课程,请求量会成倍下降。' }, { q: 'Q3:误隐藏了 0 任务点课程或某条任务怎么恢复?', a: '进入对应分类全屏页或右侧课程进度栏,点击「已忽略(N)」即可逐条撤销或批量勾选恢复。' }, { q: 'Q4:首页 Tab 数量与默认筛选可以改成显示全部吗?', a: '可以。在「设置 → 展示与提醒」中可分别调整「作业/考试/课程任务默认筛选(未完成/全部)」与「首页 Tab 数量徽标(仅未完成/全部任务)」。' }, { q: 'Q5:换浏览器或重装脚本后如何保留忽略课程和设置?', a: '前往「设置 → 同步与备份 → 配置备份与跨端迁移」,点击「导出 JSON」复制备份,在新设备点击「导入 JSON」即可一键还原。' } ].map(qa => vue.createVNode('div', { class: 'cx-qa-item' }, [ vue.createVNode('div', { class: 'cx-qa-q' }, qa.q), vue.createVNode('div', { class: 'cx-qa-a' }, qa.a) ]))) ]) ] : null ]) ]), showCourseIgnoreDialog.value ? vue.createVNode('div', { class: 'confirm-overlay', onClick: () => { showCourseIgnoreDialog.value = false; } }, [ vue.createVNode('div', { class: 'confirm-dialog course-ignore-dialog', onClick: e => e.stopPropagation() }, [ vue.createVNode('div', { class: 'confirm-title' }, '选择要忽略的课程'), vue.createVNode('div', { class: 'confirm-hint', style: 'margin-bottom:12px;' }, '课程被忽略后,所有栏目及高优先级待办都会同步隐藏(支持按住 Shift 连续勾选)。'), settingsCoursesLoading.value ? vue.createVNode('div', { class: 'loading-text' }, '正在读取课程…') : settingsCourses.value.length === 0 ? vue.createVNode('div', { class: 'empty-state' }, '暂无可管理课程') : vue.createVNode('div', { class: 'course-ignore-list' }, settingsCourses.value.map((course, idx) => vue.createVNode('label', { class: 'course-ignore-option' }, [ vue.createVNode('input', { type: 'checkbox', checked: isCourseIgnored(course), onClick: e => handleCourseIgnoreCheckboxClick(course, idx, e) }), vue.createVNode('span', null, course.courseName) ]) )), vue.createVNode('div', { class: 'confirm-actions' }, [ vue.createVNode('button', { class: 'confirm-ok-btn', onClick: () => { showCourseIgnoreDialog.value = false; notifySettingsSaved('课程忽略已保存,列表已实时更新'); } }, '完成') ]) ]) ]) : null, showOtherTasksDialog.value ? vue.createVNode('div', { class: 'confirm-overlay', onClick: () => { showOtherTasksDialog.value = false; } }, [ vue.createVNode('div', { class: 'confirm-dialog other-tasks-dialog', onClick: e => e.stopPropagation() }, [ vue.createVNode('div', { class: 'confirm-title' }, '配置其他任务'), vue.createVNode('div', { class: 'confirm-hint', style: 'margin-bottom:12px;' }, '可选择显示全部其他任务,或仅显示你勾选的类型。'), vue.createVNode('label', { class: 'other-task-all-option' }, [ vue.createVNode('input', { type: 'checkbox', checked: settings.value.showOtherTasks, onChange: e => updateSetting('showOtherTasks', e.target.checked) }), vue.createVNode('span', null, '显示全部其他任务') ]), vue.createVNode('div', { class: 'course-ignore-list', style: settings.value.showOtherTasks ? 'opacity:.55;pointer-events:none;' : '' }, OTHER_TASK_TYPES.map(type => vue.createVNode('label', { class: 'course-ignore-option' }, [ vue.createVNode('input', { type: 'checkbox', checked: (settings.value.otherTaskTypes || []).includes(type), onChange: e => toggleOtherTaskType(type, e.target.checked) }), vue.createVNode('span', null, type) ]) )), vue.createVNode('div', { class: 'confirm-actions' }, [ vue.createVNode('button', { class: 'confirm-ok-btn', onClick: () => { showOtherTasksDialog.value = false; notifySettingsSaved('其他任务展示设置已保存,列表已实时更新'); } }, '完成') ]) ]) ]) : null, showBulkIgnoreDialog.value ? vue.createVNode('div', { class: 'confirm-overlay', onClick: () => { showBulkIgnoreDialog.value = false; } }, [ vue.createVNode('div', { class: 'confirm-dialog bulk-ignore-dialog', onClick: e => e.stopPropagation() }, [ vue.createVNode('div', { class: 'confirm-title' }, '动态忽略已完成或已过期内容'), vue.createVNode('div', { class: 'confirm-hint', style: 'margin-bottom:12px;' }, '规则会持续作用于以后出现的匹配内容;取消勾选不会释放你手动忽略的内容。'), (() => { const previewItems = getBulkIgnorePreviewItems(); const previewLimit = 100; return vue.createVNode('div', { class: 'bulk-ignore-layout' }, [ vue.createVNode('div', { class: 'bulk-ignore-rules' }, [ vue.createVNode('div', { class: 'bulk-ignore-panel-title' }, '选择规则'), vue.createVNode('div', { class: 'course-ignore-list' }, bulkIgnoreOptions.map(option => vue.createVNode('label', { class: 'course-ignore-option' }, [ vue.createVNode('input', { type: 'checkbox', checked: bulkIgnoreSelection.value.has(option.key), onChange: e => toggleBulkIgnoreType(option.key, e.target.checked) }), vue.createVNode('span', null, option.label), vue.createVNode('span', { style: 'margin-left:auto;color:var(--cx-text-muted);font-size:12px;' }, String(getCompletedItemsForBulkIgnore(option.key).length)) ]) )) ]), vue.createVNode('aside', { class: 'bulk-ignore-preview' }, [ vue.createVNode('div', { class: 'bulk-ignore-preview-header' }, [ vue.createVNode('span', { class: 'bulk-ignore-panel-title' }, '将被忽略的内容'), vue.createVNode('span', { class: 'bulk-ignore-preview-count' }, `共 ${previewItems.length} 项`) ]), previewItems.length === 0 ? vue.createVNode('div', { class: 'bulk-ignore-preview-empty' }, '勾选左侧规则后,在这里预览会被忽略的内容') : vue.createVNode('div', { class: 'bulk-ignore-preview-list' }, [ previewItems.slice(0, previewLimit).map(entry => vue.createVNode('div', { class: 'bulk-ignore-preview-item' }, [ vue.createVNode('span', { class: 'bulk-ignore-type' }, entry.label), vue.createVNode('div', { class: 'bulk-ignore-preview-copy' }, [ vue.createVNode('div', { class: 'bulk-ignore-preview-name' }, entry.item.title || entry.item.courseName || '未命名内容'), vue.createVNode('div', { class: 'bulk-ignore-preview-course' }, entry.item.course || entry.item.courseName || '课程信息暂缺') ]) ])), previewItems.length > previewLimit ? vue.createVNode('div', { class: 'bulk-ignore-preview-more' }, `其余 ${previewItems.length - previewLimit} 项将在保存后按规则自动忽略`) : null ]) ]) ]); })(), vue.createVNode('div', { class: 'confirm-actions' }, [ vue.createVNode('button', { class: 'confirm-cancel-btn', onClick: () => { showBulkIgnoreDialog.value = false; bulkIgnoreSelection.value = new Set(); } }, '取消'), vue.createVNode('button', { class: 'confirm-ok-btn', onClick: runBulkIgnore }, '保存规则') ]) ]) ]) : null, showConfigTransferDialog.value ? vue.createVNode('div', { class: 'confirm-overlay', onClick: () => { showConfigTransferDialog.value = false; } }, [ vue.createVNode('div', { class: 'confirm-dialog', style: 'max-width:560px;width:92%;', onClick: e => e.stopPropagation() }, [ vue.createVNode('div', { class: 'confirm-title' }, configTransferMode.value === 'export' ? '导出配置 JSON' : '导入配置 JSON'), vue.createVNode('div', { class: 'confirm-hint', style: 'margin-bottom:10px;' }, configTransferMode.value === 'export' ? '可复制以下内容备份或同步到其他设备。' : '粘贴之前导出的配置 JSON,将覆盖当前设置与忽略列表。'), vue.createVNode('textarea', { class: 'cx-config-textarea', readonly: configTransferMode.value === 'export', value: configTransferText.value, placeholder: '在此粘贴配置 JSON...', onInput: e => { configTransferText.value = e.target.value; } }), vue.createVNode('div', { class: 'confirm-actions' }, [ vue.createVNode('button', { class: 'confirm-cancel-btn', onClick: () => { showConfigTransferDialog.value = false; } }, '关闭'), configTransferMode.value === 'export' ? vue.createVNode('button', { class: 'confirm-ok-btn', onClick: copyExportedConfig }, '复制 JSON') : vue.createVNode('button', { class: 'confirm-ok-btn', onClick: applyImportedConfig }, '确认导入') ]) ]) ]) : null, settingsToast.value ? vue.createVNode('div', { class: 'settings-toast', role: 'status' }, [ cxIcon('check', 14), vue.createVNode('span', null, settingsToast.value) ]) : null ]); }; // 跳转到原始页面(真正的外部跳转) const navigateToOriginal = (type) => { let url = ''; switch (type) { case 'todo': url = URL_TODO; break; case 'homework': url = URL_HOMEWORK; break; case 'exam': url = URL_EXAM; break; case 'activities': url = URL_ACTIVITIES; break; } if (url) window.location.href = url; }; const refreshLightTasks = async (isManual = false) => { if (lightRefreshing.value) return; const now = Date.now(); if (!isManual && now - lastLightRefreshAt < LIGHT_REFRESH_MIN_INTERVAL) return; lightRefreshing.value = true; try { const freshHomework = await loadHomeworkData(); await Promise.all([loadExamData(), loadTodoData(freshHomework)]); lastLightRefreshAt = Date.now(); if (isManual) notifySettingsSaved('已轻量刷新作业、考试与待办'); } finally { lightRefreshing.value = false; } }; const checkScheduledSync = async () => { const due = isScheduledSyncDueNow(settings.value); if (!due) return; markScheduledSyncTriggered(due.todayKey, due.dueSlots, due.triggeredToday); const freshHomework = await loadHomeworkData(); await Promise.all([loadExamData(), loadTodoData(freshHomework)]); retryActivitiesData(); }; const handleDashboardVisibilitySync = () => { if (document.visibilityState !== 'visible') return; checkScheduledSync(); if (settings.value.lightRefreshEnabled) { refreshLightTasks(false); } }; const handleGlobalKeydown = (e) => { if ((e.ctrlKey || e.metaKey) && String(e.key || '').toLowerCase() === 'k') { const input = document.getElementById('cx-global-search-input'); if (input) { e.preventDefault(); input.focus(); input.select?.(); } } else if (e.key === 'Escape') { const input = document.getElementById('cx-global-search-input'); if (input && document.activeElement === input) { if (searchQuery.value) { searchQuery.value = ''; } else { input.blur(); } } } }; vue.onMounted(() => { applyThemeMode(settings.value.themeMode); syncExamAutoPreviewPreference(settings.value.examAutoFullPreviewEnabled); cleanupDashboardCache(); hydrateShortTermCache(); cacheCleanupTimer = setInterval(cleanupDashboardCache, DASHBOARD_CACHE_TTL); scheduledSyncTimer = setInterval(() => { checkScheduledSync(); }, 30 * 1000); window.addEventListener('focus', scheduleDeadlineReminderEvaluation); window.addEventListener('keydown', handleGlobalKeydown); document.addEventListener('visibilitychange', handleReminderPageVisibility); document.addEventListener('visibilitychange', handleDashboardVisibilitySync); startDeadlineReminderMonitoring(); loadTodoData(); loadHomeworkData(); loadExamData(); lastLightRefreshAt = Date.now(); // 首页卡片与高优先级信息属于核心内容,首次打开必须完整加载。 // 仅设置课程列表、课程进度悬浮详情等非首屏资源保持按需请求。 loadActivitiesData(); loadAllCourseProgress(); const due = isScheduledSyncDueNow(settings.value); if (due) markScheduledSyncTriggered(due.todayKey, due.dueSlots, due.triggeredToday); window.addEventListener('resize', updateTourSpotlight); if (!settings.value.onboardingTourSeen) { setTimeout(() => { if (currentView.value === 'dashboard' && !tourActive.value) { startOnboardingTour(); } }, 550); } }); vue.onUnmounted(() => { if (deadlineReminderTimer) clearInterval(deadlineReminderTimer); if (deadlineReminderEvaluationTimer !== null) clearTimeout(deadlineReminderEvaluationTimer); if (scheduledSyncTimer) clearInterval(scheduledSyncTimer); if (restoredCourseSyncTimer) clearTimeout(restoredCourseSyncTimer); if (cacheCleanupTimer) clearInterval(cacheCleanupTimer); window.removeEventListener('focus', scheduleDeadlineReminderEvaluation); window.removeEventListener('keydown', handleGlobalKeydown); window.removeEventListener('resize', updateTourSpotlight); document.removeEventListener('visibilitychange', handleReminderPageVisibility); document.removeEventListener('visibilitychange', handleDashboardVisibilitySync); }); return (_ctx, _cache) => { const _component_v_card = vue.resolveComponent("v-card"); const _component_v_card_title = vue.resolveComponent("v-card-title"); const _component_v_card_text = vue.resolveComponent("v-card-text"); const _component_v_list = vue.resolveComponent("v-list"); const _component_v_list_item = vue.resolveComponent("v-list-item"); const _component_v_chip = vue.resolveComponent("v-chip"); const _component_v_btn = vue.resolveComponent("v-btn"); const _component_v_progress_linear = vue.resolveComponent("v-progress-linear"); const _component_v_alert = vue.resolveComponent("v-alert"); const _component_v_spacer = vue.resolveComponent("v-spacer"); const _component_v_icon = vue.resolveComponent("v-icon"); const _component_v_container = vue.resolveComponent("v-container"); const dashboardStyle = ` :root, [data-cx-theme="light"] { color-scheme: light; --cx-bg: #f8f9fb; --cx-card: #ffffff; --cx-card-elevated: #ffffff; --cx-surface-subtle: #f3f4f6; --cx-surface-hover: #f3f4f6; --cx-text: #111827; --cx-text-secondary: #374151; --cx-text-muted: #6b7280; --cx-border: #e5e7eb; --cx-divider: #f3f4f6; --cx-accent: #2563eb; --cx-accent-soft: rgba(37, 99, 235, 0.08); --cx-shadow: 0 1px 2px rgba(15, 23, 42, 0.04); --cx-urgent-bg: rgba(239, 68, 68, 0.07); --cx-urgent-border: rgba(239, 68, 68, 0.22); --cx-urgent-text: #b91c1c; --cx-skeleton-base: #eef0f4; --cx-skeleton-shine: #f8fafc; --cx-scrollbar-thumb: #d1d5db; --cx-scrollbar-thumb-hover: #9ca3af; } :root[data-cx-theme="dark"], [data-cx-theme="dark"] { color-scheme: dark; --cx-bg: #0b0d12; --cx-card: #12151c; --cx-card-elevated: #171b24; --cx-surface-subtle: #181c26; --cx-surface-hover: #1d222e; --cx-text: #f3f4f6; --cx-text-secondary: #d1d5db; --cx-text-muted: #9ca3af; --cx-border: rgba(255, 255, 255, 0.09); --cx-divider: rgba(255, 255, 255, 0.06); --cx-accent: #60a5fa; --cx-accent-soft: rgba(96, 165, 250, 0.14); --cx-shadow: 0 2px 12px rgba(0, 0, 0, 0.4); --cx-urgent-bg: rgba(239, 68, 68, 0.12); --cx-urgent-border: rgba(248, 113, 113, 0.28); --cx-urgent-text: #fca5a5; --cx-skeleton-base: #181c26; --cx-skeleton-shine: #232936; --cx-scrollbar-thumb: rgba(255, 255, 255, 0.16); --cx-scrollbar-thumb-hover: rgba(255, 255, 255, 0.28); } html, body { width: 100% !important; max-width: 100vw !important; min-width: 0 !important; margin: 0 !important; background-color: var(--cx-bg) !important; color: var(--cx-text) !important; } .chaoxing-list-root, .chaoxing-list-root > * { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; } .dashboard-wrapper { width: 100%; max-width: 100%; font-family: "Microsoft YaHei", "PingFang SC", -apple-system, BlinkMacSystemFont, sans-serif; background-color: var(--cx-bg); color: var(--cx-text); min-height: 100vh; min-width: 0; padding: 20px; } .dashboard-wrapper * { box-sizing: border-box; } .dashboard-wrapper a { text-decoration: none; color: inherit; } .main-content { width: 100%; max-width: 1200px; min-width: 0; margin: 0 auto; container-name: chaoxing-main; container-type: inline-size; } /* 滚动条美化 */ ::-webkit-scrollbar { width: 6px; height: 6px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: var(--cx-scrollbar-thumb); border-radius: 3px; } ::-webkit-scrollbar-thumb:hover { background: var(--cx-scrollbar-thumb-hover); } /* 欢迎语区域 */ .dashboard-header { margin-bottom: 24px; background: #fff; padding: 20px 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); display: flex; flex-direction: column; gap: 16px; } .welcome-row { display: flex; justify-content: space-between; align-items: center; width: 100%; min-width: 0; } .welcome-text { font-size: 22px; font-weight: 600; color: #262626; display: flex; align-items: center; gap: 10px; min-width: 0; } .welcome-actions { display: flex; align-items: center; gap: 12px; min-width: 0; max-width: 100%; } .date-info { font-size: 14px; color: #8c8c8c; min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .settings-onboarding { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 14px; border: 1px solid #cfe8ff; border-radius: 10px; background: linear-gradient(135deg, #f0f9ff, #f8fbff); color: #315a7d; font-size: 13px; line-height: 1.55; } .settings-onboarding-copy { display: flex; align-items: center; gap: 9px; } .settings-onboarding-icon { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: 8px; background: #dff1ff; font-size: 15px; } .settings-onboarding-actions { display: flex; gap: 8px; flex-shrink: 0; } .course-ignore-onboarding { position: fixed; right: 24px; bottom: 24px; z-index: 8000; width: min(390px, calc(100vw - 32px)); padding: 18px; border: 1px solid #d8e8ff; border-radius: 14px; background: #fff; box-shadow: 0 16px 44px rgba(15, 23, 42, .18); animation: course-ignore-hint-in .24s ease-out; } .course-ignore-onboarding-head { display: flex; align-items: flex-start; gap: 11px; } .course-ignore-onboarding-icon { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; width: 34px; height: 34px; border-radius: 10px; background: #eef5ff; font-size: 18px; } .course-ignore-onboarding-title { color: #1e293b; font-size: 15px; font-weight: 600; } .course-ignore-onboarding-copy { margin-top: 4px; color: #64748b; font-size: 13px; line-height: 1.6; } .course-ignore-onboarding-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; } @keyframes course-ignore-hint-in { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } } /* 紧急提醒条 */ .urgent-strip { display: flex; align-items: center; justify-content: space-between; background-color: #fff1f0; border: 1px solid #ffccc7; padding: 10px 16px; border-radius: 6px; color: #5c0011; font-size: 14px; width: 100%; transition: all 0.2s; cursor: pointer; } .urgent-strip:hover { background-color: #ffccc7; } .urgent-left { display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1; } .urgent-left > span:last-child { min-width: 0; overflow-wrap: anywhere; line-height: 1.5; } .urgent-icon { font-size: 16px; } .urgent-count { font-weight: bold; color: #cf1322; } .urgent-action { flex: 0 0 auto; margin-left: 10px; font-size: 13px; color: #8c8c8c; white-space: nowrap; } /* 仪表盘网格 */ .dashboard-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 20px; align-items: stretch; } .dashboard-skeleton-page { background: var(--cx-bg); } .dashboard-skeleton-overlay { position: fixed; inset: 0; z-index: 100001; overflow: auto; padding: 20px; background: var(--cx-bg); opacity: 1; transition: opacity 340ms cubic-bezier(.22,.61,.36,1); pointer-events: none; } .dashboard-skeleton-overlay.is-leaving { opacity: 0; } .dashboard-skeleton-refresh { display: flex; justify-content: flex-end; align-items: center; gap: 8px; height: 28px; margin-bottom: 8px; color: var(--cx-text-muted); font-size: 12px; letter-spacing: .2px; } .dashboard-skeleton-spinner { width: 14px; height: 14px; border: 2px solid var(--cx-border); border-top-color: var(--cx-accent); border-radius: 50%; animation: dashboard-skeleton-spin .75s linear infinite; } .dashboard-skeleton-header { min-height: 92px; display: flex; flex-direction: column; justify-content: center; gap: 12px; } .dashboard-skeleton-block, .dashboard-skeleton-card::before, .dashboard-skeleton-card::after { display: block; border-radius: 999px; background: linear-gradient(90deg, var(--cx-skeleton-base) 25%, var(--cx-skeleton-shine) 45%, var(--cx-skeleton-base) 65%); background-size: 220% 100%; animation: dashboard-skeleton-shine 1s linear infinite; } .dashboard-skeleton-title { width: 180px; height: 22px; } .dashboard-skeleton-text { width: 300px; max-width: 65%; height: 13px; } .dashboard-skeleton-alert { height: 48px; padding: 0 20px; margin-bottom: 20px; display: flex; align-items: center; gap: 12px; border-radius: 10px; border: 1px solid var(--cx-urgent-border); background: var(--cx-urgent-bg); } .dashboard-skeleton-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--cx-urgent-text); opacity: 0.65; } .dashboard-skeleton-alert-line { width: min(460px, 72%); height: 14px; } .dashboard-skeleton-card { min-height: 245px; padding: 24px; overflow: hidden; background: var(--cx-card); border: 1px solid var(--cx-border); } .dashboard-skeleton-card::before { content: ''; width: 104px; height: 18px; } .dashboard-skeleton-card::after { content: ''; width: 78%; height: 14px; margin-top: 42px; box-shadow: 0 42px 0 var(--cx-skeleton-base), 0 84px 0 var(--cx-skeleton-base); } @keyframes dashboard-skeleton-shine { to { background-position: -220% 0; } } @keyframes dashboard-skeleton-spin { to { transform: rotate(360deg); } } /* 卡片通用样式 */ .card { background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); transition: all 0.3s ease; display: flex; flex-direction: column; overflow: hidden; } .card:hover { box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08); transform: translateY(-2px); } /* 卡片标题栏 */ .card-header { padding: 18px 24px; border-bottom: 1px solid #f5f5f5; display: flex; justify-content: space-between; align-items: center; } .card-title { font-size: 16px; font-weight: 600; display: flex; align-items: center; gap: 10px; color: #333; } .indicator-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; } .card-more { font-size: 13px; color: #999; cursor: pointer; } .card-more:hover { color: #1890ff; } /* 卡片内容区 */ .card-body { padding: 0 12px; max-height: 350px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; } .card-body > .empty-state { flex: 1; min-height: 180px; display: flex; align-items: center; justify-content: center; text-align: center; } /* 列表项 */ .list-item { display: flex; justify-content: space-between; align-items: center; padding: 16px 12px; border-bottom: 1px dashed #f0f0f0; cursor: pointer; transition: background 0.2s; } .list-item:last-child { border-bottom: none; } .list-item:hover { background-color: #fafafa; border-radius: 6px; } /* 左侧内容 */ .item-main { flex: 1; margin-right: 12px; min-width: 0; } .task-title { font-size: 14px; color: #333; margin-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 500; } .task-meta { display: flex; align-items: center; font-size: 12px; color: #999; gap: 8px; } .course-tag { background: #f7f7f7; padding: 2px 6px; border-radius: 4px; color: #666; font-size: 12px; } /* 右侧状态 */ .item-status { text-align: right; flex-shrink: 0; } /* 状态胶囊 */ .badge { font-size: 12px; padding: 2px 8px; border-radius: 10px; font-weight: normal; display: inline-block; } .status-urgent { background: #fff1f0; color: #cf1322; border: 1px solid #ffa39e; } .status-warning { background: #fffbe6; color: #d48806; border: 1px solid #ffe58f; } .status-normal { background: #e6f7ff; color: #096dd9; border: 1px solid #91d5ff; } .status-done { background: #f6ffed; color: #389e0d; border: 1px solid #b7eb8f; } .status-gray { background: #f5f5f5; color: #8c8c8c; border: 1px solid #d9d9d9; } /* 空状态 */ .empty-state { text-align: center; padding: 30px 0; color: #bfbfbf; font-size: 14px; } .lazy-load-state { width: 100%; border: 0; background: transparent; cursor: pointer; color: #7c8aa5; transition: color .2s, background .2s; } .lazy-load-state:hover { color: #1677ff; background: #f0f7ff; } /* 美化进度条 */ .loading-state { text-align: center; padding: 40px 0; } .loading-spinner { width: 40px; height: 40px; border: 3px solid #f3f3f3; border-top: 3px solid #1890ff; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto; } .content-skeleton { min-height: 180px; padding: 24px 14px; display: flex; flex-direction: column; justify-content: center; gap: 22px; } .content-skeleton-lines { display: grid; gap: 14px; } .content-skeleton-line { display: block; height: 14px; border-radius: 99px; background: linear-gradient(90deg, var(--cx-skeleton-base) 25%, var(--cx-skeleton-shine) 45%, var(--cx-skeleton-base) 65%); background-size: 220% 100%; animation: dashboard-skeleton-shine 1s linear infinite; } .content-skeleton-line.wide { width: 88%; } .content-skeleton-line.medium { width: 67%; } .content-skeleton-line.short { width: 45%; } .content-skeleton-message { display: flex; align-items: center; justify-content: center; gap: 8px; color: var(--cx-text-muted); font-size: 13px; } .content-skeleton-spinner { width: 15px; height: 15px; border: 2px solid var(--cx-border); border-top-color: var(--cx-accent); border-radius: 50%; animation: dashboard-skeleton-spin .75s linear infinite; } .cache-source-note { display: inline-flex; align-items: center; gap: 4px; margin-left: 8px; padding: 3px 8px; border-radius: 999px; background: rgba(245, 158, 11, 0.14); color: #d97706; font-size: 12px; font-weight: 500; } :root[data-cx-theme="dark"] .cache-source-note, [data-cx-theme="dark"] .cache-source-note { color: #fcd34d; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .loading-text { margin-top: 12px; color: #999; font-size: 13px; } /* 详情页视图 */ .detail-view { background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); min-height: 500px; } /* 课程进度全屏查看 - 网格布局 */ .detail-progress-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px; padding: 20px; max-height: calc(100vh - 200px); overflow-y: auto; } /* 课程进度详情使用页面滚动,悬浮卡片可以完整越出网格边界。 */ .progress-detail-body { max-height: none; overflow: visible; } .progress-detail-body .detail-progress-grid { max-height: none; overflow: visible; } .detail-progress-item { background: #fff; border-radius: 12px; padding: 16px; border: 1px solid #e8e8e8; transition: all 0.2s; cursor: pointer; position: relative; } .detail-progress-item:hover { border-color: #722ed1; box-shadow: 0 4px 12px rgba(114, 46, 209, 0.15); transform: translateY(-2px); z-index: 99999; } /* 详情页沿用首页的侧边悬浮,避免上下方向切换造成页面抖动。 */ .detail-progress-item .progress-tooltip { left: calc(100% + 12px) !important; right: auto !important; top: 0; bottom: auto; transform: none; width: 280px; max-height: 500px; z-index: 100000 !important; } .detail-progress-item .progress-tooltip::before { left: -8px !important; right: auto !important; top: 20px; bottom: auto; border: 8px solid transparent; border-right-color: #fff; border-bottom-color: transparent; border-left-color: transparent; } .detail-header { display: flex; align-items: center; justify-content: space-between; padding: 20px 24px; border-bottom: 1px solid #f5f5f5; } .detail-header-left { display: flex; align-items: center; gap: 12px; } .back-btn { display: flex; align-items: center; gap: 6px; padding: 8px 16px; background: #f5f5f5; border: none; border-radius: 6px; color: #666; font-size: 14px; cursor: pointer; transition: all 0.2s; } .back-btn:hover { background: #e8e8e8; color: #333; } .detail-title { font-size: 18px; font-weight: 600; color: #333; display: flex; align-items: center; gap: 10px; } .detail-count { font-size: 13px; color: #999; font-weight: normal; } .external-link-btn { padding: 8px 16px; background: #1890ff; border: none; border-radius: 6px; color: #fff; font-size: 13px; cursor: pointer; transition: all 0.2s; } .external-link-btn:hover { background: #40a9ff; } .detail-body { padding: 0 24px 24px; max-height: 600px; overflow-y: auto; } /* 设置页内容由页面统一滚动,避免详情容器再生成一条内层滚动条。 */ .settings-detail-body { max-height: none; overflow: visible; } .settings-group-heading { margin: 4px 0 12px; padding: 2px 0 12px 14px; border-bottom: 2px solid #dbeafe; border-left: 3px solid #3b82f6; } .settings-group-heading-spaced { margin-top: 34px; } .settings-group-heading h3 { margin: 0; color: #1e3a5f; font-size: 18px; font-weight: 700; line-height: 1.4; } .settings-group-heading p { margin: 5px 0 0; color: #52637b; font-size: 14px; line-height: 1.55; } .settings-section { min-width: 0; padding: 17px 18px; border: 1px solid #e2eaf4; border-radius: 12px; background: #fbfdff; } .settings-section > h3 { display: flex; align-items: center; gap: 8px; color: #26374b; font-size: 15px; font-weight: 650; line-height: 1.5; } .settings-section > h3::before { content: ''; display: inline-block; width: 4px; height: 15px; flex: 0 0 auto; border-radius: 99px; background: #60a5fa; } .settings-section > p { color: #64748b; font-size: 13px; line-height: 1.6; } .reminder-settings-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 8px; } .reminder-settings-row .settings-toggle-row { flex: 1 1 340px; } .reminder-diagnostics-toggle { margin-top: 12px; } .reminder-diagnostic-list { display: grid; gap: 8px; margin-top: 10px; } .reminder-diagnostic-item { min-width: 0; padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; } .reminder-diagnostic-heading { display: flex; justify-content: space-between; gap: 10px; color: #334155; font-size: 12px; } .reminder-diagnostic-heading strong { overflow-wrap: anywhere; } .reminder-diagnostic-heading span, .reminder-diagnostic-meta { color: #64748b; font-size: 11px; } .reminder-diagnostic-reason { margin-top: 5px; color: #9a3412; font-size: 12px; font-weight: 650; } .reminder-diagnostic-meta { margin-top: 4px; overflow-wrap: anywhere; line-height: 1.5; } .reminder-diagnostics-clear { justify-self: start; } .settings-detail-body .progress-delay-help { padding: 10px 12px; border-radius: 8px; background: #f1f5f9; color: #52637b; line-height: 1.6; } .external-link-btn:disabled { opacity: .55; cursor: not-allowed; } .detail-list-item { display: flex; justify-content: space-between; align-items: center; padding: 16px 0; border-bottom: 1px dashed #f0f0f0; cursor: pointer; transition: background 0.2s; } .detail-list-item:hover { background: #fafafa; margin: 0 -12px; padding: 16px 12px; border-radius: 6px; } .detail-list-item:last-child { border-bottom: none; } .detail-item-main { flex: 1; min-width: 0; margin-right: 16px; } .detail-item-title { font-size: 15px; color: #333; margin-bottom: 6px; font-weight: 500; } .detail-item-meta { display: flex; align-items: center; gap: 12px; font-size: 13px; color: #999; } .detail-item-status { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; } .status-time { font-size: 13px; color: #666; font-weight: 500; } .status-time.urgent { color: #cf1322; } /* 详情页工具栏 */ .detail-toolbar { display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; background: #fafafa; border-bottom: 1px solid #f0f0f0; } .sort-container { display: flex; align-items: center; gap: 8px; } .sort-label { font-size: 13px; color: #666; } .sort-select { padding: 6px 12px; border: 1px solid #d9d9d9; border-radius: 4px; font-size: 13px; color: #333; background: #fff; cursor: pointer; outline: none; } .sort-select:hover { border-color: #40a9ff; } .sort-select:focus { border-color: #1890ff; box-shadow: 0 0 0 2px rgba(24,144,255,0.2); } /* 查看按钮 */ .view-btn { padding: 6px 12px; background: #fff; border: 1px solid #1890ff; border-radius: 4px; color: #1890ff; font-size: 13px; cursor: pointer; transition: all 0.2s; } .view-btn:hover { background: #1890ff; color: #fff; } /* 列表项时间和状态组合显示 - 新布局 */ .item-time-status { display: flex; flex-direction: row; align-items: center; gap: 8px; flex-shrink: 0; } .status-info { display: flex; flex-direction: column; align-items: flex-end; gap: 2px; } .time-display { font-size: 12px; color: #999; } .time-display.urgent { color: #cf1322; font-weight: 500; } .detail-list-item .item-time-status { flex-direction: row; } .detail-list-item .status-info { min-width: 80px; } /* 课程进度卡片样式 - 保留桌面端原有的两列布局 */ .progress-card { min-height: 200px; grid-column: span 2; overflow: hidden; } .progress-card .card-body { height: 350px; min-height: 0; max-height: 350px; flex: 0 0 350px; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; scrollbar-gutter: stable; } .progress-items-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; align-items: stretch; grid-auto-rows: 1fr; overflow: visible; } /* 课程进度主体与其他卡片一致,保持固定区域并通过自身滚动查看。 */ .tooltip-overflow-visible { overflow: visible !important; } .progress-item { display: flex; align-items: flex-start; padding: 14px; border: 1px solid #f0f0f0; border-radius: 8px; cursor: pointer; transition: all 0.2s; position: relative; min-height: 80px; min-width: 0; overflow: visible; } .progress-item:hover { background: #f5f7fa; border-color: #1890ff; box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15); z-index: 10; } .progress-item:last-child { border-bottom: none; } /* 悬浮提示样式 - 左侧显示(右边卡片使用左侧悬浮) */ .progress-tooltip { display: none; position: absolute; left: calc(100% + 12px); top: 0; width: 280px; max-width: calc(100vw - 32px); max-height: 500px; overflow-y: auto; padding: 14px; background: #fff; border-radius: 8px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.18); z-index: 10000 !important; font-size: 13px; } .progress-tooltip::before { content: ''; position: absolute; left: -8px; top: 20px; border: 8px solid transparent; border-right-color: #fff; } /* 右侧卡片(偶数项)悬浮提示显示在左侧 */ .progress-item:nth-child(even) .progress-tooltip, .detail-progress-item:nth-child(even) .progress-tooltip { left: auto; right: calc(100% + 12px); } .progress-item:nth-child(even) .progress-tooltip::before, .detail-progress-item:nth-child(even) .progress-tooltip::before { left: auto; right: -8px; border-right-color: transparent; border-left-color: #fff; } .detail-progress-item:nth-child(even) .progress-tooltip { left: auto !important; right: calc(100% + 12px) !important; } .detail-progress-item:nth-child(even) .progress-tooltip::before { left: auto !important; right: -8px !important; } .progress-item.tooltip-upward .progress-tooltip { top: auto; bottom: 0; } .progress-item.tooltip-upward .progress-tooltip::before { top: auto; bottom: 20px; } .progress-item.tooltip-portal-active > .progress-tooltip, .detail-progress-item.tooltip-portal-active > .progress-tooltip { display: none !important; } .progress-tooltip-portal { display: block !important; position: fixed !important; right: auto !important; bottom: auto !important; transform: none !important; z-index: 100002 !important; pointer-events: none; } .progress-item:hover .progress-tooltip, .detail-progress-item:hover .progress-tooltip { display: block; } /* 增强版悬浮窗样式 - 活动列表区域 */ .tooltip-activities-section { margin-top: 12px; padding-top: 10px; border-top: 2px solid #f0f0f0; } .tooltip-activities-title { font-size: 13px; font-weight: 600; color: #333; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; } .tooltip-loading { text-align: center; padding: 15px; color: #999; font-size: 12px; } .tooltip-no-activities { text-align: center; padding: 10px; color: #bbb; font-size: 12px; } .tooltip-activity-group { margin-bottom: 10px; } .tooltip-activity-group:last-child { margin-bottom: 0; } .activity-group-title { display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; color: #555; margin-bottom: 6px; } .activity-icon { font-size: 14px; } .activity-count { color: #999; font-weight: normal; } .activity-list { display: flex; flex-direction: column; gap: 4px; padding-left: 20px; } .activity-item { display: flex; justify-content: space-between; align-items: center; font-size: 11px; padding: 4px 6px; background: #fafafa; border-radius: 4px; border-left: 2px solid #e8e8e8; } .activity-item.ongoing { background: #e6f7ff; border-left-color: #1890ff; } .activity-item.finished { background: #f6ffed; border-left-color: #52c41a; } .activity-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #333; } .activity-status { margin-left: 8px; padding: 2px 6px; border-radius: 3px; font-size: 10px; white-space: nowrap; flex-shrink: 0; } .activity-status.status-ongoing { background: #1890ff; color: #fff; } .activity-status.status-finished { background: #52c41a; color: #fff; } .activity-status.status-pending { background: #d9d9d9; color: #666; } @media (max-width: 960px) { .progress-items-grid { grid-template-columns: 1fr; } } @media (max-width: 720px) { .progress-detail-header { align-items: flex-start; flex-direction: column; gap: 12px; } .progress-detail-header > .progress-detail-actions { justify-content: flex-start; width: 100%; } .bulk-ignore-dialog { width: min(560px, calc(100vw - 24px)); } .bulk-ignore-layout { grid-template-columns: 1fr; } .bulk-ignore-preview-list { max-height: 180px; } .progress-card .card-body { overflow-x: hidden; } .progress-tooltip { left: 50% !important; right: auto !important; top: calc(100% + 8px); transform: translateX(-50%); width: min(320px, calc(100vw - 32px)); max-height: 400px; } .progress-tooltip::before { left: 50% !important; top: -8px; right: auto !important; transform: translateX(-50%); border-right-color: transparent !important; border-left-color: transparent !important; border-bottom-color: #fff; } .progress-item:nth-child(even) .progress-tooltip { left: 50% !important; right: auto !important; } .progress-item:nth-child(even) .progress-tooltip::before { left: 50% !important; right: auto !important; border-left-color: transparent !important; } } .tooltip-title { font-size: 14px; font-weight: 600; color: #333; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #f0f0f0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .tooltip-row { display: flex; justify-content: space-between; margin-bottom: 6px; color: #666; } .tooltip-row .label { color: #999; font-size: 12px; } .tooltip-row .value { font-weight: 500; color: #333; } .tooltip-row .value.highlight { color: #1890ff; } .tooltip-row .value.success { color: #52c41a; } .tooltip-row .value.warning { color: #faad14; } .tooltip-loading { text-align: center; padding: 20px; color: #999; } .progress-item-main { flex: 1; min-width: 0; margin-right: 12px; overflow: hidden; } .progress-item-title { font-size: 14px; color: #333; font-weight: 500; margin-bottom: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .progress-bar-wrapper { display: flex; align-items: center; gap: 8px; } .progress-bar { flex: 1; height: 8px; background: #f0f0f0; border-radius: 4px; overflow: hidden; } .progress-bar-fill { height: 100%; border-radius: 4px; transition: width 0.3s; } .progress-bar-fill.complete { background: linear-gradient(90deg, #52c41a, #73d13d); } .progress-bar-fill.warning { background: linear-gradient(90deg, #faad14, #ffc53d); } .progress-bar-fill.danger { background: linear-gradient(90deg, #f5222d, #ff4d4f); } .progress-bar-fill.normal { background: linear-gradient(90deg, #1890ff, #40a9ff); } .progress-rate { font-size: 14px; font-weight: 600; min-width: 50px; text-align: right; } .progress-rate.complete { color: #52c41a; } .progress-rate.warning { color: #faad14; } .progress-rate.danger { color: #cf1322; } .progress-rate.normal { color: #1890ff; } .progress-tasks-count { font-size: 12px; color: #999; margin-top: 4px; } .progress-unfinished { margin-top: 4px; font-size: 12px; color: #f5222d; } .progress-last-update { font-size: 12px; color: #bbb; margin-left: auto; } /* 进度卡片右侧信息栏 */ .progress-item-info { display: flex; flex-direction: column; align-items: flex-end; justify-content: flex-start; gap: 2px; min-width: 80px; flex-shrink: 0; } .progress-item-info .progress-rate { margin-bottom: 0; line-height: 1.2; } .progress-item-info .progress-tasks-count { margin-top: 0; line-height: 1.2; } .progress-item-info .ignore-btn { margin-top: 4px; margin-right: -4px; } .refresh-btn { padding: 4px 8px; background: transparent; border: 1px solid #d9d9d9; border-radius: 4px; font-size: 12px; color: #666; cursor: pointer; transition: all 0.2s; } .refresh-btn:hover { border-color: #1890ff; color: #1890ff; } .refresh-btn.disabled { background: #f5f5f5; border-color: #d9d9d9; color: #999; cursor: not-allowed; } .refresh-btn.disabled:hover { border-color: #d9d9d9; color: #999; } /* 移动端适配 */ @media (max-width: 640px) { .dashboard-wrapper { padding: 10px; } .welcome-row { flex-wrap: wrap; gap: 8px; } .welcome-actions { width: auto; margin-left: auto; flex-wrap: wrap; justify-content: flex-end; gap: 8px; } .dashboard-header { padding: 15px; } .card-header { padding: 15px; } .dashboard-grid { grid-template-columns: minmax(0, 1fr); } .progress-card { grid-column: span 1; } .urgent-strip { align-items: flex-start; gap: 8px; padding: 10px 12px; } .urgent-left { align-items: flex-start; } .urgent-action { align-self: center; } .settings-onboarding { flex-wrap: wrap; } .settings-onboarding-copy { flex: 1 1 100%; align-items: flex-start; } .settings-onboarding-actions { width: 100%; justify-content: flex-end; } .card { min-width: 0; } .card-header { gap: 10px; padding: 12px; } .card-body { min-width: 0; padding: 0 10px; } .list-item { align-items: flex-start; flex-wrap: wrap; gap: 7px; padding: 12px 6px; } .item-main { flex: 1 1 100%; min-width: 0; margin-right: 0; } .task-title { white-space: normal; overflow-wrap: anywhere; } .item-time-status { width: 100%; flex-wrap: wrap; justify-content: flex-start; gap: 6px; } .detail-header { flex-wrap: wrap; gap: 10px; padding: 14px 16px; } .detail-header-left { min-width: 0; flex-wrap: wrap; } .detail-body { padding: 0 12px 18px; } .detail-progress-grid { grid-template-columns: minmax(0, 1fr); gap: 12px; padding: 12px; } .settings-section { padding: 14px; } .settings-toggle-row { width: 100%; max-width: 100%; } .settings-section .external-link-btn { max-width: 100%; white-space: normal; } .course-ignore-onboarding { right: 16px; bottom: 16px; } } /* 仅在仪表盘内容区确实较窄时切换紧凑布局,避免桌面侧栏触发手机版样式。 */ @container chaoxing-main (max-width: 660px) { .dashboard-header { min-width: 0; padding: 15px; } .welcome-row { flex-wrap: wrap; gap: 8px; } .welcome-actions { width: auto; max-width: 100%; margin-left: auto; justify-content: flex-end; flex-wrap: wrap; gap: 8px; } .date-info { flex: 0 1 auto; white-space: nowrap; overflow-wrap: normal; } .dashboard-grid { grid-template-columns: minmax(0, 1fr); } .progress-card { grid-column: span 1; } .urgent-strip { align-items: flex-start; gap: 8px; padding: 10px 12px; } .urgent-left { align-items: flex-start; } .urgent-action { align-self: center; } .settings-onboarding { flex-wrap: wrap; } .settings-onboarding-copy { flex: 1 1 100%; align-items: flex-start; } .settings-onboarding-actions { width: 100%; justify-content: flex-end; } .card { min-width: 0; } .card-header { gap: 10px; padding: 12px; } .card-body { min-width: 0; padding: 0 10px; } .list-item, .detail-list-item { align-items: flex-start; flex-wrap: wrap; gap: 7px; padding: 12px 6px; } .item-main, .detail-list-item .item-main { flex: 1 1 100%; min-width: 0; margin-right: 0; } .task-title { white-space: normal; overflow-wrap: anywhere; } .item-time-status { width: 100%; flex-wrap: wrap; justify-content: flex-start; gap: 6px; } .detail-header { flex-wrap: wrap; gap: 10px; padding: 14px 16px; } .detail-header-left { min-width: 0; flex-wrap: wrap; } .detail-body { padding: 0 12px 18px; } .detail-progress-grid { grid-template-columns: minmax(0, 1fr); gap: 12px; padding: 12px; } .settings-section { padding: 14px; } .settings-toggle-row { width: 100%; max-width: 100%; } .settings-section .external-link-btn { max-width: 100%; white-space: normal; } } /* ===== 忽略功能样式 ===== */ /* 忽略按钮 - 默认隐藏,hover 显示 */ .ignore-btn { display: inline-flex; align-items: center; justify-content: center; opacity: 0.6; /* 默认可见但半透明,减少视觉干扰 */ margin-right: -4px; /* 进一步靠边 */ transition: opacity 0.2s; padding: 3px 7px; border: 1px solid #ffadd2; background: #fff0f6; color: #eb2f96; border-radius: 4px; font-size: 12px; cursor: pointer; white-space: nowrap; flex-shrink: 0; margin-left: 6px; } .list-item:hover .ignore-btn, .detail-list-item:hover .ignore-btn { opacity: 1; } .progress-item .ignore-btn { opacity: 0.6; } .progress-item:hover .ignore-btn { opacity: 1; } .ignore-btn:hover { background: #ffadd2; color: #9e1068; } /* 多选模式 */ .select-checkbox { width: 16px; height: 16px; border: 1.5px solid #d9d9d9; border-radius: 3px; margin-right: 10px; flex-shrink: 0; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s; background: #fff; } .select-checkbox.checked { background: #1890ff; border-color: #1890ff; color: #fff; } .select-mode-btn { padding: 3px 8px; border: 1px solid #d9d9d9; background: #fff; border-radius: 4px; font-size: 12px; color: #666; cursor: pointer; transition: all 0.2s; } .select-mode-btn:hover, .select-mode-btn.active { border-color: #eb2f96; color: #eb2f96; } /* 批量操作栏 */ .batch-bar { position: sticky; bottom: 0; background: #fff9f0; border-top: 1px solid #ffd591; padding: 10px 16px; display: flex; align-items: center; justify-content: space-between; font-size: 13px; color: #d46b08; z-index: 100; } .batch-ignore-btn { padding: 5px 14px; background: #eb2f96; color: #fff; border: none; border-radius: 4px; font-size: 13px; cursor: pointer; transition: background 0.2s; } .batch-ignore-btn:hover { background: #c41d7f; } .batch-ignore-btn:disabled { background: #faade9; cursor: not-allowed; } .batch-restore-btn { padding: 5px 14px; background: #1890ff; color: #fff; border: none; border-radius: 4px; font-size: 13px; cursor: pointer; } .batch-restore-btn:disabled { background: #91d5ff; cursor: not-allowed; } /* 确认弹窗 */ .confirm-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.45); z-index: 9000; display: flex; align-items: center; justify-content: center; } .confirm-dialog { background: #fff; border-radius: 10px; box-shadow: 0 8px 32px rgba(0,0,0,0.18); padding: 24px; width: 380px; max-width: calc(100vw - 32px); } .deadline-reminder-banner { position: fixed; z-index: 11000; top: 12px; left: 50%; transform: translateX(-50%); display: flex; align-items: center; gap: 12px; width: min(920px, calc(100vw - 24px)); padding: 10px 12px; border: 1px solid #f4c76e; border-radius: 12px; background: #fff8e8; color: #7c4a03; box-shadow: 0 8px 28px rgba(124, 74, 3, .18); } .deadline-reminder-banner-icon { flex: 0 0 auto; font-size: 17px; } .deadline-reminder-banner-viewport { min-width: 0; flex: 1; overflow: hidden; white-space: nowrap; } .deadline-reminder-banner-text { display: inline-block; font-size: 13px; font-weight: 600; } .deadline-reminder-banner-text.is-scrolling { padding-left: 100%; animation: deadline-reminder-scroll 22s linear infinite; } .deadline-reminder-banner:hover .deadline-reminder-banner-text.is-scrolling { animation-play-state: paused; } @keyframes deadline-reminder-scroll { from { transform: translateX(0); } to { transform: translateX(-100%); } } .deadline-reminder-banner-button { flex: 0 0 auto; padding: 6px 10px; border: 0; border-radius: 7px; background: #f59e0b; color: #fff; font-size: 12px; font-weight: 700; cursor: pointer; } .deadline-reminder-banner-close { flex: 0 0 auto; padding: 2px 5px; border: 0; background: transparent; color: #8c5a06; font-size: 20px; line-height: 1; cursor: pointer; } .deadline-reminder-overlay { position: fixed; z-index: 13000; inset: 0; display: flex; align-items: center; justify-content: center; padding: 20px; background: rgba(15, 23, 42, .58); backdrop-filter: blur(2px); } .deadline-reminder-dialog { display: flex; flex-direction: column; width: min(760px, 100%); max-height: min(82vh, 720px); overflow: hidden; border: 1px solid #f5d28b; border-radius: 16px; background: #fff; box-shadow: 0 24px 80px rgba(15, 23, 42, .28); } .deadline-reminder-dialog-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 22px 24px 16px; border-bottom: 1px solid #f1f5f9; } .deadline-reminder-dialog-header h2 { margin: 0; color: #1f2937; font-size: 20px; } .deadline-reminder-dialog-header p { margin: 6px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; } .deadline-reminder-header-icon { color: #d97706; font-size: 28px; } .deadline-reminder-list { display: grid; gap: 10px; min-height: 0; padding: 14px 20px; overflow-y: auto; } .deadline-reminder-item { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 13px 14px; border: 1px solid #f2e4c7; border-radius: 11px; background: #fffcf5; } .deadline-reminder-item-copy { min-width: 0; } .deadline-reminder-item-title { overflow-wrap: anywhere; color: #1f2937; font-size: 14px; font-weight: 700; } .deadline-reminder-item-course { margin-top: 4px; color: #64748b; font-size: 12px; } .deadline-reminder-item-time { margin-top: 5px; color: #b45309; font-size: 12px; font-weight: 650; } .deadline-reminder-item-actions { display: flex; flex: 0 0 auto; align-items: center; gap: 8px; } .deadline-reminder-go-button, .deadline-reminder-mute-button, .deadline-reminder-ack-button { padding: 8px 12px; border: 0; border-radius: 8px; font-size: 12px; font-weight: 700; cursor: pointer; } .deadline-reminder-go-button { background: #f59e0b; color: #fff; } .deadline-reminder-mute-button { background: #f1f5f9; color: #475569; } .deadline-reminder-dialog-footer { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 14px 20px 18px; border-top: 1px solid #f1f5f9; } .deadline-reminder-dialog-footer span { color: #64748b; font-size: 12px; line-height: 1.5; } .deadline-reminder-ack-button { min-width: 112px; background: #334155; color: #fff; } .deadline-reminder-go-button:hover, .deadline-reminder-ack-button:hover { filter: brightness(1.08); } .deadline-reminder-mute-button:hover { background: #e2e8f0; } .course-ignore-dialog { width: 560px; } .other-tasks-dialog { width: 480px; } .bulk-ignore-dialog { width: 900px; } .bulk-ignore-layout { display: grid; grid-template-columns: minmax(260px, .9fr) minmax(340px, 1.1fr); gap: 18px; min-height: 310px; } .bulk-ignore-rules, .bulk-ignore-preview { min-width: 0; padding: 12px; border: 1px solid #e8edf4; border-radius: 10px; background: #fbfdff; } .bulk-ignore-panel-title { font-size: 13px; font-weight: 600; color: #334155; } .bulk-ignore-rules .course-ignore-list { margin-top: 10px; max-height: 280px; } .bulk-ignore-preview { display: flex; flex-direction: column; } .bulk-ignore-preview-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 10px; border-bottom: 1px solid #e8edf4; } .bulk-ignore-preview-count { padding: 2px 8px; border-radius: 999px; background: #fff1f0; color: #cf1322; font-size: 12px; } .bulk-ignore-preview-list { flex: 1; min-height: 0; max-height: 280px; overflow-y: auto; margin-top: 8px; display: grid; gap: 7px; } .bulk-ignore-preview-item { display: flex; align-items: flex-start; gap: 8px; padding: 8px; border-radius: 7px; background: #fff; border: 1px solid #eef2f6; } .bulk-ignore-type { flex: 0 0 auto; padding: 2px 6px; border-radius: 4px; background: #fff7e6; color: #d48806; font-size: 11px; } .bulk-ignore-preview-copy { min-width: 0; } .bulk-ignore-preview-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #334155; font-size: 13px; } .bulk-ignore-preview-course { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 3px; color: #94a3b8; font-size: 12px; } .bulk-ignore-preview-empty { flex: 1; display: flex; align-items: center; justify-content: center; min-height: 210px; text-align: center; color: #94a3b8; font-size: 13px; } .bulk-ignore-preview-more { padding: 8px 2px 2px; color: #64748b; font-size: 12px; text-align: center; } .other-task-all-option { display: flex; align-items: center; gap: 10px; margin: 0 0 10px; padding: 11px 12px; border-radius: 8px; background: #eff6ff; color: #1d4ed8; cursor: pointer; } .settings-toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%); z-index: 12000; display: flex; align-items: center; gap: 8px; padding: 11px 16px; border-radius: 10px; background: #1f2937; color: #fff; box-shadow: 0 10px 28px rgba(15, 23, 42, .22); font-size: 13px; animation: settings-toast-in .18s ease-out; } @keyframes settings-toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } } .course-ignore-list { max-height: 360px; overflow-y: auto; display: grid; gap: 8px; padding: 2px; } .course-ignore-option { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; color: #334155; cursor: pointer; } .course-ignore-option:hover { background: #f8fafc; border-color: #93c5fd; } .settings-toggle-row { display: flex; align-items: center; gap: 12px; width: fit-content; padding: 10px 14px; border: 1px solid #dbe7f5; border-radius: 12px; background: linear-gradient(135deg, #f8fbff, #f2f8ff); cursor: pointer; transition: border-color .2s, box-shadow .2s, transform .2s; } .settings-toggle-row:hover { border-color: #91caff; box-shadow: 0 5px 14px rgba(24, 144, 255, .10); transform: translateY(-1px); } .settings-toggle-input { position: absolute; width: 1px; height: 1px; opacity: 0; } .settings-toggle-track { width: 42px; height: 24px; padding: 3px; border-radius: 999px; background: #cbd5e1; transition: background .22s ease; } .settings-toggle-knob { display: block; width: 18px; height: 18px; border-radius: 50%; background: #fff; box-shadow: 0 1px 3px rgba(15,23,42,.25); transition: transform .22s cubic-bezier(.22,.61,.36,1); } .settings-toggle-input:checked + .settings-toggle-track { background: #1677ff; } .settings-toggle-input:checked + .settings-toggle-track .settings-toggle-knob { transform: translateX(18px); } .settings-toggle-input:focus-visible + .settings-toggle-track { outline: 3px solid rgba(22,119,255,.24); outline-offset: 2px; } .settings-toggle-copy { display: flex; flex-direction: column; gap: 2px; color: #1e293b; } .settings-toggle-copy strong { font-size: 14px; font-weight: 600; } .settings-toggle-copy small { color: #64748b; font-size: 12px; } .progress-delay-setting { display: flex; align-items: center; gap: 10px; width: fit-content; } .progress-delay-label { color: #334155; font-size: 14px; font-weight: 600; } .progress-delay-input { width: 120px; padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; color: #1e293b; font-size: 14px; outline: none; } .progress-delay-input:focus { border-color: #1677ff; box-shadow: 0 0 0 3px rgba(22,119,255,.12); } .progress-delay-unit { color: #64748b; font-size: 13px; } .progress-delay-help { margin-top: 8px; color: #94a3b8; font-size: 12px; } .progress-delay-link { padding: 4px 8px; border: 1px solid #e2e8f0; border-radius: 5px; background: #fff; color: #64748b; font-size: 11px; cursor: pointer; } .progress-delay-link:hover { border-color: #91caff; color: #1677ff; } .progress-detail-actions { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px; max-width: 100%; } .confirm-title { font-size: 16px; font-weight: 600; color: #262626; margin-bottom: 12px; } .confirm-list { max-height: 160px; overflow-y: auto; margin-bottom: 12px; background: #fafafa; border-radius: 6px; padding: 8px 12px; } .confirm-list-item { font-size: 13px; color: #595959; padding: 4px 0; border-bottom: 1px dashed #f0f0f0; } .confirm-list-item:last-child { border-bottom: none; } .confirm-hint { font-size: 12px; color: #8c8c8c; margin-bottom: 16px; line-height: 1.6; } .confirm-actions { display: flex; justify-content: flex-end; gap: 10px; } .confirm-cancel-btn { padding: 7px 16px; border: 1px solid #d9d9d9; background: #fff; border-radius: 5px; font-size: 14px; cursor: pointer; color: #595959; } .confirm-ok-btn { padding: 7px 16px; background: #eb2f96; color: #fff; border: none; border-radius: 5px; font-size: 14px; cursor: pointer; } @media (max-width: 640px) { .deadline-reminder-banner { top: 6px; gap: 7px; padding: 8px; } .deadline-reminder-banner-text { font-size: 12px; } .deadline-reminder-overlay { align-items: flex-end; padding: 8px; } .deadline-reminder-dialog { max-height: 88vh; border-radius: 14px 14px 10px 10px; } .deadline-reminder-dialog-header { padding: 17px 16px 12px; } .deadline-reminder-dialog-header h2 { font-size: 17px; } .deadline-reminder-list { padding: 10px 12px; } .deadline-reminder-item { align-items: flex-start; flex-direction: column; gap: 10px; padding: 11px; } .deadline-reminder-item-actions { width: 100%; } .deadline-reminder-item-actions button { flex: 1; } .deadline-reminder-dialog-footer { align-items: stretch; flex-direction: column; padding: 12px; } .deadline-reminder-ack-button { width: 100%; } .reminder-settings-row { align-items: flex-start; flex-direction: column; } } .confirm-ok-btn:hover { background: #c41d7f; } /* 已忽略面板 */ .ignored-panel-btn { padding: 4px 10px; border: 1px solid #d9d9d9; background: #fff; border-radius: 4px; font-size: 12px; color: #666; cursor: pointer; transition: all 0.2s; } .ignored-panel-btn:hover { border-color: #1890ff; color: #1890ff; } .restore-single-btn { padding: 3px 8px; border: 1px solid #91d5ff; background: #e6f7ff; color: #1890ff; border-radius: 4px; font-size: 12px; cursor: pointer; white-space: nowrap; flex-shrink: 0; margin-left: 6px; } .restore-single-btn:hover { background: #1890ff; color: #fff; } .ignored-date { font-size: 11px; color: var(--cx-text-muted); } /* v2.6 新增组件与深色模式适配 */ .cx-kpi-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin-top: 14px; padding: 12px 10px; background: var(--cx-surface-subtle); border: 1px solid var(--cx-border); border-radius: 14px; } .cx-kpi-item { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 6px 4px; border-radius: 10px; cursor: pointer; transition: background .18s ease; } .cx-kpi-item:hover { background: var(--cx-surface-hover); } .cx-kpi-value { font-size: 22px; font-weight: 700; line-height: 1.2; color: var(--cx-text); } .cx-kpi-value.is-blue { color: var(--cx-accent); } .cx-kpi-value.is-green { color: #22c55e; } .cx-kpi-value.is-orange { color: #f59e0b; } .cx-kpi-label { font-size: 12px; color: var(--cx-text-muted); margin-top: 3px; } .cx-global-search-bar { display: flex; align-items: center; gap: 8px; margin-top: 12px; padding: 8px 12px; background: var(--cx-surface-subtle); border: 1px solid var(--cx-border); border-radius: 12px; } .cx-global-search-input { flex: 1 1 auto; min-width: 0; border: none; outline: none; background: transparent; color: var(--cx-text); font-size: 14px; } .cx-global-search-clear { border: none; background: var(--cx-surface-hover); color: var(--cx-text-muted); border-radius: 999px; width: 22px; height: 22px; cursor: pointer; font-size: 12px; line-height: 22px; text-align: center; } .cx-icon { display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; line-height: 1; } .cx-version-pill { display: inline-flex; align-items: center; padding: 2px 8px; margin-left: 8px; border-radius: 999px; font-size: 11px; font-weight: 600; background: var(--cx-accent-soft); color: var(--cx-accent); border: 1px solid var(--cx-border); vertical-align: middle; } .external-link-btn, .back-btn, .ignored-panel-btn, .select-mode-btn, .refresh-btn, .progress-delay-link, .cx-segment-btn, .cx-icon-refresh-btn, .ignore-btn { display: inline-flex; align-items: center; gap: 5px; } .welcome-text, .empty-state, .confirm-title, .tooltip-activities-title, .activity-group-title, .deadline-reminder-banner-icon, .settings-onboarding-icon, .course-ignore-onboarding-icon { display: inline-flex; align-items: center; gap: 6px; } .cx-segmented-control { display: inline-flex; align-items: center; gap: 4px; padding: 4px; background: var(--cx-surface-subtle); border: 1px solid var(--cx-border); border-radius: 10px; flex-wrap: wrap; } .cx-segment-btn { border: none; background: transparent; color: var(--cx-text-secondary); padding: 6px 12px; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all .18s ease; } .cx-segment-btn.active { background: var(--cx-card); color: var(--cx-accent); box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12); } .cx-card-actions { display: inline-flex; align-items: center; gap: 8px; } .cx-icon-refresh-btn { border: 1px solid var(--cx-border); background: var(--cx-surface-subtle); color: var(--cx-text-secondary); border-radius: 8px; padding: 4px 7px; font-size: 12px; cursor: pointer; } .cx-icon-refresh-btn:hover { color: var(--cx-accent); border-color: var(--cx-accent); } .cx-inline-spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid var(--cx-border); border-top-color: var(--cx-accent); border-radius: 50%; animation: dashboard-skeleton-spin .75s linear infinite; } .cx-sync-times-box { margin-top: 12px; padding: 12px; border-radius: 10px; background: var(--cx-surface-subtle); border: 1px solid var(--cx-border); } .cx-sync-chips { display: flex; flex-wrap: wrap; gap: 8px; } .cx-time-chip { border: 1px solid var(--cx-border); background: var(--cx-card); color: var(--cx-text-secondary); border-radius: 8px; padding: 5px 10px; font-size: 12px; cursor: pointer; } .cx-time-chip.active { background: var(--cx-accent); color: #fff; border-color: var(--cx-accent); } .cx-sync-custom-row { display: flex; gap: 8px; margin-top: 10px; align-items: center; } .cx-sync-input { flex: 1 1 auto; min-width: 0; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--cx-border); background: var(--cx-card); color: var(--cx-text); font-size: 13px; } .cx-config-textarea { width: 100%; min-height: 220px; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--cx-border); background: var(--cx-surface-subtle); color: var(--cx-text); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; resize: vertical; } .dashboard-header, .card, .detail-view, .settings-section, .confirm-dialog, .course-ignore-onboarding, .deadline-reminder-dialog { background: var(--cx-card) !important; color: var(--cx-text) !important; border-color: var(--cx-border) !important; } .card { border-radius: 14px !important; border: 1px solid var(--cx-border); box-shadow: var(--cx-shadow) !important; } .welcome-text, .card-title, .task-title, .detail-title, .detail-item-title, .progress-item-title, .confirm-title, .course-ignore-onboarding-title { color: var(--cx-text) !important; } .date-info, .task-meta, .detail-item-meta, .progress-tasks-count, .progress-last-update, .confirm-hint, .course-ignore-onboarding-copy, .settings-section p, .settings-group-heading p { color: var(--cx-text-muted) !important; } .list-item, .detail-list-item, .progress-item, .detail-progress-item { border-bottom-color: var(--cx-divider) !important; } .list-item:hover, .detail-list-item:hover, .progress-item:hover, .detail-progress-item:hover { background: var(--cx-surface-hover) !important; } .urgent-strip { background-color: var(--cx-urgent-bg) !important; border-color: var(--cx-urgent-border) !important; color: var(--cx-urgent-text) !important; } .back-btn, .external-link-btn, .ignored-panel-btn, .select-mode-btn, .refresh-btn, .progress-delay-link, .sort-select, .progress-delay-input { background: var(--cx-surface-subtle) !important; color: var(--cx-text) !important; border-color: var(--cx-border) !important; } .progress-tooltip { background: var(--cx-card-elevated) !important; color: var(--cx-text) !important; border: 1px solid var(--cx-border) !important; } .dashboard-skeleton-page, .dashboard-skeleton-overlay { background: var(--cx-bg) !important; } .dashboard-skeleton-block, .dashboard-skeleton-card { background-color: var(--cx-skeleton-base) !important; } @media (max-width: 640px) { .cx-kpi-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); } } /* === Linear 精密桌面工作台 (v2.6.0-beta.3) === */ .main-content { max-width: 1320px !important; } .cx-tabular, .cx-kpi-card-val, .cx-time-mono, .cx-tab-count, .progress-rate, .progress-tasks-count { font-variant-numeric: tabular-nums; } .cx-topbar { display: flex; align-items: center; justify-content: space-between; gap: 14px; min-height: 54px; padding: 8px 14px; background: var(--cx-card); border: 1px solid var(--cx-border); border-radius: 12px; box-shadow: var(--cx-shadow); } .cx-topbar-left { display: flex; align-items: center; gap: 10px; min-width: 0; flex-shrink: 0; } .cx-topbar-title { display: inline-flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 600; color: var(--cx-text); white-space: nowrap; } .cx-topbar-date { font-size: 12px; color: var(--cx-text-muted); white-space: nowrap; } .cx-cmd-search { flex: 1 1 320px; max-width: 440px; min-width: 180px; display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 10px; background: var(--cx-surface-subtle); border: 1px solid var(--cx-border); border-radius: 8px; color: var(--cx-text-muted); transition: border-color .15s ease, background .15s ease; } .cx-cmd-search:focus-within { border-color: var(--cx-accent); background: var(--cx-card); } .cx-cmd-search input { flex: 1 1 auto; min-width: 0; border: 0; outline: 0; background: transparent; color: var(--cx-text); font-size: 13px; } .cx-kbd { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11px; line-height: 1; padding: 3px 6px; border-radius: 5px; border: 1px solid var(--cx-border); background: var(--cx-card); color: var(--cx-text-muted); white-space: nowrap; } .cx-topbar-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; flex-wrap: wrap; } .cx-btn-primary { display: inline-flex; align-items: center; gap: 5px; height: 32px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--cx-accent); background: var(--cx-accent); color: #fff !important; font-size: 12.5px; font-weight: 500; cursor: pointer; } .cx-btn-primary:hover { filter: brightness(1.06); } .cx-btn-amber { display: inline-flex; align-items: center; gap: 5px; height: 32px; padding: 0 10px; border-radius: 8px; border: 1px solid rgba(245, 158, 11, 0.35); background: rgba(245, 158, 11, 0.12); color: #d97706 !important; font-size: 12.5px; font-weight: 600; cursor: pointer; } .external-link-btn, .back-btn, .ignored-panel-btn, .select-mode-btn, .refresh-btn, .progress-delay-link { height: 32px; padding: 0 10px; border-radius: 8px !important; border: 1px solid var(--cx-border) !important; background: var(--cx-surface-subtle) !important; color: var(--cx-text-secondary) !important; font-size: 12.5px !important; font-weight: 500; cursor: pointer; } .external-link-btn:hover, .back-btn:hover, .ignored-panel-btn:hover, .refresh-btn:hover { border-color: var(--cx-accent) !important; color: var(--cx-text) !important; } /* 4 格独立左对齐 KPI 指标卡 */ .cx-kpi-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-top: 12px; } .cx-kpi-card { display: flex; flex-direction: column; justify-content: space-between; gap: 8px; padding: 14px 16px; background: var(--cx-card); border: 1px solid var(--cx-border); border-radius: 12px; cursor: pointer; transition: border-color .15s ease, transform .15s ease; } .cx-kpi-card:hover { border-color: var(--cx-accent); transform: translateY(-1px); } .cx-kpi-card-top { display: flex; align-items: center; justify-content: space-between; color: var(--cx-text-muted); font-size: 12.5px; font-weight: 500; } .cx-kpi-card-bottom { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; } .cx-kpi-card-val { font-size: 24px; font-weight: 700; line-height: 1.1; color: var(--cx-text); } .cx-kpi-card-val.is-blue { color: var(--cx-accent); } .cx-kpi-card-val.is-green { color: #16a34a; } .cx-kpi-card-val.is-orange { color: #d97706; } .cx-kpi-card-sub { font-size: 11.5px; color: var(--cx-text-muted); } /* 左 65% 主工作区 + 右 35% 侧边栏 */ .cx-workspace-grid { display: grid; grid-template-columns: minmax(0, 1.85fr) minmax(300px, 1fr); gap: 14px; margin-top: 14px; align-items: start; } .cx-primary-panel, .cx-side-panel { background: var(--cx-card); border: 1px solid var(--cx-border); border-radius: 12px; overflow: hidden; box-shadow: var(--cx-shadow); } .cx-panel-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--cx-border); flex-wrap: wrap; } .cx-tab-bar { display: inline-flex; align-items: center; gap: 4px; flex-wrap: wrap; } .cx-tab-btn { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border: 1px solid transparent; border-radius: 7px; background: transparent; color: var(--cx-text-muted); font-size: 13px; font-weight: 500; cursor: pointer; transition: all .14s ease; } .cx-tab-btn:hover { background: var(--cx-surface-subtle); color: var(--cx-text); } .cx-tab-btn.active { background: var(--cx-accent-soft); border-color: rgba(37, 99, 235, 0.2); color: var(--cx-accent); font-weight: 600; } .cx-tab-count { font-size: 11px; padding: 1px 6px; border-radius: 999px; background: var(--cx-surface-subtle); color: var(--cx-text-secondary); } .cx-tab-btn.active .cx-tab-count { background: var(--cx-accent); color: #fff; } .cx-subtab-bar { display: flex; align-items: center; gap: 6px; padding: 8px 14px; border-bottom: 1px solid var(--cx-divider); background: var(--cx-surface-subtle); overflow-x: auto; flex-wrap: wrap; } .cx-subtab-pill { display: inline-flex; align-items: center; gap: 5px; height: 25px; padding: 0 9px; border-radius: 999px; border: 1px solid var(--cx-border); background: var(--cx-card); color: var(--cx-text-secondary); font-size: 12px; font-weight: 500; cursor: pointer; white-space: nowrap; transition: all .14s ease; } .cx-subtab-pill:hover { border-color: var(--cx-accent); color: var(--cx-text); } .cx-subtab-pill.active { background: var(--cx-accent); border-color: var(--cx-accent); color: #fff; } .cx-type-col { width: 82px; text-align: center; flex-shrink: 0; display: inline-flex; justify-content: center; } .cx-panel-tools { display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; } .cx-panel-body { max-height: 680px; overflow-y: auto; } .cx-issue-row { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 11px 16px; border-bottom: 1px solid var(--cx-divider); cursor: pointer; transition: background .12s ease; } .cx-issue-row:last-child { border-bottom: 0; } .cx-issue-row:hover { background: var(--cx-surface-hover); } .cx-issue-left { display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1 1 auto; } .cx-status-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; } .cx-status-dot.is-blue { background: #3b82f6; } .cx-status-dot.is-amber { background: #f59e0b; } .cx-status-dot.is-red { background: #ef4444; } .cx-status-dot.is-green { background: #22c55e; } .cx-status-dot.is-muted { background: #9ca3af; } .cx-issue-title { font-size: 13.5px; font-weight: 500; color: var(--cx-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cx-issue-course { font-size: 12px; color: var(--cx-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 190px; flex-shrink: 0; } .cx-issue-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; } .cx-time-mono { font-size: 12px; color: var(--cx-text-muted); white-space: nowrap; } .cx-time-mono.urgent { color: #ef4444; font-weight: 600; } .cx-side-rail { display: flex; flex-direction: column; gap: 14px; min-width: 0; } .cx-side-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 11px 14px; border-bottom: 1px solid var(--cx-border); } .cx-side-panel-title { display: inline-flex; align-items: center; gap: 7px; font-size: 13.5px; font-weight: 600; color: var(--cx-text); } .cx-side-panel-body { padding: 8px 12px 12px; max-height: 460px; overflow-y: auto; } .cx-focus-item { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 6px; border-bottom: 1px solid var(--cx-divider); cursor: pointer; border-radius: 6px; } .cx-focus-item:last-child { border-bottom: 0; } .cx-focus-item:hover { background: var(--cx-surface-hover); } .cx-focus-title { font-size: 13px; font-weight: 500; color: var(--cx-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cx-focus-sub { font-size: 11.5px; color: var(--cx-text-muted); margin-top: 2px; } /* 统一徽章样式 */ .badge { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 6px; font-size: 11.5px; font-weight: 500; border: 1px solid transparent; white-space: nowrap; } .badge.status-normal { background: rgba(59, 130, 246, 0.1); color: #2563eb; border-color: rgba(59, 130, 246, 0.2); } .badge.status-warning { background: rgba(245, 158, 11, 0.12); color: #d97706; border-color: rgba(245, 158, 11, 0.22); } .badge.status-urgent { background: rgba(239, 68, 68, 0.1); color: #dc2626; border-color: rgba(239, 68, 68, 0.22); } .badge.status-done { background: rgba(34, 197, 94, 0.12); color: #16a34a; border-color: rgba(34, 197, 94, 0.22); } .badge.status-gray { background: var(--cx-surface-subtle); color: var(--cx-text-muted); border-color: var(--cx-border); } :root[data-cx-theme="dark"] .badge.status-normal, [data-cx-theme="dark"] .badge.status-normal { color: #93c5fd; } :root[data-cx-theme="dark"] .badge.status-warning, [data-cx-theme="dark"] .badge.status-warning { color: #fcd34d; } :root[data-cx-theme="dark"] .badge.status-urgent, [data-cx-theme="dark"] .badge.status-urgent { color: #fca5a5; } :root[data-cx-theme="dark"] .badge.status-done, [data-cx-theme="dark"] .badge.status-done { color: #86efac; } /* 文档流内临近截止提醒条(显眼且零遮挡) */ .deadline-reminder-banner.is-inflow { position: relative !important; z-index: 1 !important; top: auto !important; left: auto !important; right: auto !important; bottom: auto !important; transform: none !important; width: 100% !important; margin-top: 10px; padding: 9px 14px !important; border-radius: 10px !important; border: 1px solid rgba(245, 158, 11, 0.38) !important; border-left: 3px solid #f59e0b !important; background: rgba(245, 158, 11, 0.09) !important; color: var(--cx-text) !important; box-shadow: none !important; } :root[data-cx-theme="dark"] .deadline-reminder-banner.is-inflow, [data-cx-theme="dark"] .deadline-reminder-banner.is-inflow { background: rgba(245, 158, 11, 0.14) !important; } .deadline-reminder-banner-icon { color: #d97706 !important; display: inline-flex; align-items: center; } .deadline-reminder-banner-button { background: #d97706 !important; color: #fff !important; border-radius: 7px !important; padding: 5px 11px !important; font-size: 12px !important; font-weight: 600 !important; } .deadline-reminder-banner-close { color: var(--cx-text-muted) !important; display: inline-flex !important; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 6px; } .deadline-reminder-banner-close:hover { background: var(--cx-surface-hover); color: var(--cx-text) !important; } /* 统一全部弹窗 / 悬浮窗 / 详情页 / 引导条 */ .confirm-overlay { z-index: 12000 !important; background: rgba(11, 13, 18, 0.56) !important; backdrop-filter: blur(4px) !important; } .deadline-reminder-overlay { z-index: 13000 !important; background: rgba(11, 13, 18, 0.56) !important; backdrop-filter: blur(4px) !important; } .confirm-dialog, .course-ignore-dialog, .other-tasks-dialog, .bulk-ignore-dialog, .deadline-reminder-dialog { background: var(--cx-card) !important; color: var(--cx-text) !important; border: 1px solid var(--cx-border) !important; border-radius: 14px !important; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.28) !important; } .confirm-dialog { display: flex !important; flex-direction: column !important; max-height: min(84vh, 660px) !important; padding: 20px 22px !important; } .course-ignore-list { max-height: min(44vh, 340px) !important; overflow-y: auto !important; padding-right: 4px; margin-bottom: 0 !important; } .confirm-actions { margin-top: 14px !important; padding-top: 14px !important; border-top: 1px solid var(--cx-border); display: flex !important; justify-content: flex-end !important; align-items: center !important; gap: 10px !important; flex-shrink: 0; } .cx-qa-list { display: flex; flex-direction: column; } .cx-qa-item { padding: 14px 16px; border-bottom: 1px solid var(--cx-divider); } .cx-qa-item:last-child { border-bottom: 0; } .cx-qa-q { font-size: 13.5px; font-weight: 600; color: var(--cx-text); } .cx-qa-a { font-size: 12.5px; color: var(--cx-text-muted); margin-top: 5px; line-height: 1.55; } /* 聚光灯新手引导 */ .cx-tour-backdrop { position: fixed; inset: 0; z-index: 14000; background: rgba(11, 13, 18, 0.56); pointer-events: auto; } .cx-tour-spotlight { position: fixed; z-index: 14001; border-radius: 12px; border: 2px solid var(--cx-accent); box-shadow: 0 0 0 9999px rgba(11, 13, 18, 0.56), 0 0 0 4px rgba(37, 99, 235, 0.28); pointer-events: none; transition: all .22s ease; } .cx-tour-card { position: fixed; z-index: 14002; width: min(360px, calc(100vw - 24px)); padding: 16px 18px; background: var(--cx-card); color: var(--cx-text); border: 1px solid var(--cx-border); border-radius: 14px; box-shadow: 0 22px 60px rgba(0, 0, 0, 0.34); } .cx-tour-step-badge { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: 999px; background: var(--cx-accent-soft); color: var(--cx-accent); font-size: 11px; font-weight: 600; } .cx-tour-title { font-size: 15px; font-weight: 600; margin-top: 8px; color: var(--cx-text); } .cx-tour-desc { font-size: 13px; color: var(--cx-text-muted); margin-top: 6px; line-height: 1.55; } .cx-tour-footer { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--cx-divider); } .deadline-reminder-dialog-header, .deadline-reminder-dialog-footer { border-color: var(--cx-border) !important; background: var(--cx-card) !important; } .deadline-reminder-dialog-header h2, .confirm-title { color: var(--cx-text) !important; } .deadline-reminder-dialog-header p, .deadline-reminder-dialog-footer span, .confirm-hint { color: var(--cx-text-muted) !important; } .deadline-reminder-item, .confirm-list-item, .course-ignore-option, .other-task-all-option, .bulk-ignore-preview, .bulk-ignore-preview-item, .reminder-diagnostic-item { background: var(--cx-surface-subtle) !important; border: 1px solid var(--cx-border) !important; color: var(--cx-text) !important; border-radius: 9px !important; } .deadline-reminder-item-title, .bulk-ignore-preview-name, .reminder-diagnostic-heading strong { color: var(--cx-text) !important; } .deadline-reminder-item-course, .bulk-ignore-preview-course, .reminder-diagnostic-meta, .reminder-diagnostic-reason { color: var(--cx-text-muted) !important; } .confirm-ok-btn, .deadline-reminder-ack-button { background: var(--cx-accent) !important; color: #fff !important; border: 1px solid var(--cx-accent) !important; border-radius: 8px !important; font-weight: 500 !important; } .confirm-cancel-btn, .deadline-reminder-mute-button { background: var(--cx-surface-subtle) !important; color: var(--cx-text-secondary) !important; border: 1px solid var(--cx-border) !important; border-radius: 8px !important; } .deadline-reminder-go-button { background: #d97706 !important; color: #fff !important; border-radius: 8px !important; } .progress-tooltip, .progress-tooltip-portal, .cx-progress-popover { background: var(--cx-card-elevated) !important; color: var(--cx-text) !important; border: 1px solid var(--cx-border) !important; border-radius: 12px !important; box-shadow: 0 16px 40px rgba(0, 0, 0, 0.24) !important; } .progress-tooltip .tooltip-title, .progress-tooltip-portal .tooltip-title, .cx-progress-popover .tooltip-title, .progress-tooltip .tooltip-row .value, .progress-tooltip-portal .tooltip-row .value, .cx-progress-popover .tooltip-row .value, .progress-tooltip .tooltip-activities-title, .progress-tooltip-portal .tooltip-activities-title, .cx-progress-popover .tooltip-activities-title, .progress-tooltip .activity-group-title, .progress-tooltip-portal .activity-group-title, .cx-progress-popover .activity-group-title, .progress-tooltip .activity-name, .progress-tooltip-portal .activity-name, .cx-progress-popover .activity-name { color: var(--cx-text) !important; } .progress-tooltip .tooltip-title, .progress-tooltip-portal .tooltip-title, .cx-progress-popover .tooltip-title, .progress-tooltip .tooltip-row, .progress-tooltip-portal .tooltip-row, .cx-progress-popover .tooltip-row, .progress-tooltip .tooltip-activities-section, .progress-tooltip-portal .tooltip-activities-section, .cx-progress-popover .tooltip-activities-section { border-color: var(--cx-divider) !important; } .progress-tooltip .tooltip-row .label, .progress-tooltip-portal .tooltip-row .label, .cx-progress-popover .tooltip-row .label, .progress-tooltip .tooltip-loading, .progress-tooltip-portal .tooltip-loading, .cx-progress-popover .tooltip-loading, .progress-tooltip .tooltip-no-activities, .progress-tooltip-portal .tooltip-no-activities, .cx-progress-popover .tooltip-no-activities { color: var(--cx-text-muted) !important; } .progress-tooltip .activity-item, .progress-tooltip-portal .activity-item, .cx-progress-popover .activity-item { background: var(--cx-surface-subtle) !important; border: 1px solid var(--cx-divider) !important; color: var(--cx-text) !important; } .detail-list-item.is-checked-accent { background: var(--cx-accent-soft) !important; border-color: var(--cx-accent) !important; } .detail-list-item.is-checked-danger { background: var(--cx-urgent-bg) !important; border-color: var(--cx-urgent-border) !important; } .cx-inline-banner { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin: 10px 14px; padding: 10px 12px; border-radius: 8px; font-size: 13px; } .cx-inline-banner.is-warn { border: 1px solid rgba(245, 158, 11, 0.35); background: rgba(245, 158, 11, 0.12); color: #b45309; } :root[data-cx-theme="dark"] .cx-inline-banner.is-warn, [data-cx-theme="dark"] .cx-inline-banner.is-warn { color: #fcd34d; } .cx-inline-banner.is-error { border: 1px solid var(--cx-urgent-border); background: var(--cx-urgent-bg); color: var(--cx-urgent-text); } .settings-onboarding, .course-ignore-onboarding { background: var(--cx-card) !important; color: var(--cx-text) !important; border: 1px solid var(--cx-border) !important; border-radius: 12px !important; box-shadow: var(--cx-shadow) !important; } .settings-toast { background: var(--cx-card-elevated) !important; color: var(--cx-text) !important; border: 1px solid var(--cx-border) !important; border-radius: 10px !important; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.2) !important; } .detail-view { background: var(--cx-card) !important; border: 1px solid var(--cx-border) !important; border-radius: 12px !important; box-shadow: var(--cx-shadow) !important; margin-top: 10px; } .detail-header, .detail-toolbar { border-color: var(--cx-border) !important; background: var(--cx-card) !important; } .view-btn { background: var(--cx-accent-soft) !important; color: var(--cx-accent) !important; border: 1px solid rgba(37, 99, 235, 0.22) !important; border-radius: 7px !important; } .batch-bar { background: var(--cx-card-elevated) !important; color: var(--cx-text) !important; border: 1px solid var(--cx-border) !important; } /* 设置页面 Linear 双栏 */ .cx-settings-page { display: flex; flex-direction: column; gap: 14px; } .cx-settings-shell { display: grid; grid-template-columns: 208px minmax(0, 1fr); gap: 16px; align-items: start; } .cx-settings-nav { display: flex; flex-direction: column; gap: 4px; padding: 8px; background: var(--cx-card); border: 1px solid var(--cx-border); border-radius: 12px; position: sticky; top: 16px; } .cx-settings-nav-item { display: flex; align-items: center; gap: 8px; padding: 9px 12px; border: 0; border-radius: 8px; background: transparent; color: var(--cx-text-secondary); font-size: 13.5px; font-weight: 500; text-align: left; cursor: pointer; } .cx-settings-nav-item:hover { background: var(--cx-surface-subtle); color: var(--cx-text); } .cx-settings-nav-item.active { background: var(--cx-accent-soft); color: var(--cx-accent); font-weight: 600; } .cx-settings-section-head { margin-bottom: 10px; } .cx-settings-section-head h3 { margin: 0; font-size: 15px; font-weight: 600; color: var(--cx-text); } .cx-settings-section-head p { margin: 4px 0 0; font-size: 12.5px; color: var(--cx-text-muted); } .cx-settings-card { background: var(--cx-card); border: 1px solid var(--cx-border); border-radius: 12px; overflow: hidden; } .cx-setting-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 16px; border-bottom: 1px solid var(--cx-divider); } .cx-setting-row:last-child { border-bottom: 0; } .cx-setting-meta { min-width: 0; flex: 1 1 auto; } .cx-setting-title { font-size: 13.5px; font-weight: 500; color: var(--cx-text); } .cx-setting-desc { font-size: 12px; color: var(--cx-text-muted); margin-top: 3px; line-height: 1.45; } .cx-setting-control { flex-shrink: 0; } .cx-switch-only { padding: 0 !important; margin: 0 !important; } .cx-progress-side-list { display: flex; flex-direction: column; gap: 6px; } .cx-progress-side-list .progress-item { padding: 8px 6px; border-radius: 8px; border-bottom: 1px solid var(--cx-divider); } .cx-progress-side-list .progress-item:last-child { border-bottom: 0; } .cx-progress-compact-list { display: flex; flex-direction: column; } .cx-progress-compact-row { padding: 9px 6px; border-bottom: 1px solid var(--cx-divider); border-radius: 6px; cursor: pointer; transition: background .12s ease; } .cx-progress-compact-row:last-child { border-bottom: 0; } .cx-progress-compact-row:hover { background: var(--cx-surface-hover); } .cx-progress-row-top { display: flex; align-items: center; justify-content: space-between; gap: 10px; } .cx-progress-row-name { font-size: 13px; font-weight: 500; color: var(--cx-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1 1 auto; } .cx-progress-row-stat { display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; font-size: 12px; color: var(--cx-text-muted); font-variant-numeric: tabular-nums; } .cx-progress-row-pct { font-weight: 600; } .cx-progress-row-pct.complete { color: #16a34a; } .cx-progress-row-pct.warning { color: var(--cx-accent); } .cx-progress-row-pct.normal { color: #3b82f6; } .cx-progress-row-pct.danger { color: #d97706; } .cx-progress-row-pct.empty { color: var(--cx-text-muted); font-weight: 500; } .progress-bar { height: 4px !important; border-radius: 999px !important; background: var(--cx-surface-subtle) !important; } .progress-bar-fill { border-radius: 999px !important; } .progress-bar-fill.complete { background: #16a34a !important; } .progress-bar-fill.warning { background: var(--cx-accent) !important; } .progress-bar-fill.normal { background: #3b82f6 !important; } .progress-bar-fill.danger { background: #f59e0b !important; } .progress-bar-fill.empty { background: var(--cx-border) !important; } .progress-rate.complete { color: #16a34a !important; } .progress-rate.warning { color: var(--cx-accent) !important; } .progress-rate.normal { color: #3b82f6 !important; } .progress-rate.danger { color: #d97706 !important; } .progress-rate.empty { color: var(--cx-text-muted) !important; font-weight: 500 !important; font-size: 12px !important; } .cx-progress-detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } .cx-progress-detail-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 14px; background: var(--cx-card); border: 1px solid var(--cx-border); border-radius: 10px; cursor: pointer; transition: border-color .14s ease, background .14s ease; } .cx-progress-detail-row:hover { border-color: var(--cx-accent); background: var(--cx-surface-hover); } .cx-progress-popover { position: fixed; z-index: 11500; width: 316px; max-height: 400px; overflow-y: auto; padding: 14px; background: var(--cx-card-elevated); color: var(--cx-text); border: 1px solid var(--cx-border); border-radius: 12px; box-shadow: 0 18px 44px rgba(0, 0, 0, 0.24); pointer-events: none; } .cx-load-more-bar { display: flex; align-items: center; justify-content: center; padding: 12px 16px; border-top: 1px solid var(--cx-divider); } @media (max-width: 820px) { .cx-progress-detail-grid { grid-template-columns: minmax(0, 1fr); } } @media (max-width: 980px) { .cx-workspace-grid { grid-template-columns: minmax(0, 1fr); } .cx-kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .cx-settings-shell { grid-template-columns: minmax(0, 1fr); } .cx-settings-nav { flex-direction: row; overflow-x: auto; position: static; } .cx-settings-nav-item { white-space: nowrap; } } @media (max-width: 640px) { .cx-topbar { flex-wrap: wrap; } .cx-cmd-search { order: 3; max-width: 100%; flex-basis: 100%; } .cx-issue-course { display: none; } } `; // 注入样式 if (!document.querySelector('#dashboard-style-v2')) { const styleEl = document.createElement('style'); styleEl.id = 'dashboard-style-v2'; styleEl.textContent = dashboardStyle; document.head.appendChild(styleEl); } // 获取状态类名 const getStatusClass = (item) => { if (item.isUrgent) return 'status-urgent'; if (item.uncommitted || item.ongoing) return 'status-warning'; if (item.finished) return 'status-done'; return 'status-normal'; }; // 获取视图标题 const getViewTitle = (type) => { switch (type) { case 'todo': return '待办任务'; case 'homework': return '全部作业'; case 'exam': return '全部考试'; case 'activities': return '课程任务'; case 'progress': return '课程进度'; default: return ''; } }; // 获取视图数据(已过滤忽略项) const getViewItems = (type) => { switch (type) { case 'todo': return filteredTodoItems.value; case 'homework': return filteredHomeworkItems.value; case 'exam': return filteredExamItems.value; case 'activities': return filteredActivitiesItems.value; case 'progress': return filteredCourseProgressItems.value; default: return []; } }; // 获取视图原始数据(未过滤,用于统计) const getRawViewItems = (type) => { switch (type) { case 'todo': return todoItems.value; case 'homework': return [...homeworkItems.value, ...activitiesItems.value.filter(isRoutedToHomework)]; case 'exam': return [...examItems.value, ...activitiesItems.value.filter(isRoutedToExam)]; case 'activities': return activitiesItems.value .filter(item => !isRoutedToHomework(item) && !isRoutedToExam(item)); case 'progress': return courseProgressItems.value; default: return []; } }; // 获取视图加载状态 const getViewLoading = (type) => { switch (type) { case 'todo': return loading.value.todo; case 'homework': return loading.value.homework; case 'exam': return loading.value.exam; case 'activities': return loading.value.activities; case 'progress': return loadingProgress.value; default: return false; } }; // 获取项目链接 const getItemLink = (type, item) => { switch (type) { case 'todo': return getTodoLink(item); case 'homework': return getHomeworkLink(item); case 'exam': return getExamLink(item); case 'activities': return getActivityLink(item); case 'progress': return item.studyDataUrl || '#'; default: return '#'; } }; // 获取列表项状态显示 const getItemStatus = (type, item) => { switch (type) { case 'todo': return item.info || item.leftTime || item.type || '待办'; case 'homework': return getHomeworkStatus(item); case 'exam': return item.finished ? '已完成' : (item.expired ? '已过期' : (item.timeLeft || '进行中')); case 'activities': return item.status || (item.finished ? '已完成' : '进行中'); case 'progress': return item.isComplete ? '已完成' : (parseInt(item.completionRate) >= 100 ? '已完成' : '进行中'); default: return ''; } }; // 获取状态 badge 类名 const getItemBadgeClass = (type, item) => { switch (type) { case 'todo': return item.isActivity ? 'status-warning' : (item.type === '作业' ? 'status-normal' : 'status-urgent'); case 'homework': return getHomeworkBadgeClass(item); case 'exam': return item.finished ? 'status-done' : (item.expired ? 'status-gray' : 'status-urgent'); case 'activities': return item.finished ? 'status-done' : (item.ongoing ? 'status-warning' : 'status-normal'); case 'progress': return item.isComplete || parseInt(item.completionRate) >= 100 ? 'status-done' : 'status-normal'; default: return 'status-normal'; } }; // 渲染详情页视图 const renderDetailView = (type) => { const viewItems = getViewItems(type); const getItemDoneState = (item) => { if (type === 'homework') return item.isActivity ? (item.finished || item.status === '已完成') : item.uncommitted === false; if (type === 'exam') return Boolean(item.finished || item.expired); if (type === 'activities') return Boolean(item.finished || item.status === '已结束' || (!item.ongoing && item.expired)); return false; }; const segmentOptions = type === 'homework' ? [ { key: 'all', label: `全部 ${viewItems.length}` }, { key: 'pending', label: `待提交 ${viewItems.filter(i => !getItemDoneState(i)).length}` }, { key: 'done', label: `已提交 ${viewItems.filter(i => getItemDoneState(i)).length}` } ] : type === 'exam' ? [ { key: 'all', label: `全部 ${viewItems.length}` }, { key: 'pending', label: `待考 ${viewItems.filter(i => !getItemDoneState(i)).length}` }, { key: 'done', label: `已结束 ${viewItems.filter(i => getItemDoneState(i)).length}` } ] : type === 'activities' ? [ { key: 'all', label: `全部 ${viewItems.length}` }, { key: 'pending', label: `进行中 ${viewItems.filter(i => !getItemDoneState(i)).length}` }, { key: 'done', label: `已结束 ${viewItems.filter(i => getItemDoneState(i)).length}` } ] : []; const activeSeg = segmentOptions.some(o => o.key === detailSegment.value) ? detailSegment.value : 'all'; const segmentedViewItems = activeSeg === 'all' ? viewItems : viewItems.filter(i => activeSeg === 'pending' ? !getItemDoneState(i) : getItemDoneState(i)); const progressFilteredViewItems = type === 'progress' ? (() => { const seg = progressDetailSegment.value || 'ongoing'; if (seg === 'ongoing') return viewItems.filter(isOngoingProgressCourse); if (seg === 'completed') return viewItems.filter(isCompletedProgressCourse); if (seg === 'empty') return viewItems.filter(isZeroTaskCourse); return viewItems; })() : segmentedViewItems; const sortedItems = sortItems(progressFilteredViewItems, type, currentSort.value); const isLoading = getViewLoading(type) && !(type === 'activities' && activitiesFromCache.value) && !(type === 'progress' && progressFromCache.value); const title = getViewTitle(type); const dotColors = { todo: '#1890ff', homework: '#faad14', exam: '#f5222d', activities: '#52c41a', progress: '#722ed1' }; // 使用 getIgnoredItemsBySection 精确按板块过滤 const allIgnored = getIgnoredItemsBySection(type); const ignoredCountNow = allIgnored.length; const renderProgressDetailActions = () => vue.createVNode("div", { class: "progress-detail-actions" }, [ progressLastUpdate.value ? vue.createVNode("span", { class: "progress-last-update" }, `更新于 ${progressLastUpdate.value}`) : null, vue.createVNode("button", { class: "ignored-panel-btn", onClick: () => { showIgnoredPanel.value = true; selectedForRestore.value = new Set(); } }, [cxIcon("ban", 13), `已忽略(${ignoredCountNow})`]), settings.value.ignoreEnabled ? vue.createVNode("button", { class: `select-mode-btn ${selectMode.value ? 'active' : ''}`, onClick: toggleSelectMode }, selectMode.value ? [cxIcon("x", 13), "退出多选"] : "多选") : null, vue.createVNode("button", { class: isProgressEnabled() ? "refresh-btn" : "refresh-btn disabled", onClick: () => { const newState = !isProgressEnabled(); setProgressEnabled(newState); if (newState) { progressLoaded.value = courseProgressItems.value.length > 0; loadAllCourseProgress(); } } }, !isProgressEnabled() ? [cxIcon("xCircle", 13), "查询已关闭"] : loadingProgress.value ? [cxIcon("refreshCw", 13), "查询中"] : progressLoaded.value ? [cxIcon("check", 13), "已查询"] : [cxIcon("search", 13), "待查询"]), vue.createVNode("button", { class: "progress-delay-link", title: "在统一设置中修改课程进度请求间隔", onClick: openSettings }, [cxIcon("clock", 13), `${progressDelay.value}ms`]), vue.createVNode("button", { class: "external-link-btn", title: "排查并一键隐藏 0 任务点课程", onClick: () => triggerZeroTaskSuggestIfNeeded(true) }, [cxIcon("shield", 13), "清理 0 任务点"]), vue.createVNode("button", { class: "refresh-btn", onClick: () => loadAllCourseProgress() }, [cxIcon("refreshCw", 13), loadingProgress.value ? "刷新中..." : "刷新"]) ]); // 渲染已忽略面板内容 if (showIgnoredPanel.value) { return vue.createVNode("div", { class: "detail-view" }, [ vue.createVNode("div", { class: "detail-header" }, [ vue.createVNode("div", { class: "detail-header-left" }, [ vue.createVNode("button", { class: "back-btn", onClick: () => { showIgnoredPanel.value = false; selectedForRestore.value = new Set(); } }, ["← 返回列表"]), vue.createVNode("div", { class: "detail-title" }, [ [cxIcon("ban", 15), "已忽略内容"], vue.createVNode("span", { class: "detail-count" }, `共 ${allIgnored.length} 项`) ]) ]), selectedForRestore.value.size > 0 ? vue.createVNode("button", { class: "batch-restore-btn", onClick: batchRestore }, `恢复所选(${selectedForRestore.value.size})`) : null ]), vue.createVNode("div", { class: "detail-body" }, [ allIgnored.length === 0 ? vue.createVNode("div", { class: "empty-state" }, "暂无已忽略内容") : allIgnored.map(ig => { const isChecked = selectedForRestore.value.has(ig._key); return vue.createVNode("div", { class: `detail-list-item ${isChecked ? 'is-checked-accent' : ''}` }, [ vue.createVNode("div", { class: `select-checkbox ${isChecked ? 'checked' : ''}`, onClick: (e) => { e.stopPropagation(); toggleRestoreItem(ig._key); } }, isChecked ? cxIcon("check", 12) : ""), vue.createVNode("div", { class: "detail-item-main" }, [ vue.createVNode("div", { class: "detail-item-title" }, ig.title), vue.createVNode("div", { class: "detail-item-meta" }, [ ig.course ? vue.createVNode("span", {}, ig.course) : null, ig.type ? vue.createVNode("span", { class: "course-tag", style: "margin-left:6px;" }, ig.type) : null, vue.createVNode("span", { class: "ignored-date", style: "margin-left:8px;" }, `忽略于:${new Date(ig.ignoredAt).toLocaleDateString()}`) ]) ]), vue.createVNode("button", { class: "restore-single-btn", onClick: (e) => { e.stopPropagation(); restoreSingle(ig._key); } }, "撤销忽略") ]); }) ]) ]); } // 渲染正常详情页 return vue.createVNode("div", { class: "detail-view" }, [ // 详情页头部 vue.createVNode("div", { class: `detail-header ${type === 'progress' ? 'progress-detail-header' : ''}` }, [ vue.createVNode("div", { class: "detail-header-left" }, [ vue.createVNode("button", { class: "back-btn", onClick: backToDashboard }, ["← 返回仪表盘"]), vue.createVNode("div", { class: "detail-title" }, [ vue.createVNode("span", { class: "indicator-dot", style: `background: ${dotColors[type]};` }), title, ((type === 'activities' && activitiesFromCache.value) || (type === 'progress' && progressFromCache.value)) ? vue.createVNode("span", { class: "cache-source-note" }, "缓存内容 · 正在更新") : null, vue.createVNode("span", { class: "detail-count" }, `共 ${viewItems.length} 项`) ]) ]), type === 'progress' ? renderProgressDetailActions() : vue.createVNode("div", { style: "display:flex;gap:8px;align-items:center;" }, [ // 已忽略按钮 settings.value.ignoreEnabled ? vue.createVNode("button", { class: "ignored-panel-btn", onClick: () => { showIgnoredPanel.value = true; selectedForRestore.value = new Set(); } }, [cxIcon("ban", 13), `已忽略(${ignoredCountNow})`]) : null, // 多选按钮 settings.value.ignoreEnabled ? vue.createVNode("button", { class: `select-mode-btn ${selectMode.value ? 'active' : ''}`, onClick: toggleSelectMode }, selectMode.value ? [cxIcon("x", 13), "退出多选"] : "多选") : null, // 仅作业、考试存在对应原始聚合页;待办、课程任务和课程进度不显示无效入口。 (type === 'homework' || type === 'exam') ? vue.createVNode("button", { class: "external-link-btn", onClick: () => navigateToOriginal(type) }, "在原始页面打开") : null ]) ]), // 工具栏:搜索、分段筛选与排序选择器 vue.createVNode("div", { class: "detail-toolbar", style: "flex-wrap:wrap;gap:10px;" }, [ vue.createVNode("div", { style: "display:flex;align-items:center;gap:10px;flex-wrap:wrap;" }, [ vue.createVNode("div", { class: "sort-container" }, [ vue.createVNode("span", { class: "sort-label" }, "排序方式:"), vue.createVNode("select", { class: "sort-select", value: currentSort.value, onChange: (e) => { currentSort.value = e.target.value; } }, sortOptions.map(opt => vue.createVNode("option", { value: opt.value }, opt.label) )) ]), type === 'progress' ? vue.createVNode("div", { class: "cx-segmented-control" }, [ { key: 'ongoing', label: `进行中 ${viewItems.filter(isOngoingProgressCourse).length}` }, { key: 'completed', label: `已完成 ${viewItems.filter(isCompletedProgressCourse).length}` }, { key: 'empty', label: `无任务点 ${viewItems.filter(isZeroTaskCourse).length}` }, { key: 'all', label: `全部 ${viewItems.length}` } ].map(opt => vue.createVNode("button", { type: "button", class: `cx-segment-btn ${(progressDetailSegment.value || 'ongoing') === opt.key ? 'active' : ''}`, onClick: () => { progressDetailSegment.value = opt.key; } }, opt.label))) : (segmentOptions.length > 0 ? vue.createVNode("div", { class: "cx-segmented-control" }, segmentOptions.map(opt => vue.createVNode("button", { type: "button", class: `cx-segment-btn ${activeSeg === opt.key ? 'active' : ''}`, onClick: () => { detailSegment.value = opt.key; window.scrollTo({ top: 0, behavior: 'smooth' }); } }, opt.label)) ) : null), vue.createVNode("div", { class: "cx-global-search-bar", style: "margin-top:0;padding:4px 10px;min-width:200px;" }, [ cxIcon("search", 14), vue.createVNode("input", { type: "text", class: "cx-global-search-input", style: "font-size:13px;", placeholder: `搜索${title}或课程...`, value: searchQuery.value, onInput: e => { searchQuery.value = e.target.value; } }), searchQuery.value ? vue.createVNode("button", { type: "button", class: "cx-global-search-clear", onClick: () => { searchQuery.value = ''; } }, "×") : null ]) ]), vue.createVNode("div", { style: "font-size: 13px; color: var(--cx-text-muted);" }, type === 'progress' ? `已完成: ${viewItems.filter(i => parseInt(i.completionRate) >= 100).length} / ${viewItems.length} 门课程` : `未完成: ${viewItems.filter(i => !i.finished && (i.uncommitted !== false)).length} 项` ) ]), // 详情页内容 vue.createVNode("div", { class: `detail-body ${type === 'progress' ? 'progress-detail-body' : ''}` }, [ isLoading ? renderLoadingSkeleton(`正在加载${title}…`) : sortedItems.length === 0 ? vue.createVNode("div", { class: "empty-state" }, "暂无数据") : type === 'progress' // 课程进度 Linear 双列精密行布局(移除内联悬浮窗,改用全局按需 Popover) ? vue.createVNode("div", { class: "cx-progress-detail-grid" }, sortedItems.map(item => { const itemKey = getItemKey(item, 'progress'); const isChecked = selectMode.value && selectedForIgnore.value.has(itemKey); const isEmpty = isZeroTaskCourse(item); const rate = parseInt(item.completionRate) || 0; const rateClass = isEmpty ? 'empty' : (rate >= 100 ? 'complete' : (rate >= 60 ? 'warning' : (rate >= 30 ? 'normal' : 'danger'))); return vue.createVNode("div", { class: `cx-progress-detail-row ${isChecked ? 'is-checked-danger' : ''}`, onMouseenter: (e) => handleProgressItemHover(e, item), onMouseleave: handleProgressItemLeave, onClick: () => { if (selectMode.value) { toggleSelectItem(item, 'progress'); } else if (item.studyDataUrl) { window.open(item.studyDataUrl, '_blank'); } } }, [ selectMode.value ? vue.createVNode("div", { class: `select-checkbox ${isChecked ? 'checked' : ''}`, onClick: (e) => { e.stopPropagation(); toggleSelectItem(item, 'progress'); } }, isChecked ? cxIcon("check", 12) : "") : null, vue.createVNode("div", { class: "progress-item-main" }, [ vue.createVNode("div", { class: "progress-item-title" }, item.courseName), vue.createVNode("div", { class: "progress-bar" }, [ vue.createVNode("div", { class: `progress-bar-fill ${rateClass}`, style: `width: ${isEmpty ? 0 : Math.min(rate, 100)}%;` }) ]) ]), vue.createVNode("div", { class: "progress-item-info" }, [ vue.createVNode("span", { class: `progress-rate ${rateClass}` }, isEmpty ? '无任务点' : item.completionRate), vue.createVNode("div", { class: "progress-tasks-count" }, `${item.completedTasks}/${item.totalTasks}`), settings.value.ignoreEnabled && !selectMode.value ? vue.createVNode("button", { class: "ignore-btn", onClick: (e) => { e.stopPropagation(); requestIgnore(item, 'progress'); } }, [cxIcon("ban", 13)]) : null ]) ]); }) ) : sortedItems.map(item => { const itemKey = getItemKey(item, type); const isChecked = selectMode.value && selectedForIgnore.value.has(itemKey); return vue.createVNode("div", { class: `detail-list-item ${isChecked ? 'is-checked-danger' : ''}` }, [ // 多选复选框 selectMode.value ? vue.createVNode("div", { class: `select-checkbox ${isChecked ? 'checked' : ''}`, onClick: (e) => { e.stopPropagation(); toggleSelectItem(item, type); } }, isChecked ? cxIcon("check", 12) : "") : null, vue.createVNode("div", { class: "detail-item-main" }, [ vue.createVNode("div", { class: "detail-item-title" }, item.title), vue.createVNode("div", { class: "detail-item-meta" }, [ vue.createVNode("span", {}, item.course || item.courseName || ''), type === 'activities' ? vue.createVNode("span", {}, `· ${item.type || '活动'}`) : null ]) ]), vue.createVNode("div", { class: "item-time-status" }, [ // 详情页仅保留设计后的状态标签,避免重复显示浅灰状态/时间文本。 vue.createVNode("div", { class: "status-info" }, [ vue.createVNode("span", { class: `badge ${getItemBadgeClass(type, item)}` }, getItemStatus(type, item)) ]), // 查看按钮 resolvingTaskKey.value === getResolvingKey(item, type) ? vue.createVNode("span", { class: "cx-inline-spinner", title: "正在解析直达链接…" }) : vue.createVNode("button", { class: "view-btn", onClick: (e) => { e.stopPropagation(); openTaskLink(item, type); } }, "查看"), // 忽略按钮(非多选模式下才显示) settings.value.ignoreEnabled && !selectMode.value ? vue.createVNode("button", { class: "ignore-btn", onClick: (e) => { e.stopPropagation(); requestIgnore(item, type); } }, [cxIcon("ban", 13), "忽略"]) : null ]) ]); }), // 多选批量操作栏 selectMode.value && selectedForIgnore.value.size > 0 ? vue.createVNode("div", { class: "batch-bar" }, [ vue.createVNode("span", {}, `已选 ${selectedForIgnore.value.size} 项`), vue.createVNode("button", { class: "batch-ignore-btn", onClick: () => { ignoreConfirmSection.value = type; batchIgnoreSelected(); } }, `忽略所选(${selectedForIgnore.value.size})`) ]) : null ]) ]); }; // 根据当前视图渲染 // 确认弹窗渲染函数 const renderConfirmDialog = () => { if (!showIgnoreConfirm.value) return null; return vue.createVNode("div", { class: "confirm-overlay", onClick: cancelIgnore }, [ vue.createVNode("div", { class: "confirm-dialog", onClick: (e) => e.stopPropagation() }, [ vue.createVNode("div", { class: "confirm-title" }, [cxIcon("alertTriangle", 16), "确认忽略"]), vue.createVNode("div", { class: "confirm-list" }, ignoreConfirmItems.value.map(it => vue.createVNode("div", { class: "confirm-list-item" }, it.title || it.courseName || "未知项目") ) ), vue.createVNode("div", { class: "confirm-hint" }, "忽略后这些项目将不再显示在列表中,但可在\u300C查看全部 \u2192 已忽略\u300D中找回并撤销。" ), vue.createVNode("div", { class: "confirm-actions" }, [ vue.createVNode("button", { class: "confirm-cancel-btn", onClick: cancelIgnore }, "取消"), vue.createVNode("button", { class: "confirm-ok-btn", onClick: confirmIgnore }, "确认忽略") ]) ]) ]); }; const renderProgressPopover = () => { const course = hoveredProgressCourse.value; const rect = hoveredProgressRect.value; if (!course || !rect) return null; const cacheKey = getCourseActivitiesKey(course); const cachedData = courseActivitiesCache.value[cacheKey]; const activitiesLoading = cachedData?.loading || false; const activities = cachedData?.activities || []; const isEmpty = isZeroTaskCourse(course); const rate = parseInt(course.completionRate) || 0; const validRows = [ { label: '完成进度', val: isEmpty ? '无任务点' : course.completionRate, cls: rate >= 100 ? 'success' : (rate >= 60 ? 'warning' : '') }, { label: '课程积分', val: course.courseScore }, { label: '章节测验', val: course.chapterQuiz }, { label: '当前排名', val: course.ranking }, { label: 'AI实践', val: course.aiPractice }, { label: '分组任务', val: course.groupTask } ].filter(r => r.val && r.val !== '--'); const popWidth = 316; const popHeight = 360; const winW = window.innerWidth || 1280; const winH = window.innerHeight || 800; const openLeft = rect.left > winW / 2; const left = openLeft ? Math.max(12, rect.left - popWidth - 10) : Math.min(winW - popWidth - 12, rect.right + 10); const top = Math.max(12, Math.min(rect.top, winH - popHeight - 12)); const groups = [ { title: '课程作业', icon: 'fileText', items: activities.filter(a => a.type?.includes('作业')) }, { title: '在线考试', icon: 'clipboardList', items: activities.filter(a => a.type?.includes('考试')) }, { title: '章节测验', icon: 'book', items: activities.filter(a => a.type?.includes('测验') || a.type?.includes('练习')) }, { title: '互动讨论', icon: 'messageSquare', items: activities.filter(a => a.type?.includes('讨论') || a.type?.includes('抢答') || a.type?.includes('评分')) } ].filter(g => g.items.length > 0); return vue.createVNode('div', { class: 'cx-progress-popover', style: `left:${left}px;top:${top}px;` }, [ vue.createVNode('div', { class: 'tooltip-title', style: 'margin-bottom:8px;font-weight:600;font-size:13.5px;' }, course.courseName), ...validRows.map(r => vue.createVNode('div', { class: 'tooltip-row' }, [ vue.createVNode('span', { class: 'label' }, r.label), vue.createVNode('span', { class: `value cx-tabular ${r.cls || ''}` }, r.val) ])), vue.createVNode('div', { class: 'tooltip-activities-section', style: 'margin-top:8px;padding-top:8px;border-top:1px solid var(--cx-divider);' }, [ vue.createVNode('div', { class: 'tooltip-activities-title', style: 'font-size:12px;font-weight:600;margin-bottom:6px;' }, [cxIcon('bookOpen', 13), '学习活动']), activitiesLoading ? vue.createVNode('div', { class: 'tooltip-loading' }, '正在加载活动...') : groups.length === 0 ? vue.createVNode('div', { class: 'tooltip-no-activities' }, '暂无学习活动') : groups.map(g => vue.createVNode('div', { class: 'tooltip-activity-group', style: 'margin-bottom:6px;' }, [ vue.createVNode('div', { class: 'activity-group-title', style: 'font-size:11.5px;color:var(--cx-text-muted);margin-bottom:4px;' }, [ cxIcon(g.icon, 12), vue.createVNode('span', null, `${g.title} (${g.items.length})`) ]), vue.createVNode('div', { class: 'activity-list' }, g.items.slice(0, 3).map(act => vue.createVNode('div', { class: 'activity-item', style: 'display:flex;justify-content:space-between;align-items:center;gap:8px;padding:4px 8px;border-radius:6px;margin-bottom:3px;' }, [ vue.createVNode('span', { class: 'activity-name', style: 'font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' }, act.title), vue.createVNode('span', { class: `badge ${act.ongoing ? 'status-warning' : (act.finished ? 'status-done' : 'status-gray')}` }, act.ongoing ? '进行中' : (act.finished ? '已完成' : '未开始')) ]) )) ])) ]) ]); }; const renderOnboardingTour = () => { if (!tourActive.value) return null; const step = TOUR_STEPS[tourStepIndex.value]; if (!step) return null; const rect = tourSpotlightRect.value; const winW = window.innerWidth || 1280; const winH = window.innerHeight || 800; const cardW = Math.min(360, winW - 24); let cardTop = Math.max(20, (winH - 220) / 2); let cardLeft = Math.max(12, (winW - cardW) / 2); if (rect) { const spaceBelow = winH - rect.bottom; cardTop = spaceBelow >= 210 ? Math.min(winH - 210, rect.bottom + 12) : Math.max(16, rect.top - 205); cardLeft = Math.max(12, Math.min(winW - cardW - 12, rect.left)); } const isLast = tourStepIndex.value >= TOUR_STEPS.length - 1; return vue.createVNode('div', { class: 'cx-tour-layer' }, [ rect ? vue.createVNode('div', { class: 'cx-tour-spotlight', style: `top:${rect.top}px;left:${rect.left}px;width:${rect.width}px;height:${rect.height}px;` }) : vue.createVNode('div', { class: 'cx-tour-backdrop' }), vue.createVNode('div', { class: 'cx-tour-card', style: `top:${cardTop}px;left:${cardLeft}px;` }, [ vue.createVNode('div', { class: 'cx-tour-step-badge' }, [ cxIcon('sparkles', 12), `演示引导 · ${tourStepIndex.value + 1} / ${TOUR_STEPS.length}` ]), vue.createVNode('div', { class: 'cx-tour-title' }, step.title), vue.createVNode('div', { class: 'cx-tour-desc' }, step.desc), vue.createVNode('div', { class: 'cx-tour-footer' }, [ vue.createVNode('button', { type: 'button', class: 'back-btn', style: 'height:28px;padding:0 10px;font-size:12px;', onClick: finishOnboardingTour }, '跳过教程'), vue.createVNode('div', { style: 'display:flex;gap:6px;' }, [ tourStepIndex.value > 0 ? vue.createVNode('button', { type: 'button', class: 'external-link-btn', style: 'height:28px;padding:0 10px;font-size:12px;', onClick: prevTourStep }, '上一步') : null, vue.createVNode('button', { type: 'button', class: 'cx-btn-primary', style: 'height:28px;padding:0 12px;font-size:12px;', onClick: nextTourStep }, isLast ? '开始使用' : '下一步') ]) ]) ]) ]); }; const renderZeroTaskSuggestDialog = () => { if (!showZeroTaskSuggestDialog.value || !zeroTaskSuggestCourses.value.length) return null; const total = zeroTaskSuggestCourses.value.length; const selectedCount = zeroTaskSelectedKeys.value.size; const allChecked = selectedCount === total; return vue.createVNode('div', { class: 'confirm-overlay', onClick: dismissZeroTaskSuggest }, [ vue.createVNode('div', { class: 'confirm-dialog course-ignore-dialog', style: 'max-width:520px;width:92%;', onClick: e => e.stopPropagation() }, [ vue.createVNode('div', { class: 'confirm-title' }, [cxIcon('shield', 16), `发现 ${total} 门 0 任务点课程`]), vue.createVNode('div', { class: 'confirm-hint', style: 'margin-bottom:10px;' }, '以下课程当前显示 0/0 任务点(多为实验课、结课或无需刷课课程),勾选后可一键隐藏以减少查询与风控;如有误判请取消勾选。'), vue.createVNode('div', { style: 'display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;' }, [ vue.createVNode('span', { style: 'font-size:12px;color:var(--cx-text-muted);' }, `已选 ${selectedCount} / ${total} 门 · 支持按住 Shift 连续勾选`), vue.createVNode('button', { type: 'button', class: 'external-link-btn', style: 'height:26px;padding:0 8px;font-size:12px;', onClick: () => { zeroTaskSelectedKeys.value = allChecked ? new Set() : new Set(zeroTaskSuggestCourses.value.map(c => getCourseIgnoreKey(c))); } }, allChecked ? '取消全选' : '全选') ]), vue.createVNode('div', { class: 'course-ignore-list' }, zeroTaskSuggestCourses.value.map((course, idx) => vue.createVNode('label', { class: 'course-ignore-option' }, [ vue.createVNode('input', { type: 'checkbox', checked: zeroTaskSelectedKeys.value.has(getCourseIgnoreKey(course)), onClick: (e) => toggleZeroTaskSelection(course, idx, e) }), vue.createVNode('span', null, course.courseName) ]) )), vue.createVNode('div', { class: 'confirm-actions' }, [ vue.createVNode('button', { class: 'confirm-cancel-btn', onClick: dismissZeroTaskSuggest }, '暂不隐藏(不再提示)'), vue.createVNode('button', { class: 'confirm-ok-btn', onClick: applyZeroTaskIgnore }, `一键隐藏 (${selectedCount} 门)`) ]) ]) ]); }; const renderDeadlineReminderBanner = () => { const bannerItems = deadlineReminderBannerItems.value; if (!bannerItems.length) return null; const bannerText = bannerItems.map(alert => { const course = alert.item.course || alert.item.courseName || '课程'; return `${course} · ${alert.item.title || '待办任务'}(还剩${formatReminderRemaining(alert.deadlineAt - Date.now())})`; }).join('  |  '); return vue.createVNode('div', { class: 'deadline-reminder-banner is-inflow', role: 'status' }, [ vue.createVNode('span', { class: 'deadline-reminder-banner-icon', 'aria-hidden': 'true' }, [cxIcon('bell', 15)]), vue.createVNode('div', { class: 'deadline-reminder-banner-viewport' }, [ vue.createVNode('span', { class: `deadline-reminder-banner-text ${bannerText.length > 72 ? 'is-scrolling' : ''}` }, bannerText) ]), vue.createVNode('button', { class: 'deadline-reminder-banner-button', onClick: openDeadlineReminderDialog }, `查看 ${bannerItems.length} 项`), vue.createVNode('button', { class: 'deadline-reminder-banner-close', type: 'button', 'aria-label': '关闭临近提醒横幅', title: '关闭横幅', onClick: dismissDeadlineReminderBanner }, [cxIcon('x', 14)]) ]); }; const renderDeadlineReminderDialog = () => { const items = deadlineReminderItems.value; if (!showDeadlineReminderDialog.value || !items.length) return null; return vue.createVNode('div', { class: 'deadline-reminder-overlay', role: 'presentation', onClick: acknowledgeDeadlineReminderBatch }, [ vue.createVNode('section', { class: 'deadline-reminder-dialog', role: 'alertdialog', 'aria-modal': 'true', 'aria-labelledby': 'deadline-reminder-title', onClick: e => e.stopPropagation() }, [ vue.createVNode('div', { class: 'deadline-reminder-dialog-header' }, [ vue.createVNode('div', null, [ vue.createVNode('h2', { id: 'deadline-reminder-title' }, `有 ${items.length} 项待办临近截止`), vue.createVNode('p', null, '按截止时间由近到远排列;“我知道了”不会取消后续阶段提醒。') ]), vue.createVNode('span', { class: 'deadline-reminder-header-icon', 'aria-hidden': 'true' }, [cxIcon('clock', 18)]) ]), vue.createVNode('div', { class: 'deadline-reminder-list' }, items.map(alert => vue.createVNode('article', { class: 'deadline-reminder-item' }, [ vue.createVNode('div', { class: 'deadline-reminder-item-copy' }, [ vue.createVNode('div', { class: 'deadline-reminder-item-title' }, alert.item.title || '待办任务'), vue.createVNode('div', { class: 'deadline-reminder-item-course' }, alert.item.course || alert.item.courseName || '未知课程'), vue.createVNode('div', { class: 'deadline-reminder-item-time' }, `${alert.threshold.label}提醒 · 还剩${formatReminderRemaining(alert.deadlineAt - Date.now())}截止`) ]), vue.createVNode('div', { class: 'deadline-reminder-item-actions' }, [ vue.createVNode('button', { class: 'deadline-reminder-go-button', onClick: () => openDeadlineReminderTask(alert) }, '去完成'), vue.createVNode('button', { class: 'deadline-reminder-mute-button', onClick: () => dismissDeadlineReminderTask(alert.taskKey) }, '不再提醒') ]) ]) )), vue.createVNode('div', { class: 'deadline-reminder-dialog-footer' }, [ vue.createVNode('span', null, '每个阶段每项任务提醒一次;页面读取到完成状态后会停止后续提醒。'), vue.createVNode('button', { class: 'deadline-reminder-ack-button', onClick: acknowledgeDeadlineReminderBatch }, '我知道了') ]) ]) ]); }; if (currentView.value === 'settings') { return vue.createVNode("div", { class: "dashboard-wrapper" }, [ vue.createVNode("div", { class: "main-content" }, [renderSettingsView(renderDeadlineReminderBanner())]), renderDeadlineReminderDialog() ]); } if (currentView.value === 'dashboard-loading') { return vue.createVNode('div', { class: 'dashboard-wrapper' }, [ renderDashboardSkeleton(), renderDeadlineReminderDialog() ]); } if (currentView.value !== 'dashboard') { return vue.createVNode("div", { class: "dashboard-wrapper" }, [ vue.createVNode("div", { class: "main-content" }, [ renderDeadlineReminderBanner(), renderDetailView(currentView.value) ]), renderConfirmDialog(), renderDeadlineReminderDialog(), renderProgressPopover(), renderZeroTaskSuggestDialog() ]); } const dashboardTodoItems = sortedTodoItems.value; const dashboardTodoPreviewItems = dashboardTodoItems.slice(0, 2); const dashboardUrgentTasks = dashboardTodoItems.filter(isTodoItemUrgent); // 渲染仪表盘视图(Linear 精密桌面工作台,引导期间自动切入演示数据) const isTourDemo = tourActive.value; const dashTodoList = isTourDemo ? TOUR_DEMO_DATA.todo : dashboardTodoItems; const dashHomeworkList = isTourDemo ? TOUR_DEMO_DATA.homework : sortedHomeworkItems.value; const dashExamList = isTourDemo ? TOUR_DEMO_DATA.exam : sortedExamItems.value; const dashActivitiesList = isTourDemo ? TOUR_DEMO_DATA.activities : sortedActivitiesItems.value; const dashProgressList = isTourDemo ? TOUR_DEMO_DATA.progress : filteredCourseProgressItems.value; const dashUrgentList = isTourDemo ? TOUR_DEMO_DATA.todo.filter(i => i.isUrgent) : dashboardUrgentTasks; const pendingHomeworkCount = dashHomeworkList.filter(i => i.isActivity ? (!i.finished && i.status !== '已完成') : i.uncommitted !== false).length; const ongoingActivitiesCount = dashActivitiesList.filter(i => !i.finished && i.status !== '已结束').length; const pendingExamCount = dashExamList.filter(i => !i.finished && !i.expired).length; const activeTab = activeDashboardTab.value || 'todo'; const isRowDone = (tab, item) => { if (tab === 'homework') return item.isActivity ? (item.finished || item.status === '已完成') : item.uncommitted === false; if (tab === 'exam') return Boolean(item.finished || item.expired); if (tab === 'activities') return Boolean(item.finished || item.status === '已结束' || (!item.ongoing && item.expired)); return false; }; const rawTabItems = activeTab === 'todo' ? dashTodoList : activeTab === 'homework' ? dashHomeworkList : activeTab === 'exam' ? dashExamList : dashActivitiesList; const activeTabFilter = activeTab === 'todo' ? 'all' : (dashboardTabFilter.value || 'all'); const statusFilteredTabItems = activeTabFilter === 'all' ? rawTabItems : rawTabItems.filter(i => activeTabFilter === 'pending' ? !isRowDone(activeTab, i) : isRowDone(activeTab, i)); const activityCategoryCounts = activeTab === 'activities' ? Object.entries( statusFilteredTabItems.reduce((acc, item) => { const k = item.type || '其他任务'; acc[k] = (acc[k] || 0) + 1; return acc; }, {}) ).sort((a, b) => b[1] - a[1]) : []; const selectedCategory = activeTab === 'activities' && activityCategoryCounts.some(([k]) => k === activeActivityCategory.value) ? activeActivityCategory.value : 'all'; const visibleTabItems = activeTab === 'activities' && selectedCategory !== 'all' ? statusFilteredTabItems.filter(i => (i.type || '其他任务') === selectedCategory) : statusFilteredTabItems; const activeTabLoading = activeTab === 'todo' ? loading.value.todo : activeTab === 'homework' ? loading.value.homework : activeTab === 'exam' ? loading.value.exam : (loading.value.activities && !activitiesLoaded.value) || (!activitiesLoaded.value && !activitiesLoadFailed.value); const refreshRoutedTaskEngineByType = async (targetType) => { const routed = (activitiesItems.value || []).filter(item => item.type === targetType && item.source === 'task_engine'); if (routed.length === 0) return; const courses = routed .map(item => ({ courseId: item.courseId, clazzId: item.clazzId || item.classId, courseName: item.course || item.courseName || '' })) .filter(c => !isCourseIgnored(c)); if (courses.length === 0) return; await refreshActivitiesForSpecificCourses(courses, { taskEngineOnly: true }); }; const refreshActiveTab = async () => { if (activeTab === 'todo') { const freshHomework = await loadHomeworkData(); await loadTodoData(freshHomework); } else if (activeTab === 'homework') { await loadHomeworkData(); await refreshRoutedTaskEngineByType('作业'); } else if (activeTab === 'exam') { await loadExamData(); await refreshRoutedTaskEngineByType('考试'); } else { retryActivitiesData(); } }; const getRowDotClass = (tab, item) => { if (tab === 'todo') return item.isUrgent ? 'is-red' : (item.isActivity ? 'is-amber' : 'is-blue'); if (tab === 'homework') return isRowDone('homework', item) ? 'is-green' : 'is-blue'; if (tab === 'exam') return item.finished ? 'is-green' : (item.expired ? 'is-muted' : 'is-red'); return item.finished ? 'is-green' : (item.ongoing ? 'is-amber' : 'is-muted'); }; const getRowTimeText = (tab, item) => { if (tab === 'todo') return item.leftTime || item.info || ''; if (tab === 'homework') return item.leftTime || ''; if (tab === 'exam') return item.timeLeft || ''; return item.leftTime || ''; }; const getRowStatusText = (tab, item) => { if (tab === 'todo') return item.type || '待办'; if (tab === 'homework') return getHomeworkStatus(item); if (tab === 'exam') return item.finished ? '已完成' : (item.expired ? '已过期' : '进行中'); return item.status || (item.finished ? '已完成' : '进行中'); }; const getRowBadgeClass = (tab, item) => { if (tab === 'todo') return item.isActivity ? 'status-warning' : (item.type === '作业' ? 'status-normal' : 'status-urgent'); if (tab === 'homework') return getHomeworkBadgeClass(item); if (tab === 'exam') return item.finished ? 'status-done' : (item.expired ? 'status-gray' : 'status-urgent'); return item.finished ? 'status-done' : (item.ongoing ? 'status-warning' : 'status-normal'); }; const tm = getThemeModeMeta(); const reminderBannerCount = deadlineReminderBannerItems.value.length; return vue.createVNode("div", { class: "dashboard-wrapper" }, [ vue.createVNode("div", { class: "main-content" }, [ // 1. 顶部单行命令栏 vue.createVNode("header", { class: "cx-topbar" }, [ vue.createVNode("div", { class: "cx-topbar-left" }, [ vue.createVNode("div", { class: "cx-topbar-title" }, [ cxIcon("user", 16), `${greeting.value},${userName.value}`, vue.createVNode("span", { class: "cx-version-pill" }, "v2.6.0") ]), vue.createVNode("span", { class: "cx-topbar-date" }, dateInfo.value) ]), vue.createVNode("div", { class: "cx-cmd-search" }, [ cxIcon("search", 14), vue.createVNode("input", { id: "cx-global-search-input", type: "text", placeholder: "搜索任务、课程或活动类型...", value: searchQuery.value, onInput: e => { searchQuery.value = e.target.value; } }), searchQuery.value ? vue.createVNode("button", { type: "button", class: "cx-global-search-clear", title: "清空搜索", onClick: () => { searchQuery.value = ''; } }, "×") : vue.createVNode("span", { class: "cx-kbd" }, "Ctrl K") ]), vue.createVNode("div", { class: "cx-topbar-actions" }, [ reminderBannerCount > 0 ? vue.createVNode("button", { type: "button", class: "cx-btn-amber", onClick: openDeadlineReminderDialog }, [cxIcon("bell", 13), `临近 ${reminderBannerCount} 项`]) : null, vue.createVNode("button", { type: "button", class: "external-link-btn", title: "切换浅色/深色/跟随系统主题", onClick: (e) => cycleThemeMode(e) }, [cxIcon(tm.icon, 14), tm.label]), vue.createVNode("button", { type: "button", class: "external-link-btn", title: "仅轻量刷新作业与考试(低风控)", disabled: lightRefreshing.value, onClick: () => refreshLightTasks(true) }, [cxIcon("zap", 14), lightRefreshing.value ? "刷新中..." : "轻量刷新"]), vue.createVNode("button", { type: "button", class: "cx-btn-primary", onClick: openSettings }, [cxIcon("settings", 14), "设置"]) ]) ]), // 临近截止特别提醒(文档流内紧贴命令栏下方,显眼且零遮挡) renderDeadlineReminderBanner(), // 首次设置引导(克制横条) !settings.value.settingsHintSeen ? vue.createVNode("div", { class: "settings-onboarding", style: "margin-top:10px;" }, [ vue.createVNode("div", { class: "settings-onboarding-copy" }, [ vue.createVNode("span", { class: "settings-onboarding-icon" }, [cxIcon("sparkles", 15)]), vue.createVNode("span", null, "默认只展示核心学习任务;签到、问卷、抢答、通知等可在设置中按需开启。") ]), vue.createVNode("span", { class: "settings-onboarding-actions" }, [ vue.createVNode("button", { class: "external-link-btn", onClick: () => { updateSetting('settingsHintSeen', true); openSettings(); } }, "去设置"), vue.createVNode("button", { class: "back-btn", onClick: () => updateSetting('settingsHintSeen', true) }, "知道了") ]) ]) : null, // 2. 4 格左对齐 KPI 指标卡 vue.createVNode("section", { class: "cx-kpi-grid" }, [ vue.createVNode("div", { class: "cx-kpi-card", onClick: () => { activeDashboardTab.value = 'homework'; dashboardTabFilter.value = 'pending'; } }, [ vue.createVNode("div", { class: "cx-kpi-card-top" }, [ vue.createVNode("span", null, "待交作业"), cxIcon("fileText", 15) ]), vue.createVNode("div", { class: "cx-kpi-card-bottom" }, [ vue.createVNode("span", { class: "cx-kpi-card-val is-blue" }, String(pendingHomeworkCount)), vue.createVNode("span", { class: "cx-kpi-card-sub" }, `共 ${dashHomeworkList.length} 份`) ]) ]), vue.createVNode("div", { class: "cx-kpi-card", onClick: () => { activeDashboardTab.value = 'activities'; dashboardTabFilter.value = 'pending'; } }, [ vue.createVNode("div", { class: "cx-kpi-card-top" }, [ vue.createVNode("span", null, "进行中活动"), cxIcon("zap", 15) ]), vue.createVNode("div", { class: "cx-kpi-card-bottom" }, [ vue.createVNode("span", { class: "cx-kpi-card-val is-green" }, String(ongoingActivitiesCount)), vue.createVNode("span", { class: "cx-kpi-card-sub" }, `共 ${dashActivitiesList.length} 项`) ]) ]), vue.createVNode("div", { class: "cx-kpi-card", onClick: () => { activeDashboardTab.value = 'exam'; dashboardTabFilter.value = 'pending'; } }, [ vue.createVNode("div", { class: "cx-kpi-card-top" }, [ vue.createVNode("span", null, "待考考试"), cxIcon("clipboardList", 15) ]), vue.createVNode("div", { class: "cx-kpi-card-bottom" }, [ vue.createVNode("span", { class: "cx-kpi-card-val is-orange" }, String(pendingExamCount)), vue.createVNode("span", { class: "cx-kpi-card-sub" }, `共 ${dashExamList.length} 场`) ]) ]), vue.createVNode("div", { class: "cx-kpi-card", onClick: () => openFullScreen('progress') }, [ vue.createVNode("div", { class: "cx-kpi-card-top" }, [ vue.createVNode("span", null, "全部课程"), cxIcon("bookOpen", 15) ]), vue.createVNode("div", { class: "cx-kpi-card-bottom" }, [ vue.createVNode("span", { class: "cx-kpi-card-val" }, String(dashProgressList.length)), vue.createVNode("span", { class: "cx-kpi-card-sub" }, "点击查看进度") ]) ]) ]), // 3. 左 65% 主工作区 + 右 35% 侧边栏 vue.createVNode("div", { class: "cx-workspace-grid" }, [ // 左栏:主任务工作台 vue.createVNode("section", { class: "cx-primary-panel" }, [ vue.createVNode("div", { class: "cx-panel-header" }, [ vue.createVNode("div", { class: "cx-tab-bar" }, [ { key: 'todo', label: '待办', count: dashTodoList.length }, { key: 'homework', label: '作业', count: (settings.value.tabBadgeCountMode || 'pending') === 'pending' ? pendingHomeworkCount : dashHomeworkList.length }, { key: 'exam', label: '考试', count: (settings.value.tabBadgeCountMode || 'pending') === 'pending' ? pendingExamCount : dashExamList.length }, { key: 'activities', label: '课程任务', count: (settings.value.tabBadgeCountMode || 'pending') === 'pending' ? ongoingActivitiesCount : dashActivitiesList.length } ].map(tabItem => vue.createVNode("button", { type: "button", class: `cx-tab-btn ${activeTab === tabItem.key ? 'active' : ''}`, onClick: () => { activeDashboardTab.value = tabItem.key; dashboardTabFilter.value = settings.value.defaultTaskFilter || 'pending'; activeActivityCategory.value = 'all'; visibleListLimit.value = 60; } }, [ vue.createVNode("span", null, tabItem.label), vue.createVNode("span", { class: "cx-tab-count" }, String(tabItem.count)) ]))), vue.createVNode("div", { class: "cx-panel-tools" }, [ activeTab !== 'todo' ? vue.createVNode("div", { class: "cx-segmented-control" }, [ { key: 'all', label: '全部' }, { key: 'pending', label: '未完成' }, { key: 'done', label: '已完成' } ].map(f => vue.createVNode("button", { type: "button", class: `cx-segment-btn ${activeTabFilter === f.key ? 'active' : ''}`, style: "padding:3px 9px;font-size:12px;", onClick: () => { dashboardTabFilter.value = f.key; visibleListLimit.value = 60; } }, f.label))) : null, vue.createVNode("button", { type: "button", class: "cx-icon-refresh-btn", title: "刷新当前分类", onClick: refreshActiveTab }, [cxIcon("refreshCw", 13)]), vue.createVNode("button", { type: "button", class: "external-link-btn", style: "height:28px;padding:0 9px;font-size:12px;", onClick: () => openFullScreen(activeTab) }, "全屏") ]) ]), activeTab === 'activities' && activityCategoryCounts.length > 1 ? vue.createVNode("div", { class: "cx-subtab-bar" }, [ vue.createVNode("button", { type: "button", class: `cx-subtab-pill cx-tabular ${selectedCategory === 'all' ? 'active' : ''}`, onClick: () => { activeActivityCategory.value = 'all'; } }, `全部 ${statusFilteredTabItems.length}`), ...activityCategoryCounts.map(([cat, count]) => vue.createVNode("button", { type: "button", class: `cx-subtab-pill cx-tabular ${selectedCategory === cat ? 'active' : ''}`, onClick: () => { activeActivityCategory.value = cat; visibleListLimit.value = 60; } }, `${cat} ${count}`)) ]) : null, vue.createVNode("div", { class: "cx-panel-body" }, [ activeTab === 'activities' && activitiesLoadIssues.value.length > 0 ? vue.createVNode("div", { role: "alert", class: "cx-inline-banner is-warn" }, [ vue.createVNode("span", null, formatCourseActivityIssues(activitiesLoadIssues.value)), vue.createVNode("button", { type: "button", class: "external-link-btn", onClick: retryActivitiesData }, "重试读取") ]) : null, activeTab === 'activities' && activitiesLoadFailed.value ? vue.createVNode("div", { role: "alert", class: "cx-inline-banner is-error" }, [ vue.createVNode("span", null, "课程列表读取失败,当前结果可能不完整。"), vue.createVNode("button", { type: "button", class: "external-link-btn", onClick: retryActivitiesData }, "刷新重试") ]) : null, activeTabLoading ? vue.createVNode("div", { style: "padding:14px;" }, [renderLoadingSkeleton('正在加载数据…')]) : visibleTabItems.length === 0 ? vue.createVNode("div", { class: "empty-state", style: "padding:48px 16px;" }, [ cxIcon("checkCircle", 16), searchQuery.value ? "没有匹配当前搜索条件的内容" : "当前分类暂无任务" ]) : [ ...visibleTabItems.slice(0, visibleListLimit.value).map(item => { const timeTxt = getRowTimeText(activeTab, item); const isTimeUrgent = Boolean(item.isUrgent) || (timeTxt && !item.finished && parseTimeToMinutes(timeTxt) < 24 * 60); return vue.createVNode("div", { class: "cx-issue-row", onClick: () => openTaskLink(item, activeTab) }, [ vue.createVNode("div", { class: "cx-issue-left" }, [ vue.createVNode("span", { class: `cx-status-dot ${getRowDotClass(activeTab, item)}` }), vue.createVNode("span", { class: "cx-issue-title", title: item.title }, item.title), (item.course || item.courseName) ? vue.createVNode("span", { class: "cx-issue-course", title: item.course || item.courseName }, `· ${item.course || item.courseName}`) : null ]), vue.createVNode("div", { class: "cx-issue-right" }, [ resolvingTaskKey.value === getResolvingKey(item, activeTab) ? vue.createVNode("span", { class: "cx-inline-spinner", title: "正在解析直达链接…" }) : null, activeTab === 'activities' && item.type ? vue.createVNode("span", { class: "cx-type-col" }, [vue.createVNode("span", { class: "badge status-gray" }, item.type)]) : null, timeTxt ? vue.createVNode("span", { class: `cx-time-mono ${isTimeUrgent ? 'urgent' : ''}` }, timeTxt) : null, vue.createVNode("span", { class: `badge ${getRowBadgeClass(activeTab, item)}` }, getRowStatusText(activeTab, item)), settings.value.ignoreEnabled ? vue.createVNode("button", { class: "ignore-btn", title: "忽略此任务", onClick: (e) => { e.stopPropagation(); requestIgnore(item, activeTab); } }, [cxIcon("ban", 13)]) : null ]) ]); }), visibleTabItems.length > visibleListLimit.value ? vue.createVNode("div", { class: "cx-load-more-bar" }, [ vue.createVNode("button", { type: "button", class: "external-link-btn", onClick: () => { visibleListLimit.value += 60; } }, `加载更多(剩余 ${visibleTabItems.length - visibleListLimit.value} 项)`) ]) : null ] ]) ]), // 右栏:紧急焦点 + 课程进度 vue.createVNode("aside", { class: "cx-side-rail" }, [ // 紧急焦点面板 vue.createVNode("section", { class: "cx-side-panel" }, [ vue.createVNode("div", { class: "cx-side-panel-head" }, [ vue.createVNode("div", { class: "cx-side-panel-title" }, [ cxIcon("bell", 14), `24h 紧急焦点 (${dashUrgentList.length})` ]), vue.createVNode("a", { class: "card-more", onClick: () => openFullScreen('todo') }, "全部待办") ]), vue.createVNode("div", { class: "cx-side-panel-body" }, [ dashUrgentList.length === 0 ? vue.createVNode("div", { class: "empty-state", style: "padding:18px 8px;" }, [cxIcon("checkCircle", 15), "未来 24 小时暂无紧急任务"]) : dashUrgentList.slice(0, 5).map(item => vue.createVNode("div", { class: "cx-focus-item", onClick: () => openTaskLink(item, 'todo') }, [ vue.createVNode("div", { style: "min-width:0;flex:1;" }, [ vue.createVNode("div", { class: "cx-focus-title" }, item.title), vue.createVNode("div", { class: "cx-focus-sub" }, `${item.course || item.type || '待办'} · ${item.leftTime || item.info || '即将截止'}`) ]), vue.createVNode("span", { class: "badge status-urgent" }, item.type || '紧急') ]) ) ]) ]), // 课程进度面板(默认聚焦进行中课程,移除内联悬浮窗) vue.createVNode("section", { class: "cx-side-panel" }, [ vue.createVNode("div", { class: "cx-side-panel-head", style: "flex-wrap:wrap;" }, [ vue.createVNode("div", { class: "cx-side-panel-title" }, [ cxIcon("barChart", 14), "课程进度", progressFromCache.value ? vue.createVNode("span", { class: "cache-source-note" }, "缓存") : null ]), vue.createVNode("div", { style: "display:flex;align-items:center;gap:6px;" }, [ vue.createVNode("button", { type: "button", class: "ignored-panel-btn", style: "height:26px;padding:0 8px;font-size:11.5px;", onClick: () => { progressSideFilter.value = progressSideFilter.value === 'ongoing' ? 'all' : 'ongoing'; } }, progressSideFilter.value === 'ongoing' ? '仅进行中' : '全部课程'), vue.createVNode("button", { type: "button", class: "cx-icon-refresh-btn", style: "height:26px;", title: "刷新课程进度", onClick: () => loadAllCourseProgress() }, [cxIcon("refreshCw", 12)]), vue.createVNode("a", { class: "card-more", onClick: () => openFullScreen('progress') }, "全部") ]) ]), vue.createVNode("div", { class: "cx-side-panel-body" }, [ showProgressIgnoredPanel.value ? vue.createVNode("div", null, [ vue.createVNode("div", { style: "display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;" }, [ vue.createVNode("span", { style: "display:inline-flex;align-items:center;gap:5px;font-size:12.5px;color:var(--cx-accent);font-weight:500;" }, [cxIcon("ban", 13), "已忽略课程"]), vue.createVNode("div", { style: "display:flex;gap:6px;" }, [ progressIgnoredForRestore.value.size > 0 ? vue.createVNode("button", { class: "batch-restore-btn", onClick: batchProgressRestore }, `恢复(${progressIgnoredForRestore.value.size})`) : null, vue.createVNode("button", { class: "ignored-panel-btn", onClick: () => { showProgressIgnoredPanel.value = false; progressIgnoredForRestore.value = new Set(); } }, "返回") ]) ]), (() => { ignoredVersion.value; const progressIgnored = getIgnoredItemsBySection('progress'); if (progressIgnored.length === 0) return vue.createVNode("div", { class: "empty-state" }, "暂无已忽略课程"); return vue.createVNode("div", { style: "display:flex;flex-direction:column;gap:6px;" }, progressIgnored.map(ig => { const isChecked = progressIgnoredForRestore.value.has(ig._key); return vue.createVNode("div", { class: "detail-list-item" }, [ vue.createVNode("div", { class: `select-checkbox ${isChecked ? 'checked' : ''}`, onClick: (e) => { e.stopPropagation(); toggleProgressRestoreItem(ig._key); } }, isChecked ? cxIcon("check", 12) : ""), vue.createVNode("div", { class: "detail-item-main" }, [ vue.createVNode("div", { class: "detail-item-title" }, ig.title) ]), vue.createVNode("button", { class: "restore-single-btn", onClick: (e) => { e.stopPropagation(); restoreSingle(ig._key); } }, "撤销") ]); }) ); })() ]) : !isTourDemo && loadingProgress.value && !progressLoaded.value ? renderLoadingSkeleton('正在加载课程进度…') : !isTourDemo && !progressLoaded.value ? renderLoadingSkeleton('正在加载课程进度…') : !isTourDemo && !isProgressEnabled() ? vue.createVNode("div", { class: "empty-state" }, "课程进度查询已关闭") : progressLoadFailed.value ? vue.createVNode("button", { class: "empty-state", onClick: () => loadAllCourseProgress() }, "课程进度加载失败,点击重试") : (() => { const sideList = isTourDemo ? dashProgressList : (progressSideFilter.value === 'ongoing' ? dashProgressList.filter(isOngoingProgressCourse) : dashProgressList); if (sideList.length === 0) { return vue.createVNode("div", { class: "empty-state" }, progressSideFilter.value === 'ongoing' ? "暂无进行中课程,点击右上角可看全部" : "暂无课程进度数据"); } return vue.createVNode("div", { class: "cx-progress-compact-list" }, sideList.map(course => { const isEmpty = isZeroTaskCourse(course); const rate = parseInt(course.completionRate) || 0; const rateClass = isEmpty ? 'empty' : (rate >= 100 ? 'complete' : (rate >= 60 ? 'warning' : (rate >= 30 ? 'normal' : 'danger'))); return vue.createVNode("div", { class: "cx-progress-compact-row", onMouseenter: (e) => handleProgressItemHover(e, course), onMouseleave: handleProgressItemLeave, onClick: () => { if (course.studyDataUrl) window.open(course.studyDataUrl, '_blank'); } }, [ vue.createVNode("div", { class: "cx-progress-row-top" }, [ vue.createVNode("span", { class: "cx-progress-row-name", title: course.courseName }, course.courseName), vue.createVNode("span", { class: "cx-progress-row-stat" }, [ vue.createVNode("span", { class: `cx-progress-row-pct ${rateClass}` }, isEmpty ? '无任务点' : course.completionRate), !isEmpty ? vue.createVNode("span", null, `· ${course.completedTasks}/${course.totalTasks}`) : null, settings.value.ignoreEnabled ? vue.createVNode("button", { class: "ignore-btn", onClick: (e) => { e.stopPropagation(); requestIgnore(course, 'progress'); } }, [cxIcon("ban", 12)]) : null ]) ]), vue.createVNode("div", { class: "progress-bar", style: "margin-top:6px;" }, [ vue.createVNode("div", { class: `progress-bar-fill ${rateClass}`, style: `width: ${isEmpty ? 0 : Math.min(rate, 100)}%;` }) ]) ]); }) ); })() ]) ]) ]) ]) ]), // 全局确认弹窗 renderConfirmDialog(), renderDeadlineReminderDialog(), renderProgressPopover(), renderZeroTaskSuggestDialog(), renderOnboardingTour(), !settings.value.courseIgnoreHintSeen ? vue.createVNode("div", { class: "course-ignore-onboarding", role: "dialog", 'aria-labelledby': 'course-ignore-onboarding-title' }, [ vue.createVNode("div", { class: "course-ignore-onboarding-head" }, [ vue.createVNode("span", { class: "course-ignore-onboarding-icon", 'aria-hidden': 'true' }, [cxIcon("shield", 18)]), vue.createVNode("div", null, [ vue.createVNode("div", { id: "course-ignore-onboarding-title", class: "course-ignore-onboarding-title" }, "忽略不需要查询的课程"), vue.createVNode("div", { class: "course-ignore-onboarding-copy" }, "可将已结课或无需关注的课程加入忽略列表,减少无效查询和触发风控的概率。") ]) ]), vue.createVNode("div", { class: "course-ignore-onboarding-actions" }, [ vue.createVNode("button", { class: "back-btn", onClick: () => updateSetting('courseIgnoreHintSeen', true) }, "知道了"), vue.createVNode("button", { class: "external-link-btn", onClick: openCourseIgnoreFromHint }, "去忽略课程") ]) ]) : null, dashboardSkeletonOverlay.value ? renderDashboardSkeletonOverlay() : null ]); }; } }); const appendApp = () => { ensureResponsiveViewport(); ensureDashboardStyles(); const initialTheme = resolveThemeMode(getSettings().themeMode); document.documentElement.setAttribute('data-cx-theme', initialTheme); const vuetify$1 = vuetify.createVuetify({ theme: { defaultTheme: initialTheme }, icons: { defaultSet: "md", aliases, sets: { md } } }); vuetifyInstance = vuetify$1; window.matchMedia?.('(prefers-color-scheme: dark)')?.addEventListener?.('change', () => { if (getSettings().themeMode === 'system') applyThemeMode('system'); }); let app = _sfc_main$1; const urlDetect2 = urlDetection(); if (urlDetect2 === "homework") app = _sfc_main$2; if (urlDetect2 === "exam") app = _sfc_main; if (urlDetect2 === "todo") app = _sfc_todo; if (urlDetect2 === "activities") app = _sfc_activities; if (urlDetect2 === "dashboard") app = _sfc_dashboard; vue.createApp(app).use(vuetify$1).mount( (() => { const app2 = document.createElement("div"); app2.className = "chaoxing-list-root"; document.body.append(app2); return app2; })() ); }; const urlDetect = urlDetection(); if (urlDetect === "homework" || urlDetect === "todo" || urlDetect === "activities" || urlDetect === "dashboard") { wrapElements(); removeStyles(); removeScripts(); appendApp(); } if (urlDetect === "exam") { wrapElements(); removeStyles(); removeScripts(); keepRemoveHtmlStyle(); appendApp(); } if (urlDetect === "exam_take") { startExamAutoFullPreview(); } if (urlDetect === "pcpick_auto") { startPcpickAutoOpen(); } if (urlDetect === "home") { fixCssConflict(); startHostDarkModeSync(); startDashboardMenuBootstrap(); } if (urlDetect === "legacyHome") { fixCssConflict(); startHostDarkModeSync(); startDashboardMenuBootstrap(); } })(Vuetify, Vue);