// ==UserScript== // @name B站合集列表管理器(主题开关版 V7.2) // @namespace http://tampermonkey.net/ // @version 7.2 // @description 侧边吸附按钮可拖拽半隐藏,可选择是否跟随B站深浅主题,可视化勾选,强制从头播放,自动定位当前播放。支持偏好列表(PreferList):任意列表点⭐跨合集收集,按偏好顺序播放 // @author 你 // @match *://www.bilibili.com/* // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_registerMenuCommand // @grant GM_notification // @run-at document-start // @license MIT // ==/UserScript== (function() { 'use strict'; // ========== 0. 全局配置与存储键 ========== const MEMORY_STORAGE_KEY = 'bili_force_memory_list'; const STORAGE_KEY = 'bili_force_video_data_v3'; const THEME_KEY = 'bili_list_theme'; const THEME_FOLLOW_KEY = 'bili_list_theme_follow'; const POS_KEY = 'bili_trigger_pos'; const BEAUTY_CONFIG_KEY = 'bili_list_beauty_config'; const BG_DB_NAME = 'BiliListManagerDB'; const BG_DB_VERSION = 1; const BG_STORE = 'bg_images'; const LOG_PREFIX = '[列表管理]'; window.__biliListManagerLoaded = true; // ========== 0.0 美化配置与背景图IndexedDB ========== function getBeautyConfig() { try { const saved = JSON.parse(localStorage.getItem(BEAUTY_CONFIG_KEY) || '{}'); return { frostedGlass: saved.frostedGlass !== false, glassBlur: saved.glassBlur || 12, drawerOpacity: saved.drawerOpacity !== undefined ? saved.drawerOpacity : 0.85, defaultBgOpacity: saved.defaultBgOpacity !== undefined ? saved.defaultBgOpacity : 0.15, bgSize: saved.bgSize || 'cover', bgPosition: saved.bgPosition || 'center' }; } catch(e) { return { frostedGlass: true, glassBlur: 12, drawerOpacity: 0.85, defaultBgOpacity: 0.15, bgSize: 'cover', bgPosition: 'center' }; } } // 暴露给2.js实时调用 window.__biliListGetBeautyConfig = getBeautyConfig; function openBgDB() { return new Promise((resolve, reject) => { const req = indexedDB.open(BG_DB_NAME, BG_DB_VERSION); req.onupgradeneeded = (e) => { const db = e.target.result; if (!db.objectStoreNames.contains(BG_STORE)) { db.createObjectStore(BG_STORE, { keyPath: 'id' }); } }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } async function getBgImage(id) { try { const db = await openBgDB(); return new Promise((resolve) => { const tx = db.transaction(BG_STORE, 'readonly'); const store = tx.objectStore(BG_STORE); const req = store.get(id); req.onsuccess = () => resolve(req.result || null); req.onerror = () => resolve(null); }); } catch(e) { return null; } } async function applyCurrentBg() { let drawer = document.getElementById('bili-force-drawer'); if (!drawer) { createDrawer(); drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; } const cid = getCollectionIdFromPage(); let bgEntry = null; if (cid) bgEntry = await getBgImage(cid); const useDefault = !bgEntry; if (useDefault) bgEntry = await getBgImage('__default__'); const cfg = getBeautyConfig(); const isDark = getTheme() === 'dark'; const header = drawer.querySelector('.drawer-header'); const body = drawer.querySelector('.drawer-body'); const footer = drawer.querySelector('.drawer-footer'); // 整个面板磨砂 drawer.style.backdropFilter = cfg.frostedGlass ? `blur(${cfg.glassBlur}px)` : 'none'; drawer.style.webkitBackdropFilter = cfg.frostedGlass ? `blur(${cfg.glassBlur}px)` : 'none'; // 背景层/遮罩层放在drawer级(不随body列表滚动,图片稳定显示) let bgLayer = drawer.querySelector('.drawer-bg-layer'); let bgMask = drawer.querySelector('.drawer-bg-mask'); if (!bgLayer || !bgMask) { if (!bgLayer) { bgLayer = document.createElement('div'); bgLayer.className = 'drawer-bg-layer'; bgLayer.style.cssText = 'position:absolute;inset:0;background-repeat:no-repeat;pointer-events:none;z-index:0;transition:opacity 0.2s ease;'; drawer.insertBefore(bgLayer, drawer.firstChild); } if (!bgMask) { bgMask = document.createElement('div'); bgMask.className = 'drawer-bg-mask'; bgMask.style.cssText = 'position:absolute;inset:0;pointer-events:none;z-index:1;'; drawer.insertBefore(bgMask, bgLayer.nextSibling); } } // header/footer:接近不透明的纯色背景盖住图片,只让body列表区露出图片 const headerFooterBg = isDark ? 'rgba(30,30,30,0.96)' : 'rgba(255,255,255,0.96)'; if (header) { header.style.zIndex = '3'; header.style.position = 'relative'; header.style.background = headerFooterBg; header.style.backdropFilter = cfg.frostedGlass ? `blur(${cfg.glassBlur}px)` : 'none'; } if (footer) { footer.style.zIndex = '3'; footer.style.position = 'relative'; footer.style.background = headerFooterBg; footer.style.backdropFilter = cfg.frostedGlass ? `blur(${cfg.glassBlur}px)` : 'none'; } // body列表区:透明露出背景图,保持可滚动 if (body) { body.style.zIndex = '2'; body.style.position = 'relative'; body.style.background = 'transparent'; body.style.overflow = 'auto'; } // 设置半透明面板遮罩(覆盖在背景图上) const maskColor = bgEntry && bgEntry.imageData ? (isDark ? `rgba(30,30,30,${cfg.drawerOpacity})` : `rgba(255,255,255,${cfg.drawerOpacity})`) : (isDark ? 'rgba(30,30,30,1)' : 'rgba(255,255,255,1)'); bgMask.style.background = maskColor; // 设置背景图(drawer级,不随列表滚动) if (bgEntry && bgEntry.imageData) { bgLayer.style.backgroundImage = `url("${bgEntry.imageData}")`; bgLayer.style.backgroundSize = (bgEntry.bgSize) || cfg.bgSize || 'cover'; bgLayer.style.backgroundPosition = (bgEntry.bgPosition) || cfg.bgPosition || 'center'; bgLayer.style.opacity = bgEntry.opacity !== undefined ? bgEntry.opacity : cfg.defaultBgOpacity; } else { bgLayer.style.backgroundImage = 'none'; bgLayer.style.opacity = '0'; } } // 挂载共享函数到unsafeWindow(页面共享窗口,跨油猴沙箱100%可访问) const _global = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; _global.__biliListRefreshBg = applyCurrentBg; _global.__biliListUpdateBeautyCfg = (partialCfg) => { try { const current = getBeautyConfig(); const merged = { ...current, ...partialCfg }; localStorage.setItem(BEAUTY_CONFIG_KEY, JSON.stringify(merged)); applyCurrentBg(); } catch(e) { console.error(e); } }; _global.__biliListSaveBgImage = async (id, imageData, opts = {}) => { try { const db = await openBgDB(); return new Promise((resolve) => { const tx = db.transaction(BG_STORE, 'readwrite'); const store = tx.objectStore(BG_STORE); const entry = { id, imageData, uploadTime: Date.now(), ...opts }; store.put(entry); tx.oncomplete = () => { applyCurrentBg(); resolve(true); }; tx.onerror = () => resolve(false); }); } catch(e) { return false; } }; async function deleteBgImageById(id) { try { const db = await openBgDB(); return new Promise((resolve) => { const tx = db.transaction(BG_STORE, 'readwrite'); const store = tx.objectStore(BG_STORE); store.delete(id); tx.oncomplete = () => { applyCurrentBg(); resolve(true); }; tx.onerror = () => resolve(false); }); } catch(e) { return false; } } _global.__biliListDeleteBgImage = deleteBgImageById; _global.__biliListGetCollectionId = getCollectionIdFromPage; _global.__biliListGetBeautyConfig = getBeautyConfig; _global.__biliListManagerLoaded = true; // 备用通信:监听信号元素属性变化(即使直接函数调用失败也能工作) function ensureSignalEl() { let signal = document.getElementById('__bili_list_beauty_signal'); if (!signal) { signal = document.createElement('div'); signal.id = '__bili_list_beauty_signal'; signal.style.display = 'none'; signal.setAttribute('data-version', Date.now().toString()); (document.body || document.documentElement).appendChild(signal); } return signal; } const startObserver = () => { const signal = ensureSignalEl(); const observer = new MutationObserver(() => { applyCurrentBg(); }); observer.observe(signal, { attributes: true, attributeFilter: ['data-version'] }); }; if (document.body) startObserver(); else document.addEventListener('DOMContentLoaded', startObserver); // 进度相关 Key 常量 const PROGRESS_KEYS = [ 'bilibili_player_progress', 'bpx_player_history', 'player_progress', 'video_progress', 'play_history', 'bpx_player_progress', 'bpx_player_profile', 'cumulative_play_time', 'bilibili_player_kv_config', 'bpcc_persisted', 'bpcfgzip_prod_36900', 'pcdnzip_prod_36900', 'time_tracker', 'recommend_auto_play' ]; const TARGET_DB_LIST = ['MIRROR_TRACK_V2', 'PLAYER_LOG', 'pbp3']; const TARGET_STORE_LIST = ['log', 'meta', 'pbpZebraCache']; // ========== 0.1 旧版本缓存清理 ========== function cleanupLegacyCache() { const LEGACY_KEYS = [ 'bili_force_video_data', // 无版本号原始版 'bili_force_video_data_v1', // V1版本 'bili_force_video_data_v2', // V2版本(结构不兼容v3) 'bili_force_video_list', // 早期单列表格式 'bili_force_video_lists' // 早期多列表格式 {"lists":[]} ]; let cleanedCount = 0; LEGACY_KEYS.forEach(key => { try { if (GM_getValue(key, null) !== null) { GM_deleteValue(key); cleanedCount++; } } catch(e) {} }); if (cleanedCount > 0) { console.log(LOG_PREFIX, `已清理 ${cleanedCount} 个旧版本缓存`); } } // ========== 1. 存储层永久劫持 ========== // 关键:本脚本在沙箱 world 运行(有 @grant),直接改 Storage.prototype 只会改到沙箱自己的原型, // B站播放器在页面主 world 读写的 localStorage 完全不受影响——必须劫持 unsafeWindow 的原型才能真正拦截续播进度 const _pageWin = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const _pageStorageProto = _pageWin.Storage && _pageWin.Storage.prototype; const origGetItem = _pageStorageProto ? _pageStorageProto.getItem : Storage.prototype.getItem; const origSetItem = _pageStorageProto ? _pageStorageProto.setItem : Storage.prototype.setItem; const patchedSetItem = function(key, value) { if (PROGRESS_KEYS.some(k => key.includes(k))) return; return origSetItem.call(this, key, value); }; const patchedGetItem = function(key) { if (window.__biliForceStartEnabled && PROGRESS_KEYS.some(k => key.includes(k))) { return null; } return origGetItem.call(this, key); }; if (_pageStorageProto) { _pageStorageProto.setItem = patchedSetItem; _pageStorageProto.getItem = patchedGetItem; } try { Storage.prototype.setItem = patchedSetItem; Storage.prototype.getItem = patchedGetItem; } catch (e) {} const origIDBOpen = _pageWin.indexedDB.open.bind(_pageWin.indexedDB); _pageWin.indexedDB.open = function(dbName, version) { const req = origIDBOpen(dbName, version); if (TARGET_DB_LIST.includes(dbName)) { req.onsuccess = function() { try { const db = req.result; Array.from(db.objectStoreNames).forEach(storeName => { if (TARGET_STORE_LIST.includes(storeName)) { try { const tx = db.transaction(storeName, 'readwrite'); tx.objectStore(storeName).clear(); } catch(e) {} } }); } catch(e) {} }; } return req; }; // ========== 2. 工具函数 ========== function getMemoryList() { try { return JSON.parse(GM_getValue(MEMORY_STORAGE_KEY, '{}')); } catch(e) { return {}; } } function saveMemoryList(data) { GM_setValue(MEMORY_STORAGE_KEY, JSON.stringify(data)); } function getAllData() { try { return JSON.parse(GM_getValue(STORAGE_KEY, '{}')); } catch(e) { return {}; } } function saveAllData(data) { GM_setValue(STORAGE_KEY, JSON.stringify(data)); } // 合集名映射 {collectionKey: 合集标题}:从视频页合集组件(ugc_season / a.title.jumpable)抓取,渲染时替代「BV标题 等N个」 const COLL_NAME_KEY = 'bili_collection_names'; // 偏好列表(PreferList):跨合集/多视频的喜好收集 [{id, name, items:[{id,bv,p,title}]}] // items.id 与勾选列表同格式(纯 BV=全分P放行 / BV::P 精确到分P),播放链路直接复用 matchListEntry const PREFER_KEY = 'bili_prefer_lists_v1'; const PREFER_ACTIVE_KEY = 'bili_prefer_active'; // 当前正在按顺序播放的偏好列表 id function getNameMap() { try { return JSON.parse(GM_getValue(COLL_NAME_KEY, '{}')); } catch(e) { return {}; } } function saveNameMap(m) { GM_setValue(COLL_NAME_KEY, JSON.stringify(m)); } function recordCollectionName(cid, name) { if (!cid || !name || cid.indexOf('single_') === 0) return; const m = getNameMap(); if (m[cid] === name) return; m[cid] = name; saveNameMap(m); } // 抓当前页面的合集标题:优先 __INITIAL_STATE__(官方数据)→ 新版侧栏合集标题链接 → h1 视频标题(单BV多P合集场景) function grabCollectionTitle() { const GENERIC = /^(视频选集|合集|选集|分集|播放列表)$/; const pick = el => { if (!el) return ''; const t = (el.getAttribute('title') || el.getAttribute('data-title') || el.textContent || '').trim(); return (t && !GENERIC.test(t)) ? t : ''; // 过滤「视频选集」等组件通用词 }; try { const vd = window.__INITIAL_STATE__ && window.__INITIAL_STATE__.videoData; const t = vd && vd.ugc_season && vd.ugc_season.title; if (t && String(t).trim()) return String(t).trim(); } catch (e) {} const cands = ['.video-pod a.title.jumpable', 'a.title.jumpable', '.video-pod .title', '.ugc-season .title', 'h1.video-title']; for (const sel of cands) { const t = pick(document.querySelector(sel)); if (t) return t; } return ''; } // ====================== 偏好列表(PreferList)存储 ====================== function getPreferLists() { try { const v = JSON.parse(GM_getValue(PREFER_KEY, '[]')); return Array.isArray(v) ? v : []; } catch (e) { return []; } } function savePreferLists(lists) { GM_setValue(PREFER_KEY, JSON.stringify(lists)); } function getActivePreferId() { try { return GM_getValue(PREFER_ACTIVE_KEY, null); } catch (e) { return null; } } function setActivePreferId(id) { try { if (id) GM_setValue(PREFER_ACTIVE_KEY, id); else GM_deleteValue(PREFER_ACTIVE_KEY); } catch (e) {} } function findPreferList(id) { return getPreferLists().find(l => l && l.id === id) || null; } // 自动命名:偏好1、偏好2…(跳过已被占用/改名占用的编号) function nextPreferName(lists) { const used = new Set(lists.map(l => l.name)); let n = 1; while (used.has('偏好' + n)) n++; return '偏好' + n; } function createPreferList() { const lists = getPreferLists(); const l = { id: 'p' + Date.now(), name: nextPreferName(lists), items: [] }; lists.push(l); savePreferLists(lists); return l; } // 加入/移出单个偏好列表;返回 true=本次为加入 function togglePreferItem(listId, item) { const lists = getPreferLists(); const l = lists.find(x => x.id === listId); if (!l) return false; const idx = l.items.findIndex(i => i.id === item.id); if (idx >= 0) l.items.splice(idx, 1); else l.items.push(item); savePreferLists(lists); return idx < 0; } // 「上次播放到哪」直接从 4.js 观看记录推导(条目 BV 的 lastTime 最新者), // 与多合集跳转「最近看过的 BV」同一数据源,不另造存储。返回 { it: 条目, t: lastTime } 或 null let preferRecsCache = null; // 4.js views 记录缓存(首次进偏好视图异步加载,加载完重渲染一次) let preferAutoScrolled = false; // 本次打开偏好视图是否已执行「滚到上次」 function derivePreferLast(l, recs) { const byBv = {}; (recs || []).forEach(r => { if (r && r.id) byBv[r.id] = r; }); let best = null, bestT = 0; (l.items || []).forEach(it => { const bv = it.bv || (it.id.includes('::') ? it.id.split('::')[0] : it.id); const t = (byBv[bv] && byBv[bv].lastTime) || 0; if (t > bestT) { bestT = t; best = it; } }); return best ? { it: best, t: bestT } : null; } function getLuminance(r, g, b) { return 0.299 * r + 0.587 * g + 0.114 * b; } function getBilibiliTheme() { // 优先级1: data-theme 属性 try { const dataTheme = document.documentElement.getAttribute('data-theme'); if (dataTheme === 'dark' || dataTheme === 'light') return dataTheme; } catch(e) {} // 优先级2: html 类名 try { const html = document.documentElement; if (html.classList.contains('dark')) return 'dark'; if (html.classList.contains('light')) return 'light'; } catch(e) {} // 优先级3: localStorage try { const stored = localStorage.getItem('bilibili_theme'); if (stored === 'dark' || stored === 'light') return stored; } catch(e) {} // 优先级4: 计算 body 背景色亮度 try { const bodyStyle = window.getComputedStyle(document.body); const bgColor = bodyStyle.backgroundColor; const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/); if (match) { const r = parseInt(match[1]); const g = parseInt(match[2]); const b = parseInt(match[3]); const luminance = getLuminance(r, g, b); return luminance < 128 ? 'dark' : 'light'; } } catch(e) {} // 优先级5: 默认 dark return 'dark'; } function getThemeFollow() { return GM_getValue(THEME_FOLLOW_KEY, true); } function saveThemeFollow(follow) { GM_setValue(THEME_FOLLOW_KEY, follow); } function getTheme() { if (getThemeFollow()) { return getBilibiliTheme(); } const manual = GM_getValue(THEME_KEY, 'dark'); return manual === 'dark' || manual === 'light' ? manual : 'dark'; } function saveTheme(theme) { GM_setValue(THEME_KEY, theme); } function getTriggerPos() { try { const saved = JSON.parse(GM_getValue(POS_KEY, '{"side":"right","top":120}')); return { side: saved.side || 'right', top: saved.top || 120 }; } catch(e) { return { side: 'right', top: 120 }; } } function saveTriggerPos(pos) { GM_setValue(POS_KEY, JSON.stringify(pos)); } function getListName() { // 新版:选集页 header .title 只是"视频选集"字样,改用页面 JSON 的视频标题作列表名 if (isNewStyleVideoList()) { const vd = getInitialStateVideoData(); const t = vd && vd.title ? String(vd.title).trim() : ''; if (t) return t; } const titleEl = document.querySelector('.video-pod__header .title'); if (titleEl) return titleEl.textContent.trim(); const metaTitle = document.querySelector('meta[property="og:title"]'); if (metaTitle) { let t = metaTitle.getAttribute('content') || ''; t = t.replace(/^[^_]*_/, '').trim(); return t || '未知合集'; } return '未知合集'; } function syncForceStartState() { // 持久化的全局开关优先:memory 按列表名匹配不可靠(多合集下名字对不上会误把开关强制关闭, // 导致 resetVideo / 续播拦截全部失效,视频“突破”强制从头播放) try { const persisted = GM_getValue(FORCE_KEY, null); if (persisted !== null) { window.__biliForceStartEnabled = !!persisted; return window.__biliForceStartEnabled; } } catch (e) {} const listName = getListName(); const memory = getMemoryList(); for (const key in memory) { if (memory[key] && memory[key][0] === listName) { const entry = memory[key]; window.__biliForceStartEnabled = entry.length >= 3 ? entry[1] : false; try { GM_setValue(FORCE_KEY, window.__biliForceStartEnabled); } catch (e) {} // 老状态无缝迁移到持久开关 return window.__biliForceStartEnabled; } } window.__biliForceStartEnabled = false; return false; } // ========== 3. 视频强制归零 ========== // 归零只在每个视频页打开后的初始窗口内生效;「立即归零」每个视频页只做一次(重试链只为补 video 晚创建的空档, // 不能反复打断正常播放);事件归零用大阈值——只抓「突然跳到远处」的续播 seek,不碰连续播放/清晰度切换的连续进度 const FORCE_ZERO_WINDOW_MS = 8000; const FORCE_ZERO_SEEK_THRESHOLD = 8; function resetVideo() { if (window.__isOpeningPanel || !window.__biliForceStartEnabled) return; if (Date.now() > (window.__forceZeroDeadline || 0)) return; // 窗口外:不干预,用户可自由拖动 const videos = document.querySelectorAll('video'); if (!videos.length) return; // 播放器 video 尚未创建:交给 onBodyReady 的重试链,不在这里空转 videos.forEach(v => { const forceZero = () => { if (!window.__biliForceStartEnabled) return; if (Date.now() > (window.__forceZeroDeadline || 0)) return; // 清晰度切换/缓冲恢复时 currentTime 是连续小值,不能拽(否则正常播放会被反复拽回开头) if (v.currentTime > FORCE_ZERO_SEEK_THRESHOLD) { v.currentTime = 0; window.__forceZeroDone = true; } }; // playing 兜底:B站可能在 canplay 之后才把进度 seek 到上次位置 ['loadedmetadata', 'canplay', 'playing'].forEach(ev => { v.removeEventListener(ev, forceZero); v.addEventListener(ev, forceZero); }); // 立即归零:每个视频页只执行一次,之后重试只负责补绑监听 if (!window.__forceZeroDone && v.readyState >= 1 && v.currentTime > 0.5) { v.currentTime = 0; window.__forceZeroDone = true; } }); } // ========== 4. URL 参数清理 + SPA 路由劫持 ========== const origPushState = history.pushState; let _isRedirecting = false; // 防止自己跳转时死循环 const FORCE_KEY = 'bili_list_force_start'; // 强制从头播放开关的持久化(不依赖 memory 列表名匹配) // 统一的列表项匹配:纯 BV 勾选 = 该视频所有分P都算命中;BV::P 精确到分P。 // 此前三处(拦截判定/checkAndHijack/onVideoEnded)各自为政,P 判断不一致导致拦截链路行为错乱 function matchListEntry(id, bv, pIdx) { if (!id) return false; if (id.includes('::')) { const [ibv, ip] = id.split('::'); return ibv === bv && parseInt(ip, 10) === pIdx; } return id === bv; } function isCurrentVideoInCheckedList() { if (!window.__biliForceStartEnabled) return true; const currentBv = getCurrentBVID(); if (!currentBv) return true; // 不在视频页面不处理 const currentP = getCurrentPIndex(); const list = getListForCurrentCollection(); if (list.length === 0) return true; // 没有保存列表不拦截 for (const id of list) { if (matchListEntry(id, currentBv, currentP)) return true; } return false; } function redirectToFirstCheckedIfNeeded(delay = 100) { if (_isRedirecting || window.__isOpeningPanel) return; if (!window.__biliForceStartEnabled) return; if (isCurrentVideoInCheckedList()) return; const list = getListForCurrentCollection(); if (list.length === 0) return; _isRedirecting = true; const firstId = list[0]; const firstBv = firstId.includes('::') ? firstId.split('::')[0] : firstId; const firstP = firstId.includes('::') ? parseInt(firstId.split('::')[1]) : null; setTimeout(() => { navigateToVideo(firstBv, firstP); resetVideo(); showToast('🚫 已拦截未勾选视频,回到列表第一首'); setTimeout(() => { _isRedirecting = false; }, 500); }, delay); } history.pushState = function(...args) { origPushState.apply(this, args); if (!window.__isOpeningPanel) { setTimeout(resetVideo, 200); setTimeout(resetVideo, 600); setTimeout(redirectToFirstCheckedIfNeeded, 100); setTimeout(redirectToFirstCheckedIfNeeded, 400); } }; window.addEventListener('popstate', () => { if (!window.__isOpeningPanel) { setTimeout(resetVideo, 200); setTimeout(resetVideo, 600); setTimeout(redirectToFirstCheckedIfNeeded, 100); setTimeout(redirectToFirstCheckedIfNeeded, 400); } }); // 定期检查,防止B站自动连播漏掉 setInterval(() => { if (!window.__isOpeningPanel && window.__biliForceStartEnabled) { redirectToFirstCheckedIfNeeded(0); } }, 800); // ========== 5. 列表解析与导航逻辑 ========== // ---- 新版分P列表(__INITIAL_STATE__)兼容 ---- function getInitialStateVideoData() { // 必须用 unsafeWindow 读页面主 world 的全局 JSON(沙箱里 window.__INITIAL_STATE__ 不存在) const g = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const s = g.__INITIAL_STATE__; return (s && s.videoData) || null; } // 判定是否走新版解析:.video-pod__list 首项 data-key 为纯数字(新版分P cid), // 且与页面 JSON 的 pages 同源(bvid 匹配地址栏,防 SPA 陈旧数据) function isNewStyleVideoList() { try { const list = document.querySelector('.video-pod__list'); const first = list && list.firstElementChild; if (!first) return false; const key = first.getAttribute('data-key') || ''; if (!/^\d+$/.test(key)) return false; // 旧版项 data-key=BV… 走旧解析 const vd = getInitialStateVideoData(); const m = location.pathname.match(/\/video\/(BV[0-9a-zA-Z]+)/); const cur = m ? m[1] : ''; return !!(vd && Array.isArray(vd.pages) && vd.pages.length > 0 && cur && vd.bvid === cur); } catch (e) { return false; } } // 秒 → mm:ss function formatSec(sec) { const n = parseInt(sec, 10); if (isNaN(n)) return ''; return Math.floor(n / 60) + ':' + String(n % 60).padStart(2, '0'); } // 新版:由 __INITIAL_STATE__.videoData 重建列表(同BV多分P → 单个 multi 条目,子集 id=BV::i) function buildListFromInitialState() { const vd = getInitialStateVideoData(); if (!vd || !Array.isArray(vd.pages) || !vd.pages.length) return []; const bv = vd.bvid; const title = (vd.title || '').trim() || '未知标题'; const videos = []; if (vd.pages.length === 1) { videos.push({ id: bv, bv: bv, title: title, duration: formatSec(vd.pages[0].duration), isMulti: false, subVideos: [] }); } else { const subVideos = vd.pages.map((p, i) => ({ id: bv + '::' + i, bv: bv, pIndex: i, title: (p.part || '').trim() || ('分P' + (i + 1)), duration: formatSec(p.duration), isSub: true })); videos.push({ id: bv, bv: bv, title: title, duration: formatSec(vd.duration), isMulti: true, subVideos: subVideos, expanded: false }); } return videos; } function getCollectionIdFromPage() { // 新版:整页为同一 BV 的分P列表 → 合集ID = list_ if (isNewStyleVideoList()) { const m = location.pathname.match(/\/video\/(BV[0-9a-zA-Z]+)/); if (m) return 'list_' + m[1]; } const container = document.querySelector('.video-pod__list'); if (container) { const items = container.querySelectorAll('[data-key]'); const bvs = new Set(); items.forEach(el => { const bv = el.getAttribute('data-key'); if (bv && bv.startsWith('BV')) bvs.add(bv); }); if (bvs.size > 0) { return 'list_' + Array.from(bvs).sort().join('|'); } } // 单个视频:从URL获取BV号 const bvMatch = location.href.match(/\/video\/(BV[0-9a-zA-Z]+)/); if (bvMatch) return 'single_' + bvMatch[1]; return null; } function parsePageVideoList() { // 新版:从页面 JSON(__INITIAL_STATE__)重建;旧版走下方原 DOM 逻辑 if (isNewStyleVideoList()) return buildListFromInitialState(); const container = document.querySelector('.video-pod__list'); if (!container) return []; const items = container.querySelectorAll('.pod-item'); const videos = []; items.forEach((item) => { const bv = item.getAttribute('data-key'); if (!bv || !bv.startsWith('BV')) return; const isMulti = item.classList.contains('multi-p'); const titleEl = item.querySelector('.simple-base-item.normal .title-txt, .simple-base-item.head .title-txt, .simple-base-item.active .title-txt'); const durationEl = item.querySelector('.single-p .duration, .multi-p .head .duration'); const title = titleEl ? titleEl.textContent.trim() : '未知标题'; const duration = durationEl ? durationEl.textContent.trim() : ''; if (isMulti) { const pageList = item.querySelector('.page-list'); const subItems = pageList ? pageList.querySelectorAll('.page-item.sub') : []; const subVideos = []; subItems.forEach((sub, subIdx) => { const subTitleEl = sub.querySelector('.title-txt'); const subDurationEl = sub.querySelector('.duration'); subVideos.push({ id: bv + '::' + subIdx, bv: bv, pIndex: subIdx, title: subTitleEl ? subTitleEl.textContent.trim() : '分P' + (subIdx + 1), duration: subDurationEl ? subDurationEl.textContent.trim() : '', isSub: true }); }); videos.push({ id: bv, bv: bv, title: title, duration: duration, isMulti: true, subVideos: subVideos, expanded: false }); } else { videos.push({ id: bv, bv: bv, title: title, duration: duration, isMulti: false, subVideos: [] }); } }); return videos; } function restoreFromMemoryList(listName, videoData) { const memory = getMemoryList(); let matchedKey = null; for (const key in memory) { if (memory[key] && memory[key][0] === listName) { matchedKey = key; break; } } if (!matchedKey) return { checkedSet: null, forceFromStart: false }; const entry = memory[matchedKey]; const bitmap = entry.length === 2 ? entry[1] : entry[2]; const force = entry.length >= 3 ? entry[1] : false; const checkedSet = new Set(); let idx = 0; for (const v of videoData) { if (v.isMulti && v.subVideos.length > 0) { for (const sv of v.subVideos) { if (idx < bitmap.length && bitmap[idx] === '1') checkedSet.add(sv.id); idx++; } } else { if (idx < bitmap.length && bitmap[idx] === '1') checkedSet.add(v.id); idx++; } } return { checkedSet, forceFromStart: force }; } function updateMemoryListFromCheckedSet() { const listName = getListName(); const memory = getMemoryList(); let existingKey = null; for (const key in memory) { if (memory[key] && memory[key][0] === listName) { existingKey = key; break; } } let bitmap = ''; for (const v of panelState.videoData) { if (v.isMulti && v.subVideos.length > 0) { for (const sv of v.subVideos) bitmap += panelState.checkedSet.has(sv.id) ? '1' : '0'; } else bitmap += panelState.checkedSet.has(v.id) ? '1' : '0'; } const newEntry = [listName, panelState.forceFromStart, bitmap]; if (existingKey) { memory[existingKey] = newEntry; } else { const keys = Object.keys(memory); const newKey = 'l' + (keys.length + 1); memory[newKey] = newEntry; } saveMemoryList(memory); window.__biliForceStartEnabled = panelState.forceFromStart; return true; } function getCheckedIdsFromMemoryList(listName, videoData) { const memory = getMemoryList(); let matchedKey = null; for (const key in memory) { if (memory[key] && memory[key][0] === listName) { matchedKey = key; break; } } if (!matchedKey) return []; const entry = memory[matchedKey]; const bitmap = entry.length === 2 ? entry[1] : entry[2]; const ids = []; let idx = 0; for (const v of videoData) { if (v.isMulti && v.subVideos.length > 0) { for (const sv of v.subVideos) { if (idx < bitmap.length && bitmap[idx] === '1') ids.push(sv.id); idx++; } } else { if (idx < bitmap.length && bitmap[idx] === '1') ids.push(v.id); idx++; } } return ids; } // 合集key解析:页面BV签名与已存合集高度重叠(Jaccard≥0.6)时视为同一合集, // 避免选集框因推荐/页面状态微变BV列表后,保存另建新档而非更新原合集 function resolveCollectionKey(cid) { if (!cid || cid.indexOf('single_') === 0) return cid; const data = getAllData(); if (Array.isArray(data[cid])) return cid; // 精确命中 const cur = collectionKeyToBvs(cid); if (cur.length < 2) return cid; const curSet = new Set(cur); let bestKey = null, bestScore = 0; for (const k in data) { if (k === cid || k.indexOf('_') < 0 || !Array.isArray(data[k])) continue; if (k.indexOf('single_') === 0) continue; const oldSet = new Set(collectionKeyToBvs(k)); if (!oldSet.size) continue; let inter = 0; curSet.forEach(b => { if (oldSet.has(b)) inter++; }); const jac = inter / (oldSet.size + curSet.size - inter); if (jac > bestScore) { bestScore = jac; bestKey = k; } } return (bestKey && bestScore >= 0.6) ? bestKey : cid; } function getListForCurrentCollection() { // 偏好播放模式:偏好列表条目优先(onVideoEnded 连播 / 拦截判定 均走这里) const ap = getActivePreferId(); if (ap) { const pl = findPreferList(ap); if (pl && pl.items.length) return pl.items.map(i => i.id); if (!pl) setActivePreferId(null); // 列表已被删除:退出偏好模式 } const listName = getListName(); const videoData = panelState.videoData.length ? panelState.videoData : parsePageVideoList(); const ids = getCheckedIdsFromMemoryList(listName, videoData); if (ids.length > 0) return ids; const cid = resolveCollectionKey(getCollectionIdFromPage()); if (!cid) return []; const data = getAllData(); return Array.isArray(data[cid]) ? data[cid] : []; } function saveListForCurrentCollection(list) { const cid = resolveCollectionKey(getCollectionIdFromPage()); if (!cid) return false; const data = getAllData(); data[cid] = list; saveAllData(data); recordCollectionName(cid, grabCollectionTitle()); // 顺手记下合集标题 return true; } function getCurrentBVID() { const match = location.pathname.match(/BV[0-9A-Za-z]+/); return match ? match[0] : null; } // 当前 BV 是否在脚本已知数据中(已存合集 / 偏好列表 / 观看记录缓存)。 // 完全陌生的视频(没看过、不属于任何已存合集、不在偏好)= 用户主动的新访问, // 不属于任何播放流转,强制拦截不应把它拽回列表第一项 function isVideoInKnownData(bv) { if (!bv) return false; try { // 偏好列表收录 if (getPreferLists().some(l => (l.items || []).some(i => i.id === bv || i.id.indexOf(bv + '::') === 0))) return true; // 已存合集(v3):key 自带 BV 集合 const data = getAllData(); for (const k in data) { if (Array.isArray(data[k]) && collectionKeyToBvs(k).indexOf(bv) >= 0) return true; } // 观看记录缓存(面板/偏好视图加载过的 4.js 数据)里出现过 = 看过 if (preferRecsCache && preferRecsCache.some(r => r && r.id === bv)) return true; if (viewCountsCache.data && viewCountsCache.data[bv]) return true; } catch (e) {} return false; } function getCurrentPIndex() { const params = new URLSearchParams(location.search); const p = params.get('p'); return p ? parseInt(p) - 1 : 0; } function navigateToVideo(bv, pIndex) { if (!bv) return; // 非视频页(首页/搜索页等)pathname 没有 BV 可替换,SPA 改写会得到错误 URL,直接整页跳转 if (!/\/video\/BV/.test(location.pathname)) { location.href = 'https://www.bilibili.com/video/' + bv + (pIndex !== null && pIndex !== undefined ? '?p=' + (pIndex + 1) : ''); return; } let newPath = location.pathname.replace(/BV[0-9A-Za-z]+/, bv); const params = new URLSearchParams(location.search); if (pIndex !== null && pIndex !== undefined) params.set('p', pIndex + 1); else params.delete('p'); params.delete('t'); const search = params.toString() ? '?' + params.toString() : ''; const newUrl = newPath + search + (location.hash || ''); if (newUrl === location.href) return; window.history.pushState({}, '', newUrl); window.dispatchEvent(new PopStateEvent('popstate')); } function hijackVisibility() { try { Object.defineProperty(document, 'hidden', { configurable: true, get: () => false }); } catch(e){} try { Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' }); } catch(e){} const block = (e) => e.stopImmediatePropagation(); document.addEventListener('visibilitychange', block, true); window.addEventListener('visibilitychange', block, true); } function checkAndHijack() { // 每次进入新的视频页(含 SPA 导航/切P),重置归零窗口和「已归零」标记 window.__forceZeroDeadline = Date.now() + FORCE_ZERO_WINDOW_MS; window.__forceZeroDone = false; const bv = getCurrentBVID(); if (!bv) return; // 偏好播放模式:只按偏好列表拦截/跳回,不走普通合集的 memory 跳转(两者条目可能完全不同) const ap = getActivePreferId(); if (ap) { const pl = findPreferList(ap); const ids = pl ? pl.items.map(i => i.id) : []; if (ids.length) { const inList = ids.some(id => matchListEntry(id, bv, getCurrentPIndex())); if (inList) { hijackVisibility(); // 强制拦截仅在视频至少与脚本数据有关联时生效(在偏好/已存合集/看过的范围里走丢才拉回); // 完全不在数据中的陌生视频是用户主动访问,直接放行 } else if (window.__biliForceStartEnabled && !window.__isOpeningPanel && isVideoInKnownData(bv)) { const firstId = ids[0]; const firstBv = firstId.includes('::') ? firstId.split('::')[0] : firstId; const firstP = firstId.includes('::') ? parseInt(firstId.split('::')[1]) : null; setTimeout(() => navigateToVideo(firstBv, firstP), 500); showToast('⭐ 已回到偏好列表第一项'); } // 面板开着且在偏好视图:刷新渲染,让「正在播放」高亮跟随切P/切视频实时更新 if (panelState.open) { const d = document.getElementById('bili-force-drawer'); if (d && d.classList.contains('mode-prefer')) renderPreferView(); } } return; } const memory = getMemoryList(); const videoData = panelState.videoData.length ? panelState.videoData : parsePageVideoList(); let found = false; let listIds = []; for (const key in memory) { const entry = memory[key]; const bitmap = entry.length === 2 ? entry[1] : entry[2]; const force = entry.length >= 3 ? entry[1] : false; let idx = 0; const ids = []; for (const v of videoData) { if (v.isMulti && v.subVideos.length > 0) { for (const sv of v.subVideos) { if (idx < bitmap.length && bitmap[idx] === '1') { ids.push(sv.id); if (sv.bv === bv) found = true; } idx++; } } else { if (idx < bitmap.length && bitmap[idx] === '1') { ids.push(v.id); if (v.bv === bv) found = true; } idx++; } } // 如果开启了强制从头播放,且当前视频不在勾选列表里,自动跳转到第一个勾选视频 if (force && ids.length > 0 && !found) { const currentP = getCurrentPIndex(); // 再精确检查一次:当前BV+P是否在列表里 let exactFound = false; for (const id of ids) { if (matchListEntry(id, bv, currentP)) { exactFound = true; break; } } if (!exactFound && !window.__isOpeningPanel && isVideoInKnownData(bv)) { const firstId = ids[0]; const firstBv = firstId.includes('::') ? firstId.split('::')[0] : firstId; const firstP = firstId.includes('::') ? parseInt(firstId.split('::')[1]) : null; window.__biliForceStartEnabled = true; setTimeout(() => navigateToVideo(firstBv, firstP), 500); showToast('🎬 已跳转到选定列表第一首'); return; } } if (ids.length > 0) listIds = ids; } if (found) { hijackVisibility(); } } function onVideoEnded(e) { const video = e.target; if (!video.closest('#bilibili-player') && !video.closest('.bpx-player-video-wrap')) return; const currentBv = getCurrentBVID(); const currentP = getCurrentPIndex(); if (!currentBv) return; const list = getListForCurrentCollection(); if (list.length === 0) return; if (!window.__biliForceStartEnabled) return; let currentIndex = -1; for (let i = 0; i < list.length; i++) { if (matchListEntry(list[i], currentBv, currentP)) { currentIndex = i; break; } } // 无论当前在不在列表里,都跳转到下一个勾选;如果是最后一个,回到第一个循环 e.stopImmediatePropagation(); e.preventDefault(); let nextIndex; if (currentIndex >= 0 && currentIndex < list.length - 1) { nextIndex = currentIndex + 1; } else { // 不在列表里 或者 已经是最后一个 → 回到第一个循环 nextIndex = 0; showToast('🔁 列表播放完毕,回到第一首循环'); } const nextId = list[nextIndex]; const nextBv = nextId.includes('::') ? nextId.split('::')[0] : nextId; const nextPIndex = nextId.includes('::') ? parseInt(nextId.split('::')[1]) : null; setTimeout(() => navigateToVideo(nextBv, nextPIndex), 200); } function setupVideoEndListener() { document.addEventListener('ended', onVideoEnded, true); } // ========== 6. 主题切换与样式注入 ========== function applyTheme(theme) { const drawer = document.getElementById('bili-force-drawer'); const trigger = document.getElementById('bili-force-trigger'); if (drawer) { if (theme === 'dark') { drawer.classList.add('dark'); } else { drawer.classList.remove('dark'); } applyCurrentBg(); } if (trigger) { if (theme === 'dark') { trigger.classList.add('dark'); } else { trigger.classList.remove('dark'); } } } function toggleThemeManual() { const current = getTheme(); const next = current === 'dark' ? 'light' : 'dark'; saveTheme(next); applyTheme(next); updateThemeToggleUI(); showToast(next === 'dark' ? '🌙 已切换暗色主题' : '☀️ 已切换浅色主题'); } function updateThemeToggleUI() { const followSwitch = document.getElementById('theme-follow-switch'); const toggleBtn = document.querySelector('.btn-theme-toggle'); if (followSwitch) { followSwitch.classList.toggle('active', getThemeFollow()); } if (toggleBtn) { const isFollow = getThemeFollow(); toggleBtn.style.display = isFollow ? 'none' : 'inline-block'; const currentTheme = getTheme(); toggleBtn.textContent = currentTheme === 'dark' ? '☀️ 亮色' : '🌙 暗色'; } } function toggleThemeFollow() { const currentFollow = getThemeFollow(); const nextFollow = !currentFollow; saveThemeFollow(nextFollow); applyTheme(getTheme()); updateThemeToggleUI(); showToast(nextFollow ? '🔄 已开启跟随页面明暗' : '✋ 已关闭跟随,可手动切换'); } function setupThemeListener() { let lastDetectedTheme = getBilibiliTheme(); applyTheme(getTheme()); updateThemeToggleUI(); // 定期检测主题变化(核心手段) setInterval(() => { if (!getThemeFollow()) return; const currentTheme = getBilibiliTheme(); if (currentTheme !== lastDetectedTheme) { lastDetectedTheme = currentTheme; applyTheme(currentTheme); updateThemeToggleUI(); } }, 1000); } function injectStyles() { const styleId = 'bili-force-drawer-styles'; if (document.getElementById(styleId)) return; const style = document.createElement('style'); style.id = styleId; style.textContent = ` #bili-force-trigger { position: fixed; z-index: 99999; background: #fb7299; color: #fff; padding: 8px 14px; border-radius: 999px; cursor: grab; font-size: 13px; display: flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(251,114,153,0.3); user-select: none; transition: left 0.25s ease, right 0.25s ease, transform 0.25s, box-shadow 0.2s, opacity 0.2s; } #bili-force-trigger:active { cursor: grabbing; transform: scale(1.05); box-shadow: 0 4px 12px rgba(251,114,153,0.4); transition: transform 0.2s, box-shadow 0.2s; } /* 吸附边缘:只露出一个半圆头(18px),hover 平滑滑出 */ #bili-force-trigger.snap-hidden { opacity: 0.6; } #bili-force-trigger.snap-hidden:hover { opacity: 1; } #bili-force-trigger.snap-left { left: 0 !important; right: auto !important; transform: translateX(calc(-100% + 18px)); } #bili-force-trigger.snap-right { right: 0 !important; left: auto !important; transform: translateX(calc(100% - 18px)); } #bili-force-trigger.snap-left:hover { left: 0 !important; transform: translateX(0); } #bili-force-trigger.snap-right:hover { right: 0 !important; transform: translateX(0); } /* 面板打开时完全隐藏按钮,关闭后恢复 */ #bili-force-trigger.panel-open { opacity: 0; pointer-events: none; } #bili-force-trigger.dark { background: #fb7299; color: #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.4); } #bili-force-trigger.dark.snap-hidden { opacity: 0.7; } #bili-force-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.3); z-index: 99998; opacity: 0; visibility: hidden; transition: all 0.3s; } #bili-force-overlay.active { opacity: 1; visibility: visible; } #bili-force-drawer { position: fixed; right: -400px; top: 0; width: 380px; height: 100vh; z-index: 99999; transition: right 0.3s ease; display: flex; flex-direction: column; box-shadow: -2px 0 16px rgba(0,0,0,0.15), -8px 0 40px rgba(0,0,0,0.1), inset 1px 0 0 rgba(0,0,0,0.08); overflow: hidden; } #bili-force-drawer.active { right: 0; } /* 暗色主题 */ #bili-force-drawer.dark { color: #e0e0e0; box-shadow: -2px 0 16px rgba(0,0,0,0.4), -8px 0 40px rgba(0,0,0,0.3), inset 1px 0 0 rgba(255,255,255,0.07); } #bili-force-drawer.dark .action-btn { background: #333; border-color: #444; color: #e0e0e0; } #bili-force-drawer.dark .action-btn:hover { background: #444; } #bili-force-drawer.dark .btn-save { background: #fb7299; border-color: #fb7299; color: #fff; } #bili-force-drawer.dark .btn-save:hover { background: #ff85a8; } #bili-force-drawer.dark .video-item:hover { background: #2a2a2a; } #bili-force-drawer.dark .video-item.current-playing { background: #2d1f24; border-left-color: #fb7299; } #bili-force-drawer.dark .bv-tag, #bili-force-drawer.dark .video-meta { color: #888; } #bili-force-drawer.dark .drawer-close { color: #999; } .drawer-header { padding: 12px; border-bottom: 1px solid #eee; flex-shrink: 0; background: rgba(255,255,255,0.7); position: relative; z-index: 2; } #bili-force-drawer.dark .drawer-header { background: rgba(30,30,30,0.7); border-bottom-color: #333; } .header-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; } .drawer-title { font-size: 16px; font-weight: 600; } .drawer-close { border: none; background: none; font-size: 18px; cursor: pointer; color: #666; } .header-actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; } .action-btn { padding: 4px 9px; border: 1px solid #ddd; background: #f5f5f5; border-radius: 6px; cursor: pointer; font-size: 12px; line-height: 1.5; transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease; } .action-btn:hover { background: #eee; } .btn-save, .btn-collections-main { margin-left: auto; background: #fb7299; border-color: #fb7299; color: #fff; } /* 方案A:选择操作下拉化,四个按钮一行排齐 */ .header-actions { flex-wrap: nowrap; } .header-actions .btn-collections-main { margin-left: 0; } .select-dropdown { position: relative; display: inline-block; } .select-dropdown .select-menu { display: none; position: absolute; top: calc(100% + 4px); left: 0; min-width: 96px; background: #fff; color: #333; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 4px 16px rgba(0,0,0,0.18); padding: 4px; z-index: 50; } #bili-force-drawer.dark .select-dropdown .select-menu { background: #2a2a2a; color: #e0e0e0; border-color: #444; } .select-dropdown.open .select-menu { display: block; } .sm-row { display: block; padding: 7px 12px; font-size: 12px; border-radius: 6px; cursor: pointer; white-space: nowrap; } .sm-row:hover { background: rgba(251,114,153,0.12); } .btn-save:hover, .btn-collections-main:hover { background: #ff85a8; } /* 设置行:开关 + 计数合并为一行 */ .header-settings { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 8px; border-top: 1px solid rgba(128,128,128,0.18); font-size: 12px; color: #666; } #bili-force-drawer.dark .header-settings { color: #aaa; border-top-color: rgba(255,255,255,0.12); } .set-item { display: inline-flex; align-items: center; gap: 6px; } .btn-theme-toggle { padding: 3px 8px !important; font-size: 12px !important; } .switch-track { width: 34px; height: 18px; background: #ccc; border-radius: 9px; position: relative; cursor: pointer; transition: background 0.2s; flex-shrink: 0; } .switch-track.active { background: #fb7299; } .switch-track::before { content: ''; position: absolute; left: 2px; top: 2px; width: 14px; height: 14px; background: #fff; border-radius: 50%; transition: left 0.2s; } .switch-track.active::before { left: 18px; } .list-info { margin-left: auto; font-size: 12px; color: #666; } #bili-force-drawer.dark .list-info { color: #aaa; } /* ===== 工具栏/多合集阅览 ===== */ .header-right { display: flex; align-items: center; gap: 8px; } /* list / collections 双模式 */ #bili-force-drawer.mode-collections .list-only { display: none !important; } .collections-view { display: none; } #bili-force-drawer .collections-view { background: rgba(255,255,255,0.55); padding: 0 16px 12px; /* 关键:必须高于 drawer-bg-layer(0) 和 drawer-bg-mask(1),否则被不透明遮罩盖住 */ position: relative; z-index: 2; } #bili-force-drawer.dark .collections-view { background: rgba(24,24,24,0.6); } #bili-force-drawer.mode-collections .collections-view { display: flex; flex-direction: column; flex: 1; min-height: 0; } .collections-view .collections-head { display: flex; align-items: center; justify-content: space-between; padding: 6px 2px 10px; font-size: 12px; color: #666; } #bili-force-drawer.dark .collections-view .collections-head { color: #aaa; } .collections-view .collections-list { flex: 1; overflow-y: auto; min-height: 0; } .collection-item { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border: 1px solid rgba(0,0,0,0.06); border-radius: 8px; margin-bottom: 8px; cursor: pointer; background: rgba(255,255,255,0.5); transition: background 0.2s ease, border-color 0.2s ease; position: relative; user-select: none; -webkit-user-select: none; } /* 长按删除:条目闪红 + 只显示「删除中」+ 右→左进度条 */ .collection-item .ci-del-mask { display: none; position: absolute; inset: 0; z-index: 3; align-items: center; justify-content: center; font-size: 12px; font-weight: 600; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,0.35); border-radius: inherit; overflow: hidden; pointer-events: none; } .collection-item.del-arming .ci-del-mask { display: flex; animation: ci-blink-red 0.8s ease-in-out infinite; } .collection-item.del-arming > *:not(.ci-del-mask) { visibility: hidden; } .collection-item .ci-del-bar { position: absolute; right: 0; bottom: 0; height: 4px; width: 100%; background: #ff4d4f; border-radius: 2px 0 0 2px; } @keyframes ci-blink-red { 0%, 100% { background: rgba(220,38,38,0.2); } 50% { background: rgba(220,38,38,0.55); } } #bili-force-drawer.dark .collection-item { background: rgba(40,40,40,0.6); border-color: rgba(255,255,255,0.08); } .collection-item:hover { background: rgba(255,255,255,0.9); border-color: #fb7299; } #bili-force-drawer.dark .collection-item:hover { background: rgba(60,60,60,0.8); border-color: #fb7299; } .collection-item .ci-badge { flex-shrink: 0; font-size: 11px; padding: 2px 8px; border-radius: 10px; background: rgba(251,114,153,0.15); color: #fb7299; white-space: nowrap; } #bili-force-drawer.dark .collection-item .ci-badge { background: rgba(251,114,153,0.22); color: #ff9db8; } .collection-item .ci-main { flex: 1; min-width: 0; } .collection-item .ci-name { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .collection-item .ci-meta { font-size: 11px; color: #999; margin-top: 2px; } #bili-force-drawer.dark .collection-item .ci-meta { color: #888; } .collection-item .ci-last { flex-shrink: 0; font-size: 11px; color: #999; white-space: nowrap; } #bili-force-drawer.dark .collection-item .ci-last { color: #888; } .collection-empty { padding: 30px 10px; text-align: center; color: #888; font-size: 13px; } .drawer-body { flex: 1; overflow-y: auto; padding: 8px 0; position: relative; z-index: 1; background: transparent; } /* 旧伪元素背景已废弃,改用真实DOM .drawer-bg-layer */ .video-item { display: flex; align-items: center; padding: 8px 16px; gap: 8px; cursor: pointer; font-size: 13px; position: relative; z-index: 1; transition: background 0.2s ease; } .video-item:hover { background: rgba(245,245,245,0.8); } #bili-force-drawer.dark .video-item:hover { background: rgba(42,42,42,0.8); } .video-item.current-playing { background: rgba(255,240,243,0.9); border-left: 3px solid #fb7299; } #bili-force-drawer.dark .video-item.current-playing { background: rgba(45,31,36,0.9); border-left-color: #fb7299; } .video-item.sub-item { padding-left: 36px; font-size: 12px; } .expand-icon { width: 16px; text-align: center; color: #999; font-size: 10px; } .expand-icon.expanded { transform: rotate(90deg); } .checkbox-wrap { flex-shrink: 0; } .video-info { flex: 1; min-width: 0; } .video-title { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .video-meta { font-size: 11px; color: #999; margin-top: 2px; display: flex; gap: 10px; } .bv-tag { flex-shrink: 0; font-size: 11px; color: #999; font-family: monospace; } .drawer-footer { padding: 12px 16px; border-top: 1px solid #eee; display: flex; gap: 10px; flex-shrink: 0; background: rgba(255,255,255,0.7); position: relative; z-index: 2; } #bili-force-drawer.dark .drawer-footer { background: rgba(30,30,30,0.7); border-top-color: #333; } .drawer-footer .action-btn { flex: 1; padding: 8px; } .btn-save { background: #fb7299; color: #fff; border-color: #fb7299; } .btn-save:hover { background: #ff85a8; } /* ===== 偏好列表(PreferList) ===== */ #bili-force-drawer.mode-prefer .list-only { display: none !important; } #bili-force-drawer.mode-prefer .collections-view { display: none !important; } .prefer-view { display: none; } #bili-force-drawer .prefer-view { background: rgba(255,255,255,0.55); padding: 8px 16px 12px; position: relative; z-index: 2; } #bili-force-drawer.dark .prefer-view { background: rgba(24,24,24,0.6); } #bili-force-drawer.mode-prefer .prefer-view { display: flex; flex-direction: column; flex: 1; min-height: 0; } .prefer-view .prefer-head { display: flex; align-items: center; justify-content: space-between; padding: 6px 2px 10px; font-size: 12px; color: #666; } #bili-force-drawer.dark .prefer-view .prefer-head { color: #aaa; } .prefer-body { flex: 1; overflow-y: auto; min-height: 0; } @keyframes biliPreferHit { 0%, 100% { background: transparent; box-shadow: none; } 50% { background: rgba(255, 105, 180, 0.38); box-shadow: 0 0 8px rgba(255, 105, 180, 0.55); } } #bili-force-drawer .prefer-hit-flash { animation: biliPreferHit 0.8s ease-in-out 3; border-radius: 6px; } .prefer-empty { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; cursor: pointer; min-height: 220px; } .prefer-empty .pe-plus { font-size: 64px; font-weight: 200; line-height: 1; color: #b5b5b5; transition: transform 0.15s, color 0.15s; } .prefer-empty:hover .pe-plus { transform: scale(1.15); color: #fb7299; } .prefer-empty .pe-tip { margin-top: 10px; font-size: 12px; color: #999; text-align: center; } .prefer-row { display: flex; flex-direction: column; /* 两行结构:pr-line1 名称行 / pr-line2 记录+按钮行,纵向堆叠 */ align-items: stretch; gap: 0; padding: 10px 12px; border: 1px solid rgba(0,0,0,0.06); border-radius: 8px; margin-bottom: 8px; background: rgba(255,255,255,0.5); cursor: pointer; position: relative; user-select: none; -webkit-user-select: none; } #bili-force-drawer.dark .prefer-row { background: rgba(40,40,40,0.6); border-color: rgba(255,255,255,0.08); } .prefer-row:hover { border-color: #fb7299; } /* 正在播放的偏好列表:置顶后持续高亮(非 hover 一次性) */ .prefer-row.playing { border-color: #fb7299; background: rgba(251,114,153,0.10); box-shadow: inset 3px 0 0 #fb7299; } #bili-force-drawer.dark .prefer-row.playing { background: rgba(251,114,153,0.16); } /* 「表头」吸顶:上次(或正在)播放列表的名称+按钮行固定在滚动区顶部 */ .prefer-row.sticky-head { position: sticky; top: 0; z-index: 6; background: rgba(255,255,255,0.97); } #bili-force-drawer.dark .prefer-row.sticky-head { background: rgba(30,30,30,0.97); } .prefer-row.sticky-head.playing { background: rgba(255,240,244,0.97); } #bili-force-drawer.dark .prefer-row.sticky-head.playing { background: rgba(45,31,36,0.97); } /* 展开后上次播放到的条目:蓝色标签(正在播放的条目复用全局 .current-playing 粉色) */ .prefer-items .video-item.last-play { border-left: 3px solid #00a1d6; background: rgba(0,161,214,0.10); } .prefer-items .video-item.last-play .lp-tag { flex-shrink: 0; display: inline-block; font-size: 10px; line-height: 1; padding: 3px 7px; border-radius: 9px; background: rgba(0,161,214,0.16); color: #00a1d6; font-weight: 600; } #bili-force-drawer.dark .prefer-items .video-item.last-play .lp-tag { background: rgba(0,161,214,0.28); color: #6cc9ff; } /* 正在播放的条目:粉色「正在播放」标签(有播放时替代「上次」标签) */ .prefer-items .video-item .lp-tag.now { background: rgba(251,114,153,0.16); color: #fb7299; } #bili-force-drawer.dark .prefer-items .video-item .lp-tag.now { background: rgba(251,114,153,0.26); color: #ff9db8; } .prefer-row .pr-line1 { display: flex; align-items: center; gap: 8px; min-width: 0; } .prefer-row .pr-line2 { display: flex; align-items: center; gap: 6px; margin-top: 6px; padding-left: 22px; min-width: 0; } .prefer-row .pr-name { flex: 1; min-width: 0; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .prefer-row .pr-meta { flex-shrink: 0; font-size: 11px; color: #999; } .prefer-row .pr-last { flex: 1; min-width: 0; font-size: 11px; color: #999; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .prefer-row .pr-line2 .action-btn { margin-left: 0; } .prefer-row .pr-line2 .action-btn:first-of-type { margin-left: auto; } .prefer-row .action-btn { flex-shrink: 0; padding: 2px 7px; font-size: 11px; } .prefer-row .ci-del-mask { display: none; position: absolute; inset: 0; z-index: 3; align-items: center; justify-content: center; font-size: 12px; font-weight: 600; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,0.35); border-radius: inherit; overflow: hidden; pointer-events: none; } .prefer-row.del-arming .ci-del-mask { display: flex; animation: ci-blink-red 0.8s ease-in-out infinite; } .prefer-row.del-arming > *:not(.ci-del-mask) { visibility: hidden; } .prefer-row .ci-del-bar { position: absolute; right: 0; bottom: 0; height: 4px; width: 100%; background: #ff4d4f; border-radius: 2px 0 0 2px; } .prefer-items { margin-bottom: 8px; } .prefer-items .video-item { background: rgba(255,255,255,0.4); border-radius: 6px; padding: 6px 10px 6px 30px; margin-bottom: 4px; } #bili-force-drawer.dark .prefer-items .video-item { background: rgba(40,40,40,0.45); } .star-btn { flex-shrink: 0; cursor: pointer; font-size: 15px; line-height: 1; opacity: 0.55; user-select: none; transition: transform 0.15s, opacity 0.15s; } .star-btn:hover { opacity: 1; transform: scale(1.2); } .star-btn.active { opacity: 1; } /* ⭐ 迷你选择浮层 */ #bili-prefer-pop { position: fixed; z-index: 100001; background: #fff; color: #333; border: 1px solid #e5e5e5; border-radius: 8px; box-shadow: 0 4px 16px rgba(0,0,0,0.18); padding: 4px; min-width: 150px; font-size: 12px; } #bili-prefer-pop.dark { background: #2a2a2a; color: #e0e0e0; border-color: #444; } #bili-prefer-pop .pp-row { display: flex; align-items: center; gap: 6px; padding: 7px 10px; border-radius: 6px; cursor: pointer; white-space: nowrap; } #bili-prefer-pop .pp-row:hover { background: rgba(251,114,153,0.12); } #bili-prefer-pop .pp-new { color: #fb7299; border-top: 1px solid rgba(128,128,128,0.2); margin-top: 2px; } #bili-force-toast { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0.9); background: rgba(0,0,0,0.75); color: #fff; padding: 10px 20px; border-radius: 6px; z-index: 100000; opacity: 0; visibility: hidden; transition: all 0.2s; font-size: 14px; } #bili-force-toast.show { opacity: 1; visibility: visible; transform: translate(-50%, -50%) scale(1); } `; document.head.appendChild(style); } // ========== 7. 按钮拖拽吸附(优化版) ========== function bindDragBehavior(trigger) { let isDragging = false; let hasMoved = false; let startX = 0, startY = 0; let startLeft = 0, startTop = 0; let lastSnapSide = getTriggerPos().side; function applySnap(side) { trigger.classList.remove('snap-left', 'snap-right', 'snap-hidden'); if (side === 'left') { trigger.classList.add('snap-left', 'snap-hidden'); } else { trigger.classList.add('snap-right', 'snap-hidden'); } lastSnapSide = side; } function onStart(e) { const point = e.touches ? e.touches[0] : e; isDragging = true; hasMoved = false; startX = point.clientX; startY = point.clientY; // 拖拽时移除吸附状态 trigger.classList.remove('snap-left', 'snap-right', 'snap-hidden'); const rect = trigger.getBoundingClientRect(); startLeft = rect.left; startTop = rect.top; // 统一使用 left 定位 trigger.style.left = startLeft + 'px'; trigger.style.right = 'auto'; document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onEnd); document.addEventListener('touchmove', onMove, { passive: false }); document.addEventListener('touchend', onEnd); } function onMove(e) { if (!isDragging) return; e.preventDefault(); const point = e.touches ? e.touches[0] : e; const dx = point.clientX - startX; const dy = point.clientY - startY; if (Math.abs(dx) > 3 || Math.abs(dy) > 3) hasMoved = true; let newLeft = startLeft + dx; let newTop = startTop + dy; const btnWidth = trigger.offsetWidth; const btnHeight = trigger.offsetHeight; newLeft = Math.max(-40, Math.min(window.innerWidth - btnWidth + 40, newLeft)); newTop = Math.max(0, Math.min(window.innerHeight - btnHeight, newTop)); trigger.style.left = newLeft + 'px'; trigger.style.top = newTop + 'px'; } function onEnd() { isDragging = false; document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onEnd); document.removeEventListener('touchmove', onMove); document.removeEventListener('touchend', onEnd); if (!hasMoved) { // 只是点击没有拖拽,恢复之前的吸附状态 applySnap(lastSnapSide); return; } const rect = trigger.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const viewportHalf = window.innerWidth / 2; const posData = { top: rect.top }; if (centerX < viewportHalf) { trigger.style.left = '0px'; trigger.style.right = 'auto'; posData.side = 'left'; posData.left = 0; applySnap('left'); } else { trigger.style.left = 'auto'; trigger.style.right = '0px'; posData.side = 'right'; posData.right = 0; applySnap('right'); } saveTriggerPos(posData); } trigger.addEventListener('click', (e) => { if (hasMoved) { e.stopPropagation(); e.preventDefault(); hasMoved = false; } }, true); trigger.addEventListener('mousedown', onStart); trigger.addEventListener('touchstart', onStart, { passive: false }); // 从存储恢复位置 const savedPos = getTriggerPos(); trigger.style.top = savedPos.top + 'px'; if (savedPos.side === 'left') { trigger.style.left = '0px'; trigger.style.right = 'auto'; applySnap('left'); } else { trigger.style.left = 'auto'; trigger.style.right = '0px'; applySnap('right'); } // 窗口大小变化时修正位置 function handleResize() { const rect = trigger.getBoundingClientRect(); const btnHeight = trigger.offsetHeight; let newTop = rect.top; newTop = Math.max(0, Math.min(window.innerHeight - btnHeight, newTop)); trigger.style.top = newTop + 'px'; const posData = getTriggerPos(); posData.top = newTop; saveTriggerPos(posData); } window.addEventListener('resize', handleResize); } // ========== 8. UI 构建 ========== function createToast() { let toast = document.getElementById('bili-force-toast'); if (!toast) { toast = document.createElement('div'); toast.id = 'bili-force-toast'; document.body.appendChild(toast); } return toast; } function showToast(msg, duration = 2000) { const toast = createToast(); toast.textContent = msg; toast.classList.add('show'); clearTimeout(toast._timeout); toast._timeout = setTimeout(() => toast.classList.remove('show'), duration); } function createTriggerButton() { let trigger = document.getElementById('bili-force-trigger'); if (trigger && document.body.contains(trigger)) return trigger; if (trigger) trigger.remove(); trigger = document.createElement('div'); trigger.id = 'bili-force-trigger'; trigger.innerHTML = `列表管理`; document.body.appendChild(trigger); bindDragBehavior(trigger); return trigger; } function createOverlay() { let overlay = document.getElementById('bili-force-overlay'); if (!overlay) { overlay = document.createElement('div'); overlay.id = 'bili-force-overlay'; document.body.appendChild(overlay); } return overlay; } function createDrawer() { let drawer = document.getElementById('bili-force-drawer'); if (!drawer) { drawer = document.createElement('div'); drawer.id = 'bili-force-drawer'; drawer.innerHTML = `
📋 播放列表管理
全选 反选 取消全选
跟随页面明暗 强制从头播放 已勾选 0 个
已记录 0 个合集
共 0 个
`; document.body.appendChild(drawer); applyTheme(getTheme()); applyCurrentBg(); } return drawer; } let panelState = { open: false, videoData: [], checkedSet: new Set(), expandedMultis: new Set(), preferExpanded: new Set(), forceFromStart: false }; function updateForceSwitchUI() { const track = document.getElementById('force-start-switch'); if (track) track.classList.toggle('active', panelState.forceFromStart); } // ====================== 观看次数统计(读取 4.js 的 IndexedDB) ====================== const viewCountsCache = { data: null, ts: 0 }; // 优先使用 4.js 暴露的接口,否则直接读同一 IndexedDB(同源可用)兜底 function readViewCountDBDirect() { return new Promise(resolve => { try { const req = indexedDB.open('BiliViewCountDB'); req.onsuccess = () => { try { const tx = req.result.transaction('views', 'readonly'); const getAll = tx.objectStore('views').getAll(); getAll.onsuccess = () => { const map = {}; getAll.result.forEach(r => { map[r.id] = r.times; }); resolve(map); }; getAll.onerror = () => resolve(null); } catch (e) { resolve(null); } }; req.onerror = () => resolve(null); } catch (e) { resolve(null); } }); } async function loadViewCounts(force) { const now = Date.now(); if (!force && viewCountsCache.data && now - viewCountsCache.ts < 60000) return viewCountsCache.data; let data = null; const _g = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; if (typeof _g.__biliViewCountGetAll === 'function') { try { data = await _g.__biliViewCountGetAll(); } catch (e) { data = null; } } if (!data) data = await readViewCountDBDirect(); if (data) { viewCountsCache.data = data; viewCountsCache.ts = now; } return viewCountsCache.data; } function getTimesHtml(bvList) { const vc = viewCountsCache.data; if (!vc) return ''; const sum = bvList.reduce((s, bv) => s + (vc[bv] || 0), 0); return sum > 0 ? `🔁 ${sum}` : ''; } function renderVideoList() { const drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; const body = drawer.querySelector('.drawer-body'); if (!body) return; const currentBv = getCurrentBVID(); const currentP = getCurrentPIndex(); const videoData = panelState.videoData; // 本轮渲染的偏好命中集合(一次性收集,避免每行重复解析存储) const preferIdSet = new Set(); getPreferLists().forEach(l => (l.items || []).forEach(i => preferIdSet.add(i.id))); let html = ''; if (videoData.length === 0) { html = '
当前页面未检测到合集视频列表
'; } else { videoData.forEach(v => { if (v.isMulti && v.subVideos.length > 0) { const isExpanded = panelState.expandedMultis.has(v.bv); const anySubChecked = v.subVideos.some(sv => panelState.checkedSet.has(sv.id)); const allSubChecked = v.subVideos.every(sv => panelState.checkedSet.has(sv.id)); const isCurrentParent = currentBv === v.bv; html += `
▶ ${escapeHtml(v.title)}📁 ${v.subVideos.length}个分P${v.duration}${getTimesHtml([v.bv])} ${preferIdSet.has(v.bv) ? '⭐' : '☆'} ${v.bv}
`; if (isExpanded) { v.subVideos.forEach(sv => { const checked = panelState.checkedSet.has(sv.id); const isCurrentSub = currentBv === sv.bv && sv.pIndex === currentP; html += `
${escapeHtml(sv.title)}⏱ ${sv.duration} ${preferIdSet.has(sv.id) ? '⭐' : '☆'} P${sv.pIndex + 1}
`; }); } } else { const checked = panelState.checkedSet.has(v.id); const isCurrent = currentBv === v.bv; html += `
${escapeHtml(v.title)}⏱ ${v.duration}${getTimesHtml([v.bv])} ${preferIdSet.has(v.id) ? '⭐' : '☆'} ${v.bv}
`; } }); } body.innerHTML = html; updateCheckedCount(); bindListEvents(); } function escapeHtml(str) { const div = document.createElement('div'); div.textContent = str; return div.innerHTML; } function updateCheckedCount() { const drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; const countEl = drawer.querySelector('.checked-count'); if (countEl) countEl.textContent = panelState.checkedSet.size; } function bindListEvents() { const body = document.querySelector('#bili-force-drawer .drawer-body'); if (!body) return; body.querySelectorAll('.expand-icon').forEach(el => { el.addEventListener('click', (e) => { e.stopPropagation(); const parent = el.closest('.multi-parent'); const bv = parent.getAttribute('data-bv'); if (panelState.expandedMultis.has(bv)) { panelState.expandedMultis.delete(bv); } else { panelState.expandedMultis.add(bv); } renderVideoList(); }); }); body.querySelectorAll('input[type="checkbox"]').forEach(cb => { cb.addEventListener('change', (e) => { e.stopPropagation(); const id = cb.getAttribute('data-id'); const isParent = cb.getAttribute('data-is-parent') === '1'; if (isParent) { const video = panelState.videoData.find(v => v.bv === id); if (video && video.subVideos) { video.subVideos.forEach(sv => { if (cb.checked) panelState.checkedSet.add(sv.id); else panelState.checkedSet.delete(sv.id); }); } } else { if (cb.checked) panelState.checkedSet.add(id); else panelState.checkedSet.delete(id); } renderVideoList(); }); }); body.querySelectorAll('.video-item').forEach(item => { item.addEventListener('click', (e) => { if (e.target.closest('input') || e.target.closest('.expand-icon') || e.target.closest('.star-btn')) return; const bv = item.getAttribute('data-bv'); const pIndex = item.getAttribute('data-pindex'); navigateToVideo(bv, pIndex ? parseInt(pIndex) : null); }); }); // ⭐ 加入/移出偏好:弹迷你选择浮层(列出所有偏好列表,点击切换归属) body.querySelectorAll('.star-btn').forEach(st => { st.addEventListener('click', (e) => { e.stopPropagation(); const itemEl = st.closest('.video-item'); const titleEl = itemEl && itemEl.querySelector('.video-title'); const sid = st.getAttribute('data-star-id') || ''; showPreferPopover(st, { id: sid, bv: st.getAttribute('data-bv') || sid.split('::')[0], p: st.hasAttribute('data-pindex') ? parseInt(st.getAttribute('data-pindex'), 10) : null, title: titleEl ? titleEl.textContent.trim() : '' }); }); }); } function openPanel() { const drawer = document.getElementById('bili-force-drawer'); const overlay = document.getElementById('bili-force-overlay'); const trigger = document.getElementById('bili-force-trigger'); // 每次打开默认回到列表模式 if (drawer) drawer.classList.remove('mode-collections', 'mode-prefer'); const titleEl = document.getElementById('bili-drawer-title'); if (titleEl) titleEl.textContent = '📋 播放列表管理'; window.__isOpeningPanel = true; panelState.videoData = parsePageVideoList(); panelState.expandedMultis.clear(); panelState.preferExpanded.clear(); const currentBv = getCurrentBVID(); // 自动展开包含当前播放视频的多P项 panelState.videoData.forEach(v => { if (v.isMulti && v.bv === currentBv) { panelState.expandedMultis.add(v.bv); } }); const listName = getListName(); const restored = restoreFromMemoryList(listName, panelState.videoData); if (restored.checkedSet) { panelState.checkedSet = restored.checkedSet; } else { panelState.checkedSet = new Set(getListForCurrentCollection()); } // force 是全局持久开关:面板 UI 跟随全局状态;不允许 memory 名字匹配失败时把全局开关覆写为 false panelState.forceFromStart = window.__biliForceStartEnabled; if (drawer) drawer.classList.add('active'); if (overlay) overlay.classList.add('active'); if (trigger) trigger.classList.add('panel-open'); panelState.open = true; // 以偏好为第一性:当前视频已收录进某个偏好列表 → 打开面板直接进偏好视图,并展开所在列表 const hitPrefer = currentBv ? getPreferLists().find(l => (l.items || []).some(i => i.id === currentBv || i.id.indexOf(currentBv + '::') === 0)) : null; if (hitPrefer) { panelState.preferExpanded.clear(); panelState.preferExpanded.add(hitPrefer.id); showPrefer(); // 滚动到当前视频所在的偏好条目(优先),找不到再退回列表行。 // 不用 scrollIntoView(会连带滚动页面等所有可滚祖先),直接算相对 .prefer-body 视口的位置手动滚 const scrollHit = () => { try { const body = document.getElementById('bili-prefer-body'); if (!body) return; const item = body.querySelector('.prefer-items .video-item[data-bv="' + currentBv + '"]'); const target = item || body.querySelector('.prefer-row[data-pid="' + hitPrefer.id + '"]'); if (!target) return; const br = body.getBoundingClientRect(); const tr = target.getBoundingClientRect(); if (!br.height || !tr.height) return; // 标粉闪烁几下(3 次),结束后移除类以便下次打开可复现 if (!target.classList.contains('prefer-hit-flash')) { target.classList.add('prefer-hit-flash'); setTimeout(() => target.classList.remove('prefer-hit-flash'), 1800); } body.scrollTo({ top: body.scrollTop + (tr.top - br.top) - (br.height - tr.height) / 2, behavior: 'smooth' }); } catch (e) {} }; scrollHit(); setTimeout(scrollHit, 200); } renderVideoList(); updateForceSwitchUI(); window.__biliForceStartEnabled = panelState.forceFromStart; // 异步加载观看次数统计(4.js 的 IndexedDB),加载完成后刷新一次列表显示 🔁 loadViewCounts().then(() => { if (panelState.open) renderVideoList(); }); // 加载当前合集背景图和美化配置 applyCurrentBg(); // 自动滚动到当前播放项 setTimeout(() => { const body = drawer.querySelector('.drawer-body'); const currentItem = body.querySelector('.current-playing'); if (currentItem && body) { currentItem.scrollIntoView({ behavior: 'smooth', block: 'center' }); } }, 100); setTimeout(() => { window.__isOpeningPanel = false; }, 800); } function closePanel() { const trigger = document.getElementById('bili-force-trigger'); const drawer = document.getElementById('bili-force-drawer'); const overlay = document.getElementById('bili-force-overlay'); if (drawer) drawer.classList.remove('active'); if (overlay) overlay.classList.remove('active'); if (trigger) trigger.classList.remove('panel-open'); panelState.open = false; } function togglePanel() { panelState.open ? closePanel() : openPanel(); } function saveCurrentList() { updateMemoryListFromCheckedSet(); const ids = [...panelState.checkedSet]; saveListForCurrentCollection(ids); updateCheckedCount(); checkAndHijack(); showToast('✅ 列表已保存'); } function bindEvents() { const drawer = document.getElementById('bili-force-drawer'); const overlay = document.getElementById('bili-force-overlay'); const trigger = document.getElementById('bili-force-trigger'); if (trigger) trigger.addEventListener('click', (e) => { e.stopPropagation(); togglePanel(); }); if (overlay) overlay.addEventListener('click', closePanel); if (drawer) { const closeBtn = drawer.querySelector('.drawer-close'); if (closeBtn) closeBtn.addEventListener('click', closePanel); const closePanelBtn = drawer.querySelector('.btn-close-panel'); if (closePanelBtn) closePanelBtn.addEventListener('click', () => { closePanel(); }); const saveBottomBtn = drawer.querySelector('.btn-save-bottom'); if (saveBottomBtn) saveBottomBtn.addEventListener('click', () => { if (saveBottomBtn._saving) return; saveBottomBtn._saving = true; saveCurrentList(); saveBottomBtn.textContent = '✅ 已保存'; setTimeout(() => { saveBottomBtn.textContent = '💾 保存并关闭'; saveBottomBtn._saving = false; closePanel(); }, 700); }); // ☑ 选择下拉:全选 / 反选 / 取消全选 const selDrop = drawer.querySelector('.select-dropdown'); const selMenuBtn = drawer.querySelector('.btn-select-menu'); if (selMenuBtn && !selMenuBtn._bound) { selMenuBtn._bound = true; selMenuBtn.addEventListener('click', (e) => { e.stopPropagation(); if (selDrop) selDrop.classList.toggle('open'); }); const selMenu = drawer.querySelector('.select-menu'); if (selMenu) selMenu.addEventListener('click', (e) => { e.stopPropagation(); const row = e.target.closest('.sm-row'); if (!row) return; const op = row.dataset.op; if (op === 'all') { panelState.videoData.forEach(v => { if (v.isMulti) v.subVideos.forEach(sv => panelState.checkedSet.add(sv.id)); else panelState.checkedSet.add(v.id); }); } else if (op === 'none') { panelState.checkedSet.clear(); } else if (op === 'invert') { const allIds = []; panelState.videoData.forEach(v => { if (v.isMulti) v.subVideos.forEach(sv => allIds.push(sv.id)); else allIds.push(v.id); }); allIds.forEach(id => { if (panelState.checkedSet.has(id)) panelState.checkedSet.delete(id); else panelState.checkedSet.add(id); }); } if (selDrop) selDrop.classList.remove('open'); renderVideoList(); }); // 点击下拉外部时收起 document.addEventListener('click', (e) => { if (selDrop && selDrop.classList.contains('open') && !selDrop.contains(e.target)) { selDrop.classList.remove('open'); } }); } // 主题跟随开关 const themeFollowSwitch = drawer.querySelector('#theme-follow-switch'); if (themeFollowSwitch && !themeFollowSwitch._bound) { themeFollowSwitch._bound = true; themeFollowSwitch.addEventListener('click', (e) => { e.stopPropagation(); toggleThemeFollow(); }); } // 手动切换主题按钮 const themeToggleBtn = drawer.querySelector('.btn-theme-toggle'); if (themeToggleBtn && !themeToggleBtn._bound) { themeToggleBtn._bound = true; themeToggleBtn.addEventListener('click', (e) => { e.stopPropagation(); toggleThemeManual(); }); } const forceSwitch = drawer.querySelector('#force-start-switch'); if (forceSwitch && !forceSwitch._bound) { forceSwitch._bound = true; forceSwitch.addEventListener('click', (e) => { e.stopPropagation(); panelState.forceFromStart = !panelState.forceFromStart; updateForceSwitchUI(); window.__biliForceStartEnabled = panelState.forceFromStart; try { GM_setValue(FORCE_KEY, panelState.forceFromStart); } catch (err) {} if (window.__biliForceStartEnabled) resetVideo(); showToast(panelState.forceFromStart ? '✅ 强制从头播放已开启' : '⏸ 强制从头播放已关闭'); }); } // 多合集阅览:入口(按钮行「多合集预览」)/ 返回 / 点击合集项 const btnCollections = drawer.querySelector('.btn-collections-main'); if (btnCollections) btnCollections.addEventListener('click', (e) => { e.stopPropagation(); showCollections(); }); const backCollections = drawer.querySelector('#bili-collections-back'); if (backCollections) backCollections.addEventListener('click', backFromCollections); const collList = drawer.querySelector('#bili-collections-list'); if (collList) { collList.addEventListener('click', (e) => { const it = e.target.closest('.collection-item'); if (it && it.dataset.key) { if (it._lpArmed) { it._lpArmed = false; return; } // 长按过:本次松开不触发跳转 jumpToCollection(it.dataset.key); } }); // 长按删除状态机:按住 1s 进入「删除中」(闪红),继续不松 → 进度条 1.5s 后删除;中途松开取消 let lpRow = null, lpTimer1 = null, lpTimer2 = null; const lpReset = () => { clearTimeout(lpTimer1); clearTimeout(lpTimer2); lpTimer1 = lpTimer2 = null; if (lpRow) { lpRow.classList.remove('del-arming'); const bar = lpRow.querySelector('.ci-del-bar'); if (bar) { bar.style.transition = 'none'; bar.style.width = '100%'; } } }; collList.addEventListener('pointerdown', (e) => { if (e.button !== undefined && e.button !== 0) return; const row = e.target.closest('.collection-item'); if (!row || !row.dataset.key) return; lpReset(); lpRow = row; row._lpArmed = false; try { row.setPointerCapture(e.pointerId); } catch (err) {} lpTimer1 = setTimeout(() => { if (!lpRow) return; lpRow.classList.add('del-arming'); lpRow._lpArmed = true; const bar = lpRow.querySelector('.ci-del-bar'); if (bar) requestAnimationFrame(() => requestAnimationFrame(() => { if (!lpRow || !bar.isConnected) return; bar.style.transition = 'width 1.5s linear'; bar.style.width = '0%'; })); lpTimer2 = setTimeout(() => { const key = lpRow ? lpRow.dataset.key : null; lpReset(); lpRow = null; if (key) performDeleteCollection(key); }, 1500); }, 1000); }); const lpAbort = () => { lpReset(); lpRow = null; }; collList.addEventListener('pointerup', lpAbort); collList.addEventListener('pointercancel', lpAbort); // 滚动等系统接管时取消 collList.addEventListener('contextmenu', (e) => { if (e.target.closest('.collection-item')) e.preventDefault(); // 触屏长按防弹出菜单 }); } // 偏好列表:入口 / 返回 / 行内操作(展开、重命名、播放、移除、点击条目跳转) const btnPrefer = drawer.querySelector('.btn-prefer-main'); if (btnPrefer) btnPrefer.addEventListener('click', (e) => { e.stopPropagation(); showPrefer(); }); const backPrefer = drawer.querySelector('.btn-prefer-back'); if (backPrefer) backPrefer.addEventListener('click', backFromPrefer); const addPrefer = drawer.querySelector('.btn-prefer-add'); if (addPrefer) addPrefer.addEventListener('click', (e) => { e.stopPropagation(); const l = createPreferList(); showToast('⭐ 已创建 ' + l.name); renderPreferView(); }); // ⭐ 勾选入偏好:把当前已勾选条目整体加入某个偏好列表 const btnPreferChecked = drawer.querySelector('.btn-prefer-checked'); if (btnPreferChecked) btnPreferChecked.addEventListener('click', (e) => { e.stopPropagation(); const items = []; panelState.videoData.forEach(v => { if (v.isMulti) v.subVideos.forEach(sv => { if (panelState.checkedSet.has(sv.id)) items.push({ id: sv.id, bv: v.bv, p: sv.pIndex, title: sv.title }); }); else if (panelState.checkedSet.has(v.id)) items.push({ id: v.id, bv: v.bv, p: null, title: v.title }); }); if (!items.length) { showToast('⚠️ 请先勾选要收集的视频'); return; } showPreferBatchPopover(btnPreferChecked, items); }); const preferBody = drawer.querySelector('#bili-prefer-body'); if (preferBody) { preferBody.addEventListener('click', (e) => { const star = e.target.closest('.star-btn'); if (star) { // 偏好视图内:再点一次从该列表移除 e.stopPropagation(); const pid = star.getAttribute('data-pid'); const itemId = star.getAttribute('data-item-id'); const lists = getPreferLists(); const l = lists.find(x => x.id === pid); if (l) { l.items = l.items.filter(i => i.id !== itemId); savePreferLists(lists); showToast('☆ 已从 ' + l.name + ' 移除'); renderPreferView(); renderVideoList(); } return; } const pi = e.target.closest('.prefer-items .video-item'); if (pi) { // 点击偏好条目:自动进入该列表的偏好播放模式,并从选中条目开始播放 const itemsBox = pi.closest('.prefer-items'); const l2 = findPreferList(itemsBox ? itemsBox.getAttribute('data-pid') : null); const item2 = l2 && l2.items.find(i => i.id === pi.getAttribute('data-item-id')); if (l2 && item2) { beginPreferPlay(l2, item2, '从选中项开始'); // 内部完成导航/就地重启 + 连播接管 } else { // 兜底:列表/条目异常时退回普通跳转 const bv = pi.getAttribute('data-bv'); const p = pi.hasAttribute('data-pindex') ? parseInt(pi.getAttribute('data-pindex'), 10) : null; if (bv) navigateToVideo(bv, p); } return; } const row = e.target.closest('.prefer-row'); if (!row) return; const pid = row.getAttribute('data-pid'); const l = findPreferList(pid); if (!l) return; if (e.target.closest('.pr-rename')) { e.stopPropagation(); const name = (prompt('重命名偏好列表:', l.name) || '').trim(); if (name && name !== l.name) { const lists = getPreferLists(); const t = lists.find(x => x.id === pid); if (t) { t.name = name; savePreferLists(lists); } renderPreferView(); } return; } if (e.target.closest('.pr-resume')) { e.stopPropagation(); resumePreferPlay(l); return; } if (e.target.closest('.pr-play')) { e.stopPropagation(); startOrStopPreferPlay(l); return; } // 其余区域:展开/收起 if (panelState.preferExpanded.has(pid)) panelState.preferExpanded.delete(pid); else panelState.preferExpanded.add(pid); renderPreferView(); }); // 长按删除偏好列表(与多合集一致的交互) let lpRowP = null, lpTimer1P = null, lpTimer2P = null; const lpResetP = () => { clearTimeout(lpTimer1P); clearTimeout(lpTimer2P); lpTimer1P = lpTimer2P = null; if (lpRowP) { lpRowP.classList.remove('del-arming'); const bar = lpRowP.querySelector('.ci-del-bar'); if (bar) { bar.style.transition = 'none'; bar.style.width = '100%'; } } }; preferBody.addEventListener('pointerdown', (e) => { if (e.button !== undefined && e.button !== 0) return; // 按钮点击不走长按:setPointerCapture 会把 click 重定向到行元素,导致 ✏️/⏯/▶ 永远点不中 if (e.target.closest('.pr-rename, .pr-resume, .pr-play')) return; const row = e.target.closest('.prefer-row'); if (!row || !row.dataset.pid) return; lpResetP(); lpRowP = row; row._lpArmed = false; try { row.setPointerCapture(e.pointerId); } catch (err) {} lpTimer1P = setTimeout(() => { if (!lpRowP) return; lpRowP.classList.add('del-arming'); lpRowP._lpArmed = true; const bar = lpRowP.querySelector('.ci-del-bar'); if (bar) requestAnimationFrame(() => requestAnimationFrame(() => { if (!lpRowP || !bar.isConnected) return; bar.style.transition = 'width 1.5s linear'; bar.style.width = '0%'; })); lpTimer2P = setTimeout(() => { const pid = lpRowP ? lpRowP.dataset.pid : null; lpResetP(); lpRowP = null; if (pid) performDeletePrefer(pid); }, 1500); }, 1000); }); const lpAbortP = () => { lpResetP(); lpRowP = null; }; preferBody.addEventListener('pointerup', lpAbortP); preferBody.addEventListener('pointercancel', lpAbortP); preferBody.addEventListener('contextmenu', (e) => { if (e.target.closest('.prefer-row')) e.preventDefault(); }); } } document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && panelState.open) closePanel(); }); } // ========== 8.5 多合集阅览 ========== // 读取 4.js 观看记录(含 lastTime,用于“最近看过哪个视频”) function readViewRecords() { return new Promise(resolve => { try { const req = indexedDB.open('BiliViewCountDB'); req.onsuccess = () => { try { const tx = req.result.transaction('views', 'readonly'); const g = tx.objectStore('views').getAll(); g.onsuccess = () => resolve(g.result || []); g.onerror = () => resolve([]); } catch (e) { resolve([]); } }; req.onerror = () => resolve([]); } catch (e) { resolve([]); } }); } // 从合集 key 解析 BV 列表:single_BV… / list_BV1|BV2… function collectionKeyToBvs(key) { if (!key) return []; const i = key.indexOf('_'); if (i < 0) return []; return String(key.slice(i + 1)).split('|').filter(Boolean); } function showCollections() { const drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; drawer.classList.remove('mode-prefer'); drawer.classList.add('mode-collections'); const title = document.getElementById('bili-drawer-title'); if (title) title.textContent = '📚 多合集阅览'; renderCollections(); } function backFromCollections() { const drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; drawer.classList.remove('mode-collections'); const title = document.getElementById('bili-drawer-title'); if (title) title.textContent = '📋 播放列表管理'; } // 长按删除:直接执行;同时清理 v3 记录、合集名映射和该合集的背景图 function performDeleteCollection(key) { if (!key) return; const data = getAllData(); if (data[key] !== undefined) { delete data[key]; saveAllData(data); } try { const m = getNameMap(); if (m[key] !== undefined) { delete m[key]; saveNameMap(m); } } catch (e) {} try { deleteBgImageById(key); } catch (e) {} showToast('🗑 已删除该合集'); renderCollections(); } async function renderCollections() { const listEl = document.getElementById('bili-collections-list'); if (!listEl) return; const countEl = listEl.parentElement ? listEl.parentElement.querySelector('.collections-count') : null; // 数据源:v3 按合集记忆 {collectionId: [勾选ids]}(collectionId 自带 BV); // memory 仅按名记录 force,用于给同名单BV合集补「🔒 强制」标记 const data = getAllData(); const memory = getMemoryList(); const cidKeys = Object.keys(data).filter(k => k.indexOf('_') >= 0 && Array.isArray(data[k])); const curKey = resolveCollectionKey(getCollectionIdFromPage()); const nameMap = getNameMap(); // 当前合集若还没记过名字,用本页合集组件的标题自动补录(老合集回访一次即可恢复可读名) if (curKey && data[curKey] !== undefined) { const t = grabCollectionTitle(); if (t && nameMap[curKey] !== t) { recordCollectionName(curKey, t); nameMap[curKey] = t; } } if (countEl) countEl.textContent = cidKeys.length; if (!cidKeys.length) { listEl.innerHTML = '
还没有保存过的合集。在列表页勾选后点「💾 保存列表」,就会出现在这里。
'; return; } const nameToForce = {}; for (const k in memory) { const e = memory[k]; if (e && e[0] && e.length >= 3) nameToForce[e[0]] = !!e[1]; } let recs = []; try { recs = await readViewRecords(); } catch (e) {} const titleOf = {}, lastOf = {}, timesOf = {}, lastPOf = {}, lastCidOf = {}; recs.forEach(r => { if (!r || !r.id) return; if (r.title) titleOf[r.id] = r.title; timesOf[r.id] = r.times; if (r.lastP) lastPOf[r.id] = r.lastP; if (r.lastCid) lastCidOf[r.id] = r.lastCid; const t = r.lastTime || 0; if (!(r.id in lastOf) || t > lastOf[r.id]) lastOf[r.id] = t; }); const rows = []; let failed = 0; cidKeys.forEach(cid => { try { const ids = data[cid] || []; const bvs = collectionKeyToBvs(cid); const firstBv = bvs[0] || ''; const isSingle = cid.indexOf('single_') === 0; // 名字优先级:保存时抓到的合集标题 > 首个BV标题(+等N个)> 类型占位 let name = nameMap[cid] || ''; if (!name) { name = firstBv ? (titleOf[firstBv] || '') : ''; if (bvs.length > 1 && name) name += ' 等' + bvs.length + '个'; } if (!name) name = isSingle ? '单视频合集' : (bvs.length > 1 ? '多视频合集' : '分P合集'); const force = firstBv && nameToForce[titleOf[firstBv]] ? nameToForce[titleOf[firstBv]] : false; let lastTs = 0, sumTimes = 0, lastPSeen = 0, jumpBv = firstBv, jumpCid = ''; bvs.forEach(b => { const t = lastOf[b] || 0; if (t > lastTs) { lastTs = t; lastPSeen = lastPOf[b] || 0; jumpBv = b; jumpCid = lastCidOf[b] || ''; } sumTimes += timesOf[b] || 0; }); const isCur = cid === curKey; const badge = isSingle ? '单视频' : (bvs.length > 1 ? '多视频' : '分P'); const metaBits = []; if (bvs.length) metaBits.push(bvs.length + ' 个BV'); if (ids.length) metaBits.push('勾选 ' + ids.length + ' 项'); if (sumTimes) metaBits.push('累计 🔁 ' + sumTimes); if (force) metaBits.push('🔒 强制'); if (lastPSeen > 1) metaBits.push('上次 P' + lastPSeen); const lastStr = lastTs ? new Date(lastTs).toLocaleString('zh-CN', { hour12: false }) : ''; const subLine = [metaBits.join(' · '), lastStr ? '最近 ' + lastStr : ''].filter(Boolean).join(' · ') || '—'; // 悬浮提示:将跳转至 <名称>,BV为 [,cid为 ] let tip = '将跳转至 ' + (name || '该合集') + ',BV为 ' + (jumpBv || '—'); if (jumpCid) tip += ',cid为 ' + jumpCid; rows.push(`
${badge}
${escapeHtml(name)}${isCur ? '(当前)' : ''}
${escapeHtml(subLine)}
▶ 跳转
删除中
`); } catch (err) { failed++; console.error('[多合集渲染错误]', err, cid.slice(0, 60)); } }); if (!rows.length) { listEl.innerHTML = failed ? '
解析合集时出错 ' + failed + ' 条,详见 Console
' : '
有合集记录但暂无可显示项
'; } else { listEl.innerHTML = rows.join(''); } } // 跳转到该合集“最近看过”的视频;单BV多P页则回本页或带 p=1 async function jumpToCollection(key) { setActivePreferId(null); // 跳普通合集 = 退出偏好播放 const data = getAllData(); const ids = data[key]; if (!Array.isArray(ids) || !ids.length) return; const bvs = collectionKeyToBvs(key); if (!bvs.length) return; let recs = []; try { recs = await readViewRecords(); } catch (e) {} let targetBv = bvs[0], lastTs = 0, targetP = 0; bvs.forEach(b => { const r = recs.find(x => x && x.id === b); const t = r ? (r.lastTime || 0) : 0; if (t > lastTs) { lastTs = t; targetBv = b; targetP = (r && r.lastP) || 0; } }); try { // 临时诊断:定位「跳转不带分P」——若记录里没有 lastP,问题在 4.js 写入端 const _dbg = recs.find(x => x && x.id === targetBv); console.log('[合集跳转诊断] 记录总数=' + recs.length, '| 目标=', _dbg, '| 解析出 targetP=' + targetP); } catch (e) {} const curBv = (location.pathname.match(/\/video\/(BV[0-9a-zA-Z]+)/) || [])[1]; const curP = getCurrentPIndex() + 1; // 0基 → 1基(无 ?p 视为 1) const effTargetP = targetP > 1 ? targetP : 1; // 同一视频且已在目标分P才算“已在”;同视频不同分P仍要跳(否则只能手动点选集) if (curBv === targetBv && curP === effTargetP) { showToast('✅ 已在当前视频,可在列表中继续勾选'); backFromCollections(); return; } // 带上上次退出的分P(无需精确空降,落到对应P即可;实测 B 站 ?p=N 落地有效) const url = 'https://www.bilibili.com/video/' + targetBv + (targetP > 1 ? '?p=' + targetP : ''); showToast(targetP > 1 ? '⏭ 正在跳转到该合集(P' + targetP + ')…' : '⏭ 正在跳转到该合集…'); setTimeout(() => { location.href = url; }, 300); } // ========== 8.6 偏好列表(PreferList)视图 ========== function showPrefer() { const drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; drawer.classList.remove('mode-collections'); drawer.classList.add('mode-prefer'); const title = document.getElementById('bili-drawer-title'); if (title) title.textContent = '⭐ 偏好列表'; preferAutoScrolled = false; // 每次进入偏好视图重新给一次「滚到上次」的机会 renderPreferView(); } function backFromPrefer() { const drawer = document.getElementById('bili-force-drawer'); if (!drawer) return; drawer.classList.remove('mode-prefer'); const title = document.getElementById('bili-drawer-title'); if (title) title.textContent = '📋 播放列表管理'; } function renderPreferView() { const body = document.getElementById('bili-prefer-body'); if (!body) return; const drawer = document.getElementById('bili-force-drawer'); const countEl = drawer ? drawer.querySelector('.prefer-count') : null; const lists = getPreferLists(); if (countEl) countEl.textContent = lists.length; // 空态:居中灰色加号,点击自建偏好1 if (!lists.length) { body.innerHTML = '
+创建第一个偏好列表(偏好1)
之后在任意列表点条目右侧 ☆ 即可收集
'; const empty = body.querySelector('#bili-prefer-empty'); if (empty) empty.addEventListener('click', () => { const l = createPreferList(); showToast('⭐ 已创建 ' + l.name); renderPreferView(); }); return; } const activeId = getActivePreferId(); // 正在播放的列表排到最前面(不改动存储顺序,仅展示序) const sorted = lists.slice().sort((a, b) => (b.id === activeId ? 1 : 0) - (a.id === activeId ? 1 : 0)); // 「表头」列表:播放中=活动列表;未播放=上次观看时间最新的列表。其名称+按钮行吸顶 let stickyId = lists.find(l => l.id === activeId) ? activeId : null; if (!stickyId) { let bt = 0; lists.forEach(l => { const h = derivePreferLast(l, preferRecsCache); if (h && h.t > bt) { bt = h.t; stickyId = l.id; } }); } // 观看记录(4.js views):首次异步加载,加载完重渲染一次,之后走缓存 if (preferRecsCache === null) { readViewRecords().then(recs => { preferRecsCache = recs || []; renderPreferView(); }); } const curBv = getCurrentBVID(), curP = getCurrentPIndex(); const rows = sorted.map(l => { const expanded = panelState.preferExpanded.has(l.id); const isActive = l.id === activeId; // 「上次播放」从观看记录推导(不另存续播点);仅一条时 ▶ 播放即是续播,不必重复出按钮 const lh = derivePreferLast(l, preferRecsCache); const lastHit = lh && lh.it; const canResume = !!lastHit && l.items.length > 1 && lastHit.id !== l.items[0].id; let itemsHtml = ''; if (expanded) { const listHasNow = !!(curBv && l.items.some(it => matchListEntry(it.id, curBv, curP))); const inner = l.items.length ? l.items.map(it => { const pAttr = (it.p !== null && it.p !== undefined) ? ` data-pindex="${it.p}"` : ''; const tag = it.id.includes('::') ? 'P' + (parseInt(it.id.split('::')[1], 10) + 1) : escapeHtml(it.bv || ''); const isLast = lastHit && it.id === lastHit.id; const isNow = curBv && matchListEntry(it.id, curBv, curP); // 复用合集视图的 current-playing 约定 // 标签语义:本列表有正在播放的条目 → 该条目挂粉色「正在播放」;未播放任何 → 上次播放条目挂蓝色「上次」 const tagHtml = isNow ? '正在播放' : (isLast && !listHasNow ? '上次' : ''); return `
⭐ ${tagHtml}${isNow ? '▶ ' : ''}${escapeHtml(it.title || it.id)} ${tag}
`; }).join('') : '
空列表。去任意视频列表点条目右侧 ☆ 收集。
'; itemsHtml = '
' + inner + '
'; } return `
▶ ${escapeHtml(l.name)}${isActive ? '(播放中)' : ''} ${l.items.length} 项
${lastHit ? '上次: ' + escapeHtml(lastHit.title || lastHit.id) : '尚无观看记录'} ${canResume ? `` : ''}
删除中
${itemsHtml}`; }).join(''); body.innerHTML = rows; maybeScrollPreferToLast(); } // 未播放任何时:打开偏好视图自动展开「上次播放的列表」并滚动+闪烁定位到「上次」条目 // (播放中不走这里——openPanel 已有「滚到当前播放条目」逻辑);每次 showPrefer 重置一次机会 function maybeScrollPreferToLast() { if (preferAutoScrolled) return; if (preferRecsCache === null) return; // 等观看记录异步加载完的重渲染再试 const lists = getPreferLists(); if (!lists.length) { preferAutoScrolled = true; return; } const curBv = getCurrentBVID(), curP = getCurrentPIndex(); const inAny = curBv && lists.some(l => (l.items || []).some(i => matchListEntry(i.id, curBv, curP))); if (inAny) { preferAutoScrolled = true; return; } // 正在播偏好里的视频:交给现有「滚到当前条」逻辑 // 目标列表:与吸顶同一规则(activeId 优先,否则上次观看时间最新的列表) const activeId = getActivePreferId(); let sticky = lists.find(l => l.id === activeId); if (!sticky) { let bt = 0; lists.forEach(l => { const h = derivePreferLast(l, preferRecsCache); if (h && h.t > bt) { bt = h.t; sticky = l; } }); } if (!sticky) { preferAutoScrolled = true; return; } const hit = derivePreferLast(sticky, preferRecsCache); if (!hit) { preferAutoScrolled = true; return; } // 该列表没有任何观看记录 if (!panelState.preferExpanded.has(sticky.id)) { panelState.preferExpanded.add(sticky.id); // 自动展开后重渲染,再次进入本函数 renderPreferView(); return; } const body = document.getElementById('bili-prefer-body'); if (!body) return; const row = body.querySelector('.prefer-row[data-pid="' + sticky.id + '"]'); const items = row ? row.nextElementSibling : null; const item = items && items.querySelector('.video-item[data-item-id="' + hit.it.id + '"]'); if (!item) { preferAutoScrolled = true; return; } try { const br = body.getBoundingClientRect(); const tr = item.getBoundingClientRect(); if (br.height && tr.height) { item.classList.add('prefer-hit-flash'); // 同播放定位:标粉闪烁几下 setTimeout(() => item.classList.remove('prefer-hit-flash'), 1800); body.scrollTo({ top: body.scrollTop + (tr.top - br.top) - (br.height - tr.height) / 2, behavior: 'smooth' }); } } catch (e) {} preferAutoScrolled = true; } function performDeletePrefer(pid) { const lists = getPreferLists(); const idx = lists.findIndex(l => l.id === pid); if (idx < 0) return; const name = lists[idx].name; lists.splice(idx, 1); savePreferLists(lists); panelState.preferExpanded.delete(pid); if (getActivePreferId() === pid) setActivePreferId(null); showToast('🗑 已删除 ' + name); renderPreferView(); } // ▶ 按顺序播放 / ⏹ 停止:偏好播放复用强制播放链路(连播+拦截),开启全局开关 function startOrStopPreferPlay(l) { if (getActivePreferId() === l.id) { setActivePreferId(null); showToast('⏹ 已退出偏好播放'); renderPreferView(); return; } if (!l.items.length) { showToast('⚠️ 该偏好列表还是空的'); return; } beginPreferPlay(l, l.items[0], '开始按'); } // ⏯ 从上次播放开始:目标条目从观看记录推导;没有任何观看记录则退回从第一项播 function resumePreferPlay(l) { const h = derivePreferLast(l, preferRecsCache); const last = h && h.it; if (!last) { showToast('⚠️ 没有续播记录,改为从头播放'); startOrStopPreferPlay(l); return; } beginPreferPlay(l, last, '从上次播放继续'); } // 按 entry 开始偏好播放(entry 为 l.items 里的条目);tip 用于提示语区分「开始按 / 从上次播放继续」 function beginPreferPlay(l, entry, tip) { setActivePreferId(l.id); window.__biliForceStartEnabled = true; panelState.forceFromStart = true; try { GM_setValue(FORCE_KEY, true); } catch (e) {} updateForceSwitchUI(); const startBv = entry.bv || (entry.id.includes('::') ? entry.id.split('::')[0] : entry.id); const startP = (entry.p !== null && entry.p !== undefined) ? entry.p : (entry.id.includes('::') ? parseInt(entry.id.split('::')[1], 10) : null); showToast('⭐ ' + tip + '「' + l.name + '」顺序播放'); const curBv = getCurrentBVID(); const curP = getCurrentPIndex(); if (curBv === startBv && curP === (startP || 0)) { // 已在该项:就地重启归零窗口并接管可见性 window.__forceZeroDeadline = Date.now() + FORCE_ZERO_WINDOW_MS; window.__forceZeroDone = false; hijackVisibility(); resetVideo(); } else { setTimeout(() => navigateToVideo(startBv, startP), 200); } renderPreferView(); } // ⭐ 迷你选择浮层:列出所有偏好列表(点击切换归属)+ 新建 let preferPopEl = null; function closePreferPopover() { if (preferPopEl) { preferPopEl.remove(); preferPopEl = null; document.removeEventListener('click', closePreferPopover, true); } } function showPreferPopover(anchor, item) { closePreferPopover(); if (!item || !item.id) return; const pop = document.createElement('div'); pop.id = 'bili-prefer-pop'; if (getTheme() === 'dark') pop.classList.add('dark'); const lists = getPreferLists(); pop.innerHTML = lists.map(l => `
${l.items.some(i => i.id === item.id) ? '⭐' : '☆'}${escapeHtml(l.name)}${l.items.length}
`).join('') + '
+ 新建偏好列表
'; document.body.appendChild(pop); const rect = anchor.getBoundingClientRect(); let left = Math.max(8, Math.min(rect.left, window.innerWidth - pop.offsetWidth - 10)); let top = rect.bottom + 6; if (top + pop.offsetHeight > window.innerHeight - 8) top = Math.max(8, rect.top - pop.offsetHeight - 6); pop.style.left = left + 'px'; pop.style.top = top + 'px'; pop.addEventListener('click', (e) => { e.stopPropagation(); const row = e.target.closest('.pp-row'); if (!row) return; if (row.classList.contains('pp-new')) { // 新建并加入:在同一个解析副本上完成建表+收录再整体保存(否则改动会被重新解析覆盖丢失) const lists = getPreferLists(); const l = { id: 'p' + Date.now(), name: nextPreferName(lists), items: [item] }; lists.push(l); savePreferLists(lists); showToast('⭐ 已创建 ' + l.name + ' 并加入'); } else { const added = togglePreferItem(row.dataset.pid, item); const l = findPreferList(row.dataset.pid); showToast(added ? '⭐ 已加入 ' + (l ? l.name : '偏好') : '☆ 已从 ' + (l ? l.name : '偏好') + ' 移除'); } closePreferPopover(); renderVideoList(); const d = document.getElementById('bili-force-drawer'); if (d && d.classList.contains('mode-prefer')) renderPreferView(); }); preferPopEl = pop; // 延迟挂全局点击关闭(避免本次点击冒泡立即自关) setTimeout(() => { document.addEventListener('click', closePreferPopover, true); }, 0); } // 「⭐ 勾选入偏好」批量浮层:把当前已勾选条目整体加入某个偏好列表(合并去重,只加不删) function showPreferBatchPopover(anchor, items) { closePreferPopover(); if (!items || !items.length) return; const pop = document.createElement('div'); pop.id = 'bili-prefer-pop'; if (getTheme() === 'dark') pop.classList.add('dark'); const lists = getPreferLists(); pop.innerHTML = lists.map(l => { const overlap = items.filter(i => l.items.some(x => x.id === i.id)).length; return `
${overlap === items.length ? '⭐' : '☆'}${escapeHtml(l.name)}${overlap}/${items.length}
`; }).join('') + '
+ 新建偏好列表并加入
'; document.body.appendChild(pop); const rect = anchor.getBoundingClientRect(); let left = Math.max(8, Math.min(rect.left, window.innerWidth - pop.offsetWidth - 10)); let top = rect.bottom + 6; if (top + pop.offsetHeight > window.innerHeight - 8) top = Math.max(8, rect.top - pop.offsetHeight - 6); pop.style.left = left + 'px'; pop.style.top = top + 'px'; pop.addEventListener('click', (e) => { e.stopPropagation(); const row = e.target.closest('.pp-row'); if (!row) return; // 在同一个解析副本上完成建表/合并再整体保存(savePreferLists(getPreferLists()) 会把改动丢弃) const lists = getPreferLists(); let l; if (row.classList.contains('pp-new')) { l = { id: 'p' + Date.now(), name: nextPreferName(lists), items: [] }; lists.push(l); } else { l = lists.find(x => x.id === row.dataset.pid); } if (!l) return; const exist = new Set(l.items.map(i => i.id)); let added = 0; items.forEach(it => { if (!exist.has(it.id)) { l.items.push(it); added++; } }); savePreferLists(lists); showToast(added ? `⭐ 已加入 ${l.name}:${added} 项` : `⚠️ 勾选项已全部在 ${l.name} 中`); closePreferPopover(); renderVideoList(); const d = document.getElementById('bili-force-drawer'); if (d && d.classList.contains('mode-prefer')) renderPreferView(); }); preferPopEl = pop; setTimeout(() => { document.addEventListener('click', closePreferPopover, true); }, 0); } // ========== 8.7 视频标题右侧 ⭐(仅偏好收录) ========== // 在 h1 视频标题右边注入一颗星:点击弹出偏好选择浮层,只加入/移出偏好列表(不碰普通合集勾选逻辑)。 // SPA 切视频后标题会被 B 站重渲染,用轻量轮询保证星星存在性与颜色状态 let titleStarEl = null, titleStarBv = null; function getTitleStarMeta() { const bv = getCurrentBVID(); if (!bv || !/\/video\//.test(location.pathname)) return null; const h1 = document.querySelector('h1.video-title') || document.querySelector('.video-info-container h1') || document.querySelector('.video-title'); if (!h1) return null; let title = h1.getAttribute('data-title') || h1.getAttribute('title') || h1.textContent.trim(); if (!title) title = (document.title || '').replace(/_哔哩哔哩_bilibili.*$/, '').trim(); return { bv, title: title || bv, h1 }; } function ensureTitleStar() { const meta = getTitleStarMeta(); if (!meta) { if (titleStarEl) { titleStarEl.remove(); titleStarEl = null; titleStarBv = null; } return; } if (!titleStarEl || !titleStarEl.isConnected || titleStarBv !== meta.bv) { if (titleStarEl && titleStarEl.isConnected) titleStarEl.remove(); const star = document.createElement('span'); star.className = 'bili-title-star'; star.title = '加入/移出偏好列表'; star.style.cssText = 'display:inline-block;margin-left:8px;cursor:pointer;font-size:18px;line-height:1;vertical-align:middle;user-select:none;transition:transform 0.15s,opacity 0.15s;'; star.addEventListener('click', (e) => { e.stopPropagation(); e.preventDefault(); const m = getTitleStarMeta(); if (!m) return; showPreferPopover(star, { id: m.bv, bv: m.bv, p: null, title: m.title }); // 纯 BV=全分P放行 }); meta.h1.parentNode.insertBefore(star, meta.h1.nextSibling); titleStarEl = star; titleStarBv = meta.bv; } const inPrefer = getPreferLists().some(l => (l.items || []).some(i => i.id === meta.bv)); const want = inPrefer ? '⭐' : '☆'; if (titleStarEl.textContent !== want) { titleStarEl.textContent = want; titleStarEl.style.opacity = inPrefer ? '1' : '0.45'; } } setInterval(ensureTitleStar, 1000); // ========== 9. 初始化 ========== function init() { cleanupLegacyCache(); injectStyles(); function onBodyReady() { createTriggerButton(); createOverlay(); createDrawer(); setupThemeListener(); bindEvents(); syncForceStartState(); checkAndHijack(); setupVideoEndListener(); resetVideo(); // 整页加载时播放器 video 元素创建晚于 DOMContentLoaded,一次 resetVideo 摸不到就再也没人归零; // 重试链幂等且开销可忽略(querySelectorAll + 事件绑定) [400, 1000, 2000, 3500, 6000].forEach(t => setTimeout(resetVideo, t)); // 应用美化配置(磨砂/背景) applyCurrentBg(); // 初始化检查:如果当前不在勾选列表里,跳回第一个 setTimeout(redirectToFirstCheckedIfNeeded, 800); console.log(LOG_PREFIX, 'V7.2 就绪,新增偏好列表(PreferList):⭐跨合集收集 + 按偏好顺序播放'); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { document.body ? onBodyReady() : setTimeout(onBodyReady, 50); }); } else { document.body ? onBodyReady() : setTimeout(onBodyReady, 50); } } GM_registerMenuCommand('打开列表管理器', openPanel); GM_registerMenuCommand('强制从头播放:切换', () => { window.__biliForceStartEnabled = !window.__biliForceStartEnabled; panelState.forceFromStart = window.__biliForceStartEnabled; try { GM_setValue(FORCE_KEY, window.__biliForceStartEnabled); } catch (err) {} updateForceSwitchUI(); if (window.__biliForceStartEnabled) resetVideo(); showToast(window.__biliForceStartEnabled ? '✅ 强制从头播放已开启' : '⏸ 强制从头播放已关闭'); }); GM_registerMenuCommand('切换明暗主题(不跟随页面时有效)', () => { if (getThemeFollow()) { showToast('⚠️ 当前为跟随页面模式,请先在面板中关闭跟随'); return; } toggleThemeManual(); }); init(); })(); /* * ⚠️ 维护者必读(血泪教训,勿动): * 本脚本对 localStorage 等采用的暴力拦截(原型劫持/全量覆写等看似"过重"的手段), * 是为了对抗 B 站 SPA 的异步多重反拦截——路由切换/分P跳转时会多轮异步恢复原生行为, * 温和的单次拦截都会被逐步绕过或还原。 * 此结论来自多次试错的最终收敛:不要改动任何拦截函数,哪怕是"看起来可以更优雅"的重构。 */