// ==UserScript==
// @name B站宽屏+
// @namespace https://github.com/wha4up
// @version 1.80.0
// @description 自动宽屏 + 信息/评论/视频/弹幕多标签侧边栏,更高效地浏览视频信息。
// @author wha4up
// @icon https://raw.githubusercontent.com/wha4up/BilibiliWidescreenPlus/refs/heads/main/docs/LOGO.webp
// @license MIT
// @match https://*.bilibili.com/video/*
// @match https://*.bilibili.com/list/*
// @match https://www.bilibili.com/bangumi/play/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_info
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
const config = {
debugMode: GM_getValue('debugMode', false),
playerCenterOffset: 75,
delays: {
stateChangeProcess: 200,
urlCheck: 1000,
finalCheck: 750,
debounce: 200,
observerMaxWait: 20000,
},
intervals: {
check: 500,
wideBtnWait: 100,
contentElementWait: 300,
},
attempts: {
max: 20,
wideBtnWait: 20,
wideBtnExtendedWait: 40,
wideBtnRecoveryMaxRetries: 60,
contentElementWait: 5,
sidebarPollMaxRetries: 10,
commentLazyLoadRelease: 40,
},
animationDurations: {
scroll: 500,
},
styles: {
sidebarTabHeaderHeight: '40px',
bilibiliBlue: '#00a1d6',
defaultVideoTitleFontSize: '22px',
minSidebarWidth: 250,
minPlayerWidth: 640,
sidebarWidthRatio: 0.225,
maxSidebarWidth: 600,
bottomDrawerHandleHeight: '8px',
sidebarContentPadding: '0 16px',
sidebarHeaderBorderWidth: '1px',
},
settingsKeys: {
defaultTab: 'settingDefaultSidebarTab',
autoWideDelay: 'settingAutoWideStartDelay',
borderRadius: 'settingCustomBorderRadius',
borderStrokeWidth: 'settingCustomBorderStrokeWidth',
shadowSpread: 'settingCustomShadowSpread',
shadowBlur: 'settingCustomShadowBlur',
playerSidebarGap: 'settingCustomPlayerSidebarGap',
browserEdgeMargin: 'settingCustomBrowserEdgeMargin',
playerCenterOffset: 'settingPlayerCenterOffset',
minSidebarWidth: 'settingMinSidebarWidth',
maxSidebarWidth: 'settingMaxSidebarWidth',
},
defaultSettings: {
defaultTab: 'comments',
autoWideDelay: 500,
borderRadius: '6px',
borderStrokeWidth: '1px',
shadowSpread: '2px',
shadowBlur: '4px',
playerSidebarGap: '12px',
browserEdgeMargin: '12px',
playerCenterOffset: 75,
minSidebarWidth: 250,
maxSidebarWidth: 600,
},
featureTogglesKeys: {
enableWideScreen: 'enableWideScreen',
enableSidebar: 'enableSidebar',
},
defaultFeatureToggles: {
enableWideScreen: false,
enableSidebar: true,
}
};
const SELECTORS = {
player: '#bilibili-player',
playerContainer: '.bpx-player-container',
playerAlternativeContainer: '#bilibiliPlayer',
playerWrap: '#playerWrap',
playerCtrlArea: '.bpx-player-ctrl-area',
wideBtn: '.bpx-player-ctrl-wide',
webFullBtn: '.bpx-player-ctrl-web',
fullBtn: '.bpx-player-ctrl-full',
viewpointBtn: '.bpx-player-ctrl-viewpoint',
videoArea: '.bpx-player-video-area',
playerPlaceholderTop: '#bilibili-player-placeholder-top',
sendingBar: '.bpx-player-sending-bar',
playerPlaceholderBottom: '#bilibili-player-placeholder-bottom',
commentContainer: '#bili-custom-comment-sidebar',
commentApp: ':is(#commentapp, #comment-module)',
commentBottomFixedWrapper: '.bili-comments-bottom-fixed-wrapper',
commentInputCandidates: [
'.bili-comments-bottom-fixed-wrapper',
'.reply-box-warp', '.reply-box-wrap', '.reply-box-container', '.reply-box',
'.commentbox', '.comment-box', '.comment-send', '.bili-comment-box',
'.comment-input-container', '.comment-submit-container'
].join(','),
allTabsContentArea: '#bili-custom-all-tabs-content-area',
videoTitle: '.video-title',
videoInfoMeta: '.video-info-meta',
videoInfoDetailList: '.video-info-detail-list',
showMoreBtnDetail: '.show-more-btn.detail',
videoDescContainer: '.video-desc-container',
basicDescInfo: '.basic-desc-info',
videoTagContainer: '.video-tag-container',
upPanelContainer: '.up-panel-container',
videoInfoContainerWin: '.video-info-container.win',
rcmdTab: '.rcmd-tab',
actionList: '.action-list-container',
recommendListV1: '.recommend-list-v1',
recommendListContainer: '.recommend-list-container',
episodeList: '[class*="Paginated"][class*="List_root"]',
recommendListBangumi: '[class*="recommend_wrap"]',
recommendListFallback: '.right-container .recommend-list-container, .right-container .recommend-list-v1, .right-container .video-card-list, .right-container .video-page-card-small',
danmakuModules: '.video-pod-above-modules, #danmukuBox',
danmakuBox: '#danmukuBox',
adCard: '.video-card-ad-small',
adReport: '.ad-report',
rightContainer: '.right-container',
fixedSidenavRail: '.fixed-sidenav-storage',
videoToolbarContainer: '.video-toolbar-container',
bangumiVideoToolbar: '.player-left-components .toolbar',
bangumiVideoToolbarRoot: '.toolbar',
bangumiMediaInfo: '[class*="mediainfo_mediaInfoWrap"]',
bangumiMediaDescSection: '[class*="mediainfo_media_desc_section"]',
arcToolbarReport: '#arc_toolbar_report',
viewboxReport: '#viewbox_report',
mirrorVdcon: '#mirror-vdcon',
leftContainer: '.left-container',
settingsPanel: '#bili-plus-settings-panel',
biliReportWrap: '#bili_report_wrap',
mainContentContainer: '#app',
};
const SCRIPT_ELEMENT_IDS = {
commentContainer: 'bili-custom-comment-sidebar',
allTabsContentArea: 'bili-custom-all-tabs-content-area',
bottomDrawerWrapper: 'bili-custom-bottom-drawer-wrapper',
bottomDrawerButton: 'bili-custom-bottom-drawer-button',
bottomDrawerContent: 'bili-custom-bottom-drawer-content',
settingsPanel: 'bili-plus-settings-panel',
playerPlaceholderTop: 'bilibili-player-placeholder-top',
playerPlaceholderBottom: 'bilibili-player-placeholder-bottom'
};
const CSS_CLASSES = {
commentSidebar: SCRIPT_ELEMENT_IDS.commentContainer,
commentSidebarActive: `${SCRIPT_ELEMENT_IDS.commentContainer}--active`,
sidebarTabHeader: 'bili-sidebar-tab-header',
sidebarTab: 'bili-sidebar-tab',
sidebarTabActive: 'bili-sidebar-tab--active',
sidebarTabIndicator: 'bili-sidebar-tab-indicator',
sidebarTabContentWrapper: 'bili-sidebar-tab-content-wrapper',
sidebarTabContentWrapperActive: 'bili-sidebar-tab-content-wrapper--active',
sidebarTabContent: 'bili-sidebar-tab-content',
sidebarTabContentActive: 'bili-sidebar-tab-content--active',
infoTabTop: 'bili-info-tab-top-content',
infoTabMiddle: 'bili-info-tab-middle-content',
infoTabBottom: 'bili-info-tab-bottom-content',
bottomDrawerWrapper: SCRIPT_ELEMENT_IDS.bottomDrawerWrapper,
bottomDrawerButton: SCRIPT_ELEMENT_IDS.bottomDrawerButton,
bottomDrawerContent: SCRIPT_ELEMENT_IDS.bottomDrawerContent,
drawerContentExpanded: 'bili-drawer-content-expanded',
bodyEnhancementsActive: 'bili-custom-enhancements-active',
miniPlayerActive: 'bili-plus-mini-player-active',
};
const SVG_ICONS = {
info: '',
comments: '',
videos: '',
danmaku: '',
};
const SIDEBAR_TABS_CONFIG = [
{ id: 'info', text: '信息', svg: SVG_ICONS.info, paneId: 'infoContentPane', wrapperId: 'infoContentWrapper' },
{ id: 'comments', text: '评论', svg: SVG_ICONS.comments, paneId: 'commentsContentPane', wrapperId: 'commentsContentWrapper' },
{ id: 'videos', text: '视频', svg: SVG_ICONS.videos, paneId: 'videosContentPane', wrapperId: 'videosContentWrapper' },
{ id: 'danmaku', text: '弹幕', svg: SVG_ICONS.danmaku, paneId: 'danmakuContentPane', wrapperId: 'danmakuContentWrapper' }
];
const VALID_SIDEBAR_TAB_IDS = SIDEBAR_TABS_CONFIG.map(t => t.id);
const PLAYER_STATES = {
NORMAL: 'normal',
WIDE: 'wide',
WEB_FULLSCREEN: 'web',
FULLSCREEN: 'full',
};
let elements = {
player: null, playerContainer: null, playerWrap: null, wideBtn: null,
commentContainer: null, sidebarTabHeader: null, sidebarTabIndicator: null, allTabsContentArea: null,
infoTab: null, commentsTab: null, videosTab: null, danmakuTab: null,
infoContentPane: null, commentsContentPane: null, videosContentPane: null, danmakuContentPane: null,
infoContentWrapper: null, commentsContentWrapper: null, videosContentWrapper: null, danmakuContentWrapper: null,
infoTabTopContent: null, infoTabMiddleContent: null, infoTabBottomContent: null,
bottomDrawerWrapper: null, bottomDrawerButton: null, bottomDrawerContent: null,
commentApp: null,
rcmdTabElement: null,
actionListElement: null,
recommendListV1Element: null,
recommendListContainerElement: null,
episodeListElement: null,
bangumiMediaInfoElement: null,
bangumiMediaDescSectionElement: null,
recommendListBangumiElement: null,
videoTitleElement: null, originalVideoTitleElementHolder: { originalFontSize: '' },
videoInfoMetaElement: null,
videoDescContainerElement: null,
videoTagContainerElement: null,
upPanelContainerElement: null,
danmakuModulesElement: null,
videoToolbarContainerElement: null,
videoInfoContainerWinElement: null,
viewboxReportElement: null,
mirrorVdcon: null, originalMirrorVdconHeight: '', originalMirrorVdconPaddingLeft: '',
settingsPanel: null,
};
let currentSettings = {};
let currentUrl = window.location.href;
let navigationObserver = null;
let reInitScheduled = false;
let lastScrollTime = 0;
let isScrolling = false;
let pendingScrollOperation = null;
let autoWideMenuId = null, sidebarMenuId = null, openSettingsPanelMenuId = null;
let sidebarUpdateRAFId = null;
let lastObservedPlayerWidth = 0;
let lastObservedPlayerHeight = 0;
let viewportSuspendedForSize = false;
let userManuallyExitedWide = false;
let currentActiveSidebarTabId = config.defaultSettings.defaultTab;
let coreElementsObserver = null;
let playerStateObserver = null;
let dynamicBgObserver = null;
let fsHandlerRef = null;
let videoAreaDblClickListenerRef = null;
let playerResizeObserver = null;
let miniPlayerObserver = null;
let miniPlayerCompatibilityActive = false;
let windowResizeHandlerRef = null;
let activeTimers = new Set();
let commentProjectionState = { app: null, input: null, floatingInput: null, originalStyle: null, originalInputStyle: null, originalFloatingInputStyle: null, active: false, suspended: false, videoId: null, inputOffsetTop: null, inputStickyThreshold: 160, floatingInputVisible: false, scrollHandler: null, inputInsideApp: false };
let commentNativeActivationState = { anchor: null, originalStyle: null, videoId: null, active: false };
let commentAppRef = null;
function setCommentApp(el) { commentAppRef = (el && typeof WeakRef === 'function') ? new WeakRef(el) : el; }
function getCommentApp() { return (commentAppRef && typeof commentAppRef.deref === 'function') ? commentAppRef.deref() : commentAppRef; }
let scheduledCommentPreactivationVideoId = null;
let lastCommentActivationNudgeVideoId = null;
let sidebarTabStateAppliedVideoId = null;
let sidebarHiddenByCondition = false;
let nonCommentNavigationState = { active: false, previousUrl: '', nextUrl: '', previousVideoId: null, nextVideoId: null, oldTitleText: '', oldDocumentTitle: '', startedAt: 0, oldSourceElements: new WeakSet(), ready: true };
let playerResizeDebouncedRef = null;
let miniPlayerDebouncedRef = null;
let dynamicBgDebouncedRef = null;
let scriptUIAnchorClickRef = null;
let enhancedFeaturesApplyPromise = null;
let pendingNativeLayoutRestoreTimer = null;
let lastMenuTexts = { autoWide: null, sidebar: null, settings: null };
const featureToggleCache = { enableWideScreen: null, enableSidebar: null };
const layoutQueryCache = new Map();
const LAYOUT_QUERY_CACHE_TTL_MS = 16;
const missingElementWarned = new Set();
// --- Utility Functions ---
function log(...args) { if (config.debugMode) console.log(`[B站宽屏+]`, ...args); }
function warn(...args) { if (config.debugMode) console.warn(`[B站宽屏+]`, ...args); }
function error(...args) { console.error(`[B站宽屏+]`, ...args); }
function debounce(func, delay) {
let timeoutId;
const wrapper = function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
wrapper.cancel = () => clearTimeout(timeoutId);
return wrapper;
}
const seqRegistry = Object.create(null);
const SEQ = {
commentProjection: 'commentProjection',
commentPreactivation: 'commentPreactivation',
sidebarContent: 'sidebarContent',
sidebarWarmup: 'sidebarWarmup',
toolbarDrawer: 'toolbarDrawer',
init: 'init',
};
function bumpSeq(name) { return (seqRegistry[name] = (seqRegistry[name] || 0) + 1); }
function seqOf(name) { return seqRegistry[name] || 0; }
function isStaleSeq(name, id) { return seqOf(name) !== id; }
function setAttrIfChanged(el, name, value) {
if (!el) return;
const v = `${value}`;
if (el.getAttribute(name) === v) return;
el.setAttribute(name, v);
}
function assignStyleIfChanged(el, styles) {
if (!el) return;
for (const prop in styles) {
const v = styles[prop];
if (el.style[prop] !== v) el.style[prop] = v;
}
}
function setCssVarsIfChanged(el, vars) {
if (!el) return;
for (const name in vars) {
const v = `${vars[name]}`;
if (el.style.getPropertyValue(name) !== v) el.style.setProperty(name, v);
}
}
function discardOwnMutations() {
[playerStateObserver, miniPlayerObserver, dynamicBgObserver].forEach(observer => {
try { observer?.takeRecords(); } catch (e) { }
});
}
function waitForElementObserved(selector, timeoutMs = 2000) {
const immediate = document.querySelector(selector);
if (immediate) return Promise.resolve(immediate);
return new Promise(resolve => {
let settled = false;
const finish = (el) => {
if (settled) return;
settled = true;
observer.disconnect();
clearTimeout(timer);
resolve(el || null);
};
const observer = new MutationObserver(() => {
const el = document.querySelector(selector);
if (el) finish(el);
});
const timer = setTimeout(() => finish(document.querySelector(selector)), Math.max(16, timeoutMs));
observer.observe(document.documentElement, { childList: true, subtree: true });
});
}
function pickRichestElement(candidates) {
let best = null;
let bestScore = -1;
for (const el of candidates) {
if (!el || el.nodeType !== 1) continue;
const rect = el.getBoundingClientRect();
const visible = rect.width > 0 && rect.height > 0;
const score = (visible ? 1e6 : 0) + el.getElementsByTagName('*').length;
if (score > bestScore) { bestScore = score; best = el; }
}
return best;
}
function isLiveSource(el) {
return !!(el && el.isConnected && document.body.contains(el));
}
function getNavigationKey(url) {
try {
const u = new URL(url, window.location.origin);
const videoId = getVideoIdFromUrl(url) || '';
const part = u.searchParams.get('p') || '';
return `${u.pathname}|${videoId}|${part}|${u.hash}`;
} catch (e) {
return String(url);
}
}
// --- Feature Toggle Cache ---
function getFeatureToggle(key) {
const cached = featureToggleCache[key];
if (cached !== null && cached !== undefined) return cached;
const value = GM_getValue(key, config.defaultFeatureToggles[key]);
featureToggleCache[key] = value;
return value;
}
function setFeatureToggle(key, value) {
featureToggleCache[key] = value;
GM_setValue(key, value);
}
function refreshFeatureToggleCache() {
Object.keys(config.featureTogglesKeys).forEach(k => { featureToggleCache[k] = null; });
}
// --- Timer Management ---
function safeSetTimeout(fn, delay) {
const timerId = setTimeout(() => {
fn();
activeTimers.delete(timerId);
}, delay);
activeTimers.add(timerId);
return timerId;
}
function clearAllTimers() {
log(`Clearing ${activeTimers.size} active timers.`);
activeTimers.forEach(timerId => clearTimeout(timerId));
activeTimers.clear();
}
// --- 事件驱动等待 ---
const pendingDomWaits = new Set();
function cancelDomWaits() {
pendingDomWaits.forEach(cancel => cancel());
pendingDomWaits.clear();
}
function waitForDomChange(callback, { tokenName = null, token = null, timeoutMs = 800, minGapMs = 120 } = {}) {
let done = false;
let timeoutId = null;
let wakeId = null;
let lastWakeAt = 0;
const cleanup = () => {
observer.disconnect();
if (timeoutId) { clearTimeout(timeoutId); activeTimers.delete(timeoutId); timeoutId = null; }
if (wakeId) { clearTimeout(wakeId); activeTimers.delete(wakeId); wakeId = null; }
pendingDomWaits.delete(cancel);
};
const finish = () => {
if (done) return;
done = true;
cleanup();
if (tokenName && isStaleSeq(tokenName, token)) return;
callback();
};
const wake = () => {
if (done) return;
const now = performance.now();
const gap = minGapMs - (now - lastWakeAt);
if (gap <= 0) { lastWakeAt = now; finish(); return; }
if (wakeId) return;
wakeId = safeSetTimeout(() => {
wakeId = null;
lastWakeAt = performance.now();
finish();
}, gap);
};
const observer = new MutationObserver(wake);
observer.observe(document.documentElement, { childList: true, subtree: true });
timeoutId = safeSetTimeout(finish, timeoutMs);
const cancel = () => {
if (done) return;
done = true;
cleanup();
};
pendingDomWaits.add(cancel);
return cancel;
}
async function waitForSpecificElement(selector, options = {}) {
const {
attempts = config.attempts.max,
interval = config.intervals.check,
onTimeout = null,
timeoutMessage = null,
required = false
} = options;
const element = await waitForElementObserved(selector, attempts * interval);
if (element) return element;
const budgetMs = attempts * interval;
const message = timeoutMessage || `waitForSpecificElement: "${selector}" not found within ${budgetMs}ms.`;
warn(message);
if (required) {
error(`waitForSpecificElement: Required element "${selector}" not found. This may critically affect script functionality.`);
}
if (onTimeout && typeof onTimeout === 'function') {
onTimeout(selector, attempts);
}
return null;
}
function validateCssLength(value, defaultValue = '0px') {
if (typeof value !== 'string' && typeof value !== 'number') return defaultValue;
value = String(value).trim();
if (/^\d+(\.\d+)?px$/i.test(value)) return value;
if (/^-?\d+(\.\d+)?$/.test(value)) return value + 'px';
warn(`Invalid CSS length: "${value}", using default: "${defaultValue}"`);
return defaultValue;
}
function parseCssLengthToPx(value, fallbackValue) {
const validated = validateCssLength(value, fallbackValue);
const str = String(validated).trim();
if (/^-?\d+(\.\d+)?$/.test(str)) return parseFloat(str);
if (/^-?\d+(\.\d+)?px$/i.test(str)) return parseFloat(str);
const fallbackValidated = validateCssLength(fallbackValue, '0px');
const fallbackNum = parseFloat(fallbackValidated);
return Number.isFinite(fallbackNum) ? fallbackNum : 0;
}
function readLayoutSettings() {
return {
gap: parseCssLengthToPx(currentSettings.playerSidebarGap, config.defaultSettings.playerSidebarGap),
edgeMargin: parseCssLengthToPx(currentSettings.browserEdgeMargin, config.defaultSettings.browserEdgeMargin),
minSidebarWidth: Number.isFinite(currentSettings.minSidebarWidth) ? currentSettings.minSidebarWidth : config.styles.minSidebarWidth,
maxSidebarWidth: Number.isFinite(currentSettings.maxSidebarWidth) ? currentSettings.maxSidebarWidth : config.styles.maxSidebarWidth,
};
}
function validateNonNegativeInt(value, defaultValue = 0) {
const num = parseInt(value, 10);
if (!isNaN(num) && num >= 0) return num;
warn(`Invalid non-negative integer: "${value}", using default: ${defaultValue}`);
return defaultValue;
}
function getVideoIdFromUrl(urlString) {
try {
const url = new URL(urlString, window.location.origin);
if (url.pathname.includes('/video/')) {
return url.pathname.split('/').find(p => /^BV[0-9A-Za-z]{10}$/.test(p)) || null;
}
if (url.pathname.includes('/list/')) {
return url.searchParams.get('bvid');
}
if (url.pathname.includes('/bangumi/play/')) {
return url.searchParams.get('ep_id') || (url.pathname.match(/\/(?:ep|ss)\d+/) || [])[0] || null;
}
} catch (e) {
error("Failed to parse URL for video ID:", e);
}
return null;
}
function getCurrentVideoId() {
return getVideoIdFromUrl(window.location.href);
}
function isScriptManagedElement(element) {
if (!element || typeof element.closest !== 'function') return false;
return !!element.closest(`#${SCRIPT_ELEMENT_IDS.commentContainer}, #${SCRIPT_ELEMENT_IDS.bottomDrawerWrapper}, #${SCRIPT_ELEMENT_IDS.settingsPanel}`);
}
function queryPageElement(selector) {
const candidates = Array.from(document.querySelectorAll(selector))
.filter(el => !isScriptManagedElement(el));
return pickRichestElement(candidates);
}
function clearCommentAppReferences() {
setCommentApp(null);
if (elements.commentsContentPane && currentActiveSidebarTabId === 'comments') elements.commentsContentPane.textContent = '';
}
function getInlineStyleSnapshot(element, props) {
const snapshot = {};
props.forEach(prop => { snapshot[prop] = element.style[prop] || ''; });
return snapshot;
}
function restoreInlineStyleSnapshot(element, snapshot) {
if (!element || !snapshot) return;
Object.keys(snapshot).forEach(prop => { element.style[prop] = snapshot[prop]; });
}
function findCommentInputElement(commentApp) {
const allCandidates = Array.from(document.querySelectorAll(SELECTORS.commentInputCandidates))
.filter(el => !isScriptManagedElement(el))
.filter(el => {
const rect = el.getBoundingClientRect();
const text = (el.innerText || el.textContent || '').trim();
const hasEditable = !!el.querySelector('textarea, input, [contenteditable="true"], .ql-editor');
const isKnownFixedWrapper = el.matches?.(SELECTORS.commentBottomFixedWrapper);
return isKnownFixedWrapper || ((rect.width > 80 && rect.height > 20) && (hasEditable || /评论|回复|发送/.test(text)));
});
if (!allCandidates.length) return null;
if (commentApp) {
const inside = allCandidates.filter(el => commentApp.contains(el) && !el.matches?.(SELECTORS.commentBottomFixedWrapper));
if (inside.length) return inside[inside.length - 1];
}
const nonFloating = allCandidates.filter(el => !el.matches?.(SELECTORS.commentBottomFixedWrapper));
if (nonFloating.length) return nonFloating[nonFloating.length - 1];
return null;
}
let bottomFixedWrapperCache = null;
function findBottomFixedCommentWrapper() {
if (bottomFixedWrapperCache && document.body.contains(bottomFixedWrapperCache) && !isScriptManagedElement(bottomFixedWrapperCache)) {
return bottomFixedWrapperCache;
}
const wrapper = queryPageElement(SELECTORS.commentBottomFixedWrapper);
bottomFixedWrapperCache = (wrapper && !isScriptManagedElement(wrapper)) ? wrapper : null;
return bottomFixedWrapperCache;
}
function findPageCommentApp() {
const direct = queryPageElement(SELECTORS.commentApp);
if (direct) return direct;
const cachedCommentApp = getCommentApp();
if (cachedCommentApp && !isScriptManagedElement(cachedCommentApp) && document.body.contains(cachedCommentApp)) return cachedCommentApp;
return null;
}
let commentAppAppearanceObserver = null;
function watchCommentAppAppearance() {
if (commentAppAppearanceObserver || !document.body) return;
const stop = () => {
if (!commentAppAppearanceObserver) return;
commentAppAppearanceObserver.disconnect();
commentAppAppearanceObserver = null;
};
commentAppAppearanceObserver = new MutationObserver(() => {
if (currentActiveSidebarTabId !== 'comments') { stop(); return; }
if (!findPageCommentApp()) return;
stop();
updateCommentProjectionVisibility();
});
commentAppAppearanceObserver.observe(document.body, { childList: true, subtree: true });
safeSetTimeout(stop, 30000);
}
function findCommentActivationAnchor() {
const selectors = [
SELECTORS.commentApp,
'.reply-wrap', '.reply-warp', '.comment-container', '.bili-comment-container',
'.bili-comments', '.comments-container', '#comment', '#comments'
].join(',');
const candidates = Array.from(document.querySelectorAll(selectors))
.filter(el => !isScriptManagedElement(el));
return candidates.length ? candidates[candidates.length - 1] : null;
}
function restoreCommentNativeActivationAnchor() {
const state = commentNativeActivationState;
if (state.anchor && state.originalStyle) restoreInlineStyleSnapshot(state.anchor, state.originalStyle);
if (state.anchor) {
try { delete state.anchor.dataset.biliPlusNativeActivationProxy; } catch (e) { }
}
commentNativeActivationState = { anchor: null, originalStyle: null, videoId: null, active: false };
}
function preactivateNativeCommentsWithoutScroll() {
const videoId = getCurrentVideoId() || window.location.href;
if (findPageCommentApp()) {
restoreCommentNativeActivationAnchor();
return true;
}
if (commentNativeActivationState.active && commentNativeActivationState.videoId === videoId) return true;
const anchor = findCommentActivationAnchor();
if (!anchor || isScriptManagedElement(anchor)) return false;
restoreCommentNativeActivationAnchor();
const rect = anchor.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return false;
commentNativeActivationState = {
anchor,
originalStyle: getInlineStyleSnapshot(anchor, [
'transform', 'opacity', 'pointerEvents', 'transition', 'willChange', 'visibility'
]),
videoId,
active: true
};
const targetTop = Math.max(80, Math.min(window.innerHeight * 0.35, 220));
const deltaY = Math.round(targetTop - rect.top);
assignStyleIfChanged(anchor, {
transform: `${anchor.style.transform || ''} translate3d(0, ${deltaY}px, 0)`,
opacity: '0',
pointerEvents: 'none',
transition: 'none',
willChange: 'transform',
visibility: 'visible'
});
anchor.dataset.biliPlusNativeActivationProxy = 'true';
safeSetTimeout(() => {
if (findPageCommentApp()) restoreCommentNativeActivationAnchor();
}, 800);
safeSetTimeout(() => {
if (commentNativeActivationState.videoId === videoId) restoreCommentNativeActivationAnchor();
}, 2600);
return true;
}
function shouldPreactivateCommentsBySettings() {
const autoWideEnabled = getFeatureToggle(config.featureTogglesKeys.enableWideScreen);
const sidebarEnabled = getFeatureToggle(config.featureTogglesKeys.enableSidebar);
return !!(autoWideEnabled && sidebarEnabled && isTargetPage(window.location.href));
}
function scheduleCommentNativePreactivation(options = {}) {
const { force = false, reason = 'generic' } = options;
if (!shouldPreactivateCommentsBySettings()) return false;
const videoId = getCurrentVideoId() || window.location.href;
if (!force && scheduledCommentPreactivationVideoId === videoId && (findPageCommentApp() || commentNativeActivationState.active)) {
return true;
}
scheduledCommentPreactivationVideoId = videoId;
const token = bumpSeq(SEQ.commentPreactivation);
const maxAttempts = 16;
const interval = 180;
const runAttempt = (attempt) => {
if (isStaleSeq(SEQ.commentPreactivation, token)) return;
if (!shouldPreactivateCommentsBySettings()) return;
const currentVideoId = getCurrentVideoId() || window.location.href;
if (currentVideoId !== videoId) return;
if (findPageCommentApp()) {
restoreCommentNativeActivationAnchor();
if (currentActiveSidebarTabId === 'comments') updateCommentProjectionVisibility();
return;
}
preactivateNativeCommentsWithoutScroll();
if (attempt < maxAttempts) {
safeSetTimeout(() => runAttempt(attempt + 1), interval);
} else {
warn(`scheduleCommentNativePreactivation: comment app still not found after ${maxAttempts + 1} attempts. reason=${reason}`);
}
};
safeSetTimeout(() => runAttempt(0), force ? 20 : 80);
return true;
}
function hideCommentAppWhileSuspended(app) {
if (!app || !document.body.contains(app)) return;
assignStyleIfChanged(app, {
position: 'fixed',
left: '-100000px',
top: '0px',
width: '1px',
height: '1px',
maxHeight: '1px',
overflow: 'hidden',
zIndex: '-1',
boxSizing: 'border-box',
backgroundColor: 'transparent',
margin: '0',
paddingRight: '0',
paddingBottom: '0',
scrollbarGutter: 'auto',
transform: 'none',
opacity: '0',
pointerEvents: 'none'
});
app.dataset.biliPlusCommentProjected = 'suspended';
app.dataset.biliPlusCommentSuspended = 'true';
}
function deactivateCommentProjection({ keepReference = true, restoreToPage = true } = {}) {
const state = commentProjectionState;
const app = state.app;
if (app) {
if (state.scrollHandler) {
try { app.removeEventListener('scroll', state.scrollHandler); } catch (e) { }
}
if (restoreToPage || !keepReference) {
restoreInlineStyleSnapshot(app, state.originalStyle);
try {
delete app.dataset.biliPlusCommentProjected;
delete app.dataset.biliPlusCommentSuspended;
} catch (e) { }
} else {
hideCommentAppWhileSuspended(app);
}
}
if (state.input) {
restoreInlineStyleSnapshot(state.input, state.originalInputStyle);
try { delete state.input.dataset.biliPlusCommentInputProjected; } catch (e) { }
}
if (state.floatingInput && state.floatingInput !== state.input) {
restoreInlineStyleSnapshot(state.floatingInput, state.originalFloatingInputStyle);
try { delete state.floatingInput.dataset.biliPlusCommentInputProjected; } catch (e) { }
}
const keepSuspendedSnapshot = !!(keepReference && !restoreToPage && app);
commentProjectionState = {
app: keepReference ? app : null,
input: null,
floatingInput: null,
originalStyle: keepSuspendedSnapshot ? state.originalStyle : null,
originalInputStyle: null,
originalFloatingInputStyle: null,
active: false,
suspended: keepSuspendedSnapshot,
videoId: keepReference ? state.videoId : null,
inputOffsetTop: null,
inputStickyThreshold: 160,
floatingInputVisible: false,
scrollHandler: null,
inputInsideApp: false
};
if (!keepReference) setCommentApp(null);
}
let lastCommentPageRequestAt = 0;
function releaseNativeCommentLazyLoad(commentComponent) {
const pendingLazyLoad = commentComponent?.lazyLoadDP;
if (!pendingLazyLoad || typeof pendingLazyLoad.resolve !== 'function') return false;
pendingLazyLoad.resolve();
return true;
}
// B 站评论组件的原生懒加载要等 IntersectionObserver 报一次 isIntersecting 才会拉取列表,
// 未收到时会一直停在「加载中」;投影就绪后主动放行,组件尚未挂载/升级时稍后重试。
function ensureNativeCommentLazyLoadReleased(app, retryCount = 0) {
const state = commentProjectionState;
if (!state.active || state.app !== app || retryCount > config.attempts.commentLazyLoadRelease) return;
if (releaseNativeCommentLazyLoad(app.querySelector('bili-comments'))) return;
safeSetTimeout(() => ensureNativeCommentLazyLoadReleased(app, retryCount + 1), 250);
}
function requestNextCommentPage(app) {
if (!app || !app.isConnected) return false;
const commentComponent = app.querySelector('bili-comments');
if (!commentComponent) return false;
if (commentComponent.showSpinner === true) {
releaseNativeCommentLazyLoad(commentComponent);
return false;
}
if (commentComponent.showEnd === true || commentComponent.showContinuations === true) return false;
const now = Date.now();
if (now - lastCommentPageRequestAt < 250) return false;
lastCommentPageRequestAt = now;
if (typeof commentComponent.getList === 'function') {
try {
Promise.resolve(commentComponent.getList())
.catch(e => warn('requestNextCommentPage: getList failed.', e));
} catch (e) {
warn('requestNextCommentPage: getList threw.', e);
}
return true;
}
try {
if (commentComponent.scrollContainer !== app) commentComponent.scrollContainer = app;
window.dispatchEvent(new Event('scroll'));
return true;
} catch (e) {
return false;
}
}
function syncCommentProjection() {
const state = commentProjectionState;
if (!state.active || !state.app || !elements.commentsContentPane) return false;
if (!document.body.contains(state.app) || !document.body.contains(elements.commentsContentPane)) {
deactivateCommentProjection({ keepReference: false });
if (currentActiveSidebarTabId === 'comments') {
safeSetTimeout(() => updateCommentProjectionVisibility(), 120);
}
return false;
}
const paneRect = elements.commentsContentPane.getBoundingClientRect();
if (paneRect.width <= 0 || paneRect.height <= 0) return false;
if (!state.input || !document.body.contains(state.input)) {
state.input = findCommentInputElement(state.app);
if (state.input && !state.originalInputStyle) {
const appRectBeforeProjection = state.app.getBoundingClientRect();
const inputRectBeforeProjection = state.input.getBoundingClientRect();
const rawOffset = Math.round(inputRectBeforeProjection.top - appRectBeforeProjection.top);
state.inputOffsetTop = Number.isFinite(rawOffset) ? Math.max(0, Math.min(rawOffset, Math.floor(paneRect.height * 0.45))) : 0;
state.originalInputStyle = getInlineStyleSnapshot(state.input, [
'position', 'left', 'top', 'right', 'bottom', 'width', 'height', 'maxHeight', 'overflow',
'zIndex', 'boxSizing', 'backgroundColor', 'margin', 'padding', 'transform', 'opacity', 'pointerEvents', 'display',
'minWidth', 'maxWidth', 'clipPath', 'contain', 'visibility'
]);
state.input.dataset.biliPlusCommentInputProjected = 'true';
}
}
let inputHeight = 0;
if (state.input && document.body.contains(state.input)) {
state.inputInsideApp = state.app.contains(state.input);
const inputRect = state.input.getBoundingClientRect();
inputHeight = Math.max(46, Math.min(Math.round(inputRect.height || 58), Math.floor(paneRect.height * 0.28)));
if (state.inputInsideApp) {
assignStyleIfChanged(state.input, {
position: 'sticky',
left: '',
top: 'auto',
right: '',
bottom: '0px',
width: '100%',
minWidth: '0',
maxWidth: '100%',
height: '',
maxHeight: '',
overflow: 'hidden',
clipPath: 'inset(0 0 0 0)',
contain: 'layout paint',
zIndex: '1004',
boxSizing: 'border-box',
backgroundColor: 'var(--bg1_float, #fff)',
margin: '0',
transform: 'none',
opacity: '1',
pointerEvents: 'auto',
display: ''
});
} else {
const originalOffset = Number.isFinite(state.inputOffsetTop) ? state.inputOffsetTop : 0;
const scrollTop = Math.max(0, Math.round(state.app.scrollTop || 0));
const threshold = Number.isFinite(state.inputStickyThreshold) ? state.inputStickyThreshold : Math.max(120, originalOffset + inputHeight);
const isBottomFixedWrapper = state.input.matches?.(SELECTORS.commentBottomFixedWrapper);
const shouldFloatBottom = scrollTop > threshold;
if (isBottomFixedWrapper && !shouldFloatBottom) {
assignStyleIfChanged(state.input, {
position: 'fixed',
left: `${Math.round(paneRect.left)}px`,
top: `${Math.round(paneRect.bottom)}px`,
right: 'auto',
bottom: 'auto',
width: `${Math.round(paneRect.width)}px`,
minWidth: `${Math.round(paneRect.width)}px`,
maxWidth: `${Math.round(paneRect.width)}px`,
height: `${inputHeight}px`,
maxHeight: `${inputHeight}px`,
overflow: 'hidden',
clipPath: 'inset(0 0 100% 0)',
contain: 'layout paint',
zIndex: '1004',
boxSizing: 'border-box',
backgroundColor: 'var(--bg1_float, #fff)',
margin: '0',
transform: 'none',
opacity: '0',
pointerEvents: 'none',
visibility: 'hidden',
display: ''
});
inputHeight = 0;
} else {
const normalTop = Math.round(paneRect.top + Math.max(0, originalOffset - scrollTop));
const bottomTop = Math.round(paneRect.bottom - inputHeight);
const projectedTop = shouldFloatBottom ? bottomTop : Math.min(Math.max(Math.round(paneRect.top), normalTop), bottomTop);
assignStyleIfChanged(state.input, {
position: 'fixed',
left: `${Math.round(paneRect.left)}px`,
top: `${projectedTop}px`,
right: 'auto',
bottom: 'auto',
width: `${Math.round(paneRect.width)}px`,
minWidth: `${Math.round(paneRect.width)}px`,
maxWidth: `${Math.round(paneRect.width)}px`,
height: `${inputHeight}px`,
maxHeight: `${inputHeight}px`,
overflow: 'hidden',
clipPath: 'inset(0 0 0 0)',
contain: 'layout paint',
zIndex: '1004',
boxSizing: 'border-box',
backgroundColor: 'var(--bg1_float, #fff)',
margin: '0',
transform: 'none',
opacity: '1',
pointerEvents: 'auto',
visibility: 'visible',
display: ''
});
}
}
}
let floatingInputHeight = 0;
const floatingInput = findBottomFixedCommentWrapper();
if (floatingInput && floatingInput !== state.input && document.body.contains(floatingInput)) {
if (state.floatingInput && state.floatingInput !== floatingInput) {
restoreInlineStyleSnapshot(state.floatingInput, state.originalFloatingInputStyle);
try { delete state.floatingInput.dataset.biliPlusCommentInputProjected; } catch (e) { }
state.originalFloatingInputStyle = null;
}
if (state.floatingInput !== floatingInput) {
state.floatingInput = floatingInput;
state.originalFloatingInputStyle = getInlineStyleSnapshot(floatingInput, [
'position', 'left', 'top', 'right', 'bottom', 'width', 'height', 'maxHeight', 'overflow',
'zIndex', 'boxSizing', 'backgroundColor', 'margin', 'padding', 'transform', 'opacity', 'pointerEvents', 'display',
'minWidth', 'maxWidth', 'clipPath', 'contain', 'visibility'
]);
floatingInput.dataset.biliPlusCommentInputProjected = 'true';
}
const floatingRect = floatingInput.getBoundingClientRect();
const measuredFloatingHeight = Math.max(46, Math.min(Math.round(floatingRect.height || 58), Math.floor(paneRect.height * 0.30)));
const scrollTop = Math.max(0, Math.round(state.app.scrollTop || 0));
const threshold = Math.max(120, Math.min(Math.round(paneRect.height * 0.28), 220));
const shouldShowFloating = scrollTop > threshold;
floatingInputHeight = shouldShowFloating ? measuredFloatingHeight : 0;
assignStyleIfChanged(floatingInput, {
position: 'fixed',
left: `${Math.round(paneRect.left)}px`,
top: `${Math.round(paneRect.bottom - measuredFloatingHeight)}px`,
right: 'auto',
bottom: 'auto',
width: `${Math.round(paneRect.width)}px`,
minWidth: `${Math.round(paneRect.width)}px`,
maxWidth: `${Math.round(paneRect.width)}px`,
height: `${measuredFloatingHeight}px`,
maxHeight: `${measuredFloatingHeight}px`,
overflow: 'hidden',
clipPath: shouldShowFloating ? 'inset(0 0 0 0)' : 'inset(0 0 100% 0)',
contain: 'layout paint',
zIndex: '1005',
boxSizing: 'border-box',
backgroundColor: 'var(--bg1_float, #fff)',
margin: '0',
transform: 'none',
opacity: shouldShowFloating ? '1' : '0',
pointerEvents: shouldShowFloating ? 'auto' : 'none',
visibility: shouldShowFloating ? 'visible' : 'hidden',
display: ''
});
state.floatingInputVisible = shouldShowFloating;
} else if (state.floatingInput && state.floatingInput !== state.input) {
restoreInlineStyleSnapshot(state.floatingInput, state.originalFloatingInputStyle);
try { delete state.floatingInput.dataset.biliPlusCommentInputProjected; } catch (e) { }
state.floatingInput = null;
state.originalFloatingInputStyle = null;
state.floatingInputVisible = false;
}
if (!state.scrollHandler) {
state.scrollHandler = () => {
if (!commentProjectionState.active) return;
syncCommentProjection();
const app = commentProjectionState.app;
if (!app) return;
if (app.scrollHeight - app.scrollTop - app.clientHeight <= 240) requestNextCommentPage(app);
};
state.app.addEventListener('scroll', state.scrollHandler, { passive: true });
}
const appHeight = Math.max(120, Math.round(paneRect.height));
assignStyleIfChanged(state.app, {
position: 'fixed',
left: `${Math.round(paneRect.left)}px`,
top: `${Math.round(paneRect.top)}px`,
width: `${Math.round(paneRect.width)}px`,
height: `${appHeight}px`,
maxHeight: `${appHeight}px`,
overflow: 'auto',
zIndex: '1003',
boxSizing: 'border-box',
backgroundColor: 'var(--bg1_float, #fff)',
margin: '0',
paddingRight: '8px',
paddingBottom: (state.input || state.floatingInput) ? `${Math.max(inputHeight, floatingInputHeight) + 10}px` : '',
scrollbarGutter: 'stable',
transform: 'none',
opacity: '1',
pointerEvents: 'auto'
});
return true;
}
function activateCommentProjection(retryCount = 0, token = seqOf(SEQ.commentProjection)) {
const pane = elements.commentsContentPane;
if (!pane) { warn('activateCommentProjection: Comments pane not found.'); return false; }
if (isStaleSeq(SEQ.commentProjection, token) || currentActiveSidebarTabId !== 'comments') return false;
if (retryCount === 0) preactivateNativeCommentsWithoutScroll();
const commentApp = findPageCommentApp();
if (!commentApp) {
watchCommentAppAppearance();
if (retryCount < config.attempts.max) {
if (currentActiveSidebarTabId === 'comments') pane.textContent = '评论区加载中…';
waitForDomChange(() => {
if (currentActiveSidebarTabId === 'comments') activateCommentProjection(retryCount + 1, token);
}, { tokenName: SEQ.commentProjection, token, timeoutMs: 400 });
} else if (!isStaleSeq(SEQ.commentProjection, token) && currentActiveSidebarTabId === 'comments') {
pane.textContent = `评论区模块 (${SELECTORS.commentApp}) 未在页面找到或加载失败。`;
warn(`activateCommentProjection: Page comment app (${SELECTORS.commentApp}) not found.`);
}
return false;
}
const currentVideoIdForProjection = getCurrentVideoId() || '';
if (commentProjectionState.active && commentProjectionState.app !== commentApp) {
deactivateCommentProjection({ keepReference: false });
}
setCommentApp(commentApp);
if (!commentProjectionState.active) {
const preservedOriginalStyle = (commentProjectionState.app === commentApp && commentProjectionState.originalStyle)
? commentProjectionState.originalStyle
: getInlineStyleSnapshot(commentApp, [
'position', 'left', 'top', 'width', 'height', 'maxHeight', 'overflow',
'zIndex', 'boxSizing', 'backgroundColor', 'margin', 'paddingRight', 'paddingBottom', 'scrollbarGutter', 'transform', 'opacity', 'pointerEvents'
]);
commentProjectionState = {
app: commentApp,
input: null,
floatingInput: null,
originalStyle: preservedOriginalStyle,
originalInputStyle: null,
originalFloatingInputStyle: null,
active: true,
suspended: false,
videoId: currentVideoIdForProjection,
inputOffsetTop: null,
inputStickyThreshold: 160,
floatingInputVisible: false,
scrollHandler: null,
inputInsideApp: false
};
setAttrIfChanged(commentApp, 'data-bili-plus-comment-projected', 'true');
try { delete commentApp.dataset.biliPlusCommentSuspended; } catch (e) { }
setAttrIfChanged(commentApp, 'data-bili-plus-current-video-id', currentVideoIdForProjection);
try { commentApp.scrollTop = 0; } catch (e) { }
} else if (commentProjectionState.videoId !== currentVideoIdForProjection) {
commentProjectionState.videoId = currentVideoIdForProjection;
setAttrIfChanged(commentApp, 'data-bili-plus-current-video-id', currentVideoIdForProjection);
try { commentApp.scrollTop = 0; } catch (e) { }
}
const projectionSynced = syncCommentProjection();
if (!projectionSynced) {
if (retryCount < config.attempts.max) {
pane.textContent = '评论区加载中…';
waitForDomChange(() => {
if (currentActiveSidebarTabId === 'comments') activateCommentProjection(retryCount + 1, token);
}, { tokenName: SEQ.commentProjection, token, timeoutMs: 200 });
} else {
warn('activateCommentProjection: comments pane never got a measurable size; giving up this round.');
}
return false;
}
pane.textContent = '';
ensureNativeCommentLazyLoadReleased(commentApp);
if (commentApp.scrollHeight <= commentApp.clientHeight + 8) requestNextCommentPage(commentApp);
return true;
}
function updateCommentProjectionVisibility() {
const shouldProject = !!(
document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive) &&
elements.commentContainer?.classList.contains(CSS_CLASSES.commentSidebarActive) &&
currentActiveSidebarTabId === 'comments'
);
if (shouldProject) {
const token = seqOf(SEQ.commentProjection);
activateCommentProjection(0, token);
} else if (commentProjectionState.active) {
deactivateCommentProjection({ keepReference: true, restoreToPage: false });
}
}
function restoreCommentAppToPage({ keepReference = false } = {}) {
deactivateCommentProjection({ keepReference });
restoreCommentNativeActivationAnchor();
return true;
}
// --- Core Functionality ---
// --- Settings and Styles ---
function loadAllSettings() {
try {
for (const key in config.settingsKeys) {
currentSettings[key] = GM_getValue(config.settingsKeys[key], config.defaultSettings[key]);
}
currentSettings.autoWideDelay = validateNonNegativeInt(
currentSettings.autoWideDelay,
config.defaultSettings.autoWideDelay
);
currentSettings.playerCenterOffset = Math.max(0, validateNonNegativeInt(
currentSettings.playerCenterOffset,
config.defaultSettings.playerCenterOffset
));
currentSettings.minSidebarWidth = Math.max(0, validateNonNegativeInt(
currentSettings.minSidebarWidth,
config.defaultSettings.minSidebarWidth
));
currentSettings.maxSidebarWidth = Math.max(0, validateNonNegativeInt(
currentSettings.maxSidebarWidth,
config.defaultSettings.maxSidebarWidth
));
refreshFeatureToggleCache();
log("All settings loaded:", currentSettings);
updateCssVariables();
} catch (e) {
error("loadAllSettings: Failed to load settings from GM_storage.", e);
currentSettings = { ...config.defaultSettings };
refreshFeatureToggleCache();
}
}
function updateCssVariables() {
const layoutSettings = readLayoutSettings();
setCssVarsIfChanged(document.documentElement, {
'--biliplus-border-radius': validateCssLength(currentSettings.borderRadius, config.defaultSettings.borderRadius),
'--biliplus-border-stroke-width': validateCssLength(currentSettings.borderStrokeWidth, config.defaultSettings.borderStrokeWidth),
'--biliplus-shadow-blur': validateCssLength(currentSettings.shadowBlur, config.defaultSettings.shadowBlur),
'--biliplus-shadow-spread': validateCssLength(currentSettings.shadowSpread, config.defaultSettings.shadowSpread),
'--biliplus-player-sidebar-gap': `${layoutSettings.gap}px`,
'--biliplus-browser-edge-margin': `${layoutSettings.edgeMargin}px`
});
log("CSS variables updated from currentSettings.");
}
function generateBaseCssString() {
return `
:root {
--biliplus-border-radius: ${config.defaultSettings.borderRadius};
--biliplus-border-stroke-width: ${config.defaultSettings.borderStrokeWidth};
--biliplus-shadow-blur: ${config.defaultSettings.shadowBlur};
--biliplus-shadow-spread: ${config.defaultSettings.shadowSpread};
--biliplus-player-sidebar-gap: ${config.defaultSettings.playerSidebarGap};
--biliplus-browser-edge-margin: ${config.defaultSettings.browserEdgeMargin};
--biliplus-themed-box-shadow-border-color: rgba(0,0,0,0.1);
--dynamic-shadow-color: rgba(0,0,0,0.08);
}
html.dark :root {
--dynamic-shadow-color: rgba(0,0,0,0.15);
--biliplus-themed-box-shadow-border-color: rgba(255,255,255,0.15);
}
#${SCRIPT_ELEMENT_IDS.settingsPanel} {
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
background-color: var(--bg1_float, #fff); color: var(--text1, #212121);
border: 1px solid var(--line_regular, #ddd); border-radius: var(--biliplus-border-radius);
box-shadow: 0 4px 12px rgba(0,0,0,0.15); padding: 20px; z-index: 2000;
width: 520px; max-width: 90vw; max-height: 80vh; overflow-y: auto;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
display: none;
}
#${SCRIPT_ELEMENT_IDS.settingsPanel} h2 {
margin-top: 0; margin-bottom: 20px; font-size: 18px; color: var(--text1, #212121);
border-bottom: 1px solid var(--line_light, #eee); padding-bottom: 10px;
}
#${SCRIPT_ELEMENT_IDS.settingsPanel} .bili-plus-settings-section { margin-bottom: 20px; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} .bili-plus-settings-row { display: flex; gap: 20px; margin-bottom: 10px; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} .bili-plus-setting-item { flex: 1; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} label { display: block; margin-bottom: 4px; font-weight: 500; font-size: 13px; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} input[type="text"], #${SCRIPT_ELEMENT_IDS.settingsPanel} input[type="number"], #${SCRIPT_ELEMENT_IDS.settingsPanel} select {
width: 100%; padding: 6px 8px;
border-radius: 4px; box-sizing: border-box;
border: 1px solid var(--line_regular, #ccc); background-color: var(--bg1, #f4f4f4);
color: var(--text1, #212121); font-size: 13px;
}
html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} input[type="text"], html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} input[type="number"], html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} select {
background-color: var(--bg2, #333); border-color: var(--line_regular, #555);
}
#${SCRIPT_ELEMENT_IDS.settingsPanel} .bili-plus-settings-buttons { display: flex; justify-content: space-between; margin-top: 25px; align-items: center; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} button {
padding: 8px 15px; border: none; border-radius: 4px;
cursor: pointer; font-size: 14px; font-weight: 500;
transition: background-color 0.2s, box-shadow 0.2s;
}
#${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-reset-settings {
background-color: var(--bg2_float_hover, #e7e7e7); color: var(--text2, #61666d);
}
#${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-reset-settings:hover { background-color: var(--bg2_float_active, #ddd); }
html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-reset-settings { background-color: var(--graph_bg_thin, #383838); color: var(--text1, #ccc); }
html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-reset-settings:hover { background-color: var(--graph_bg, #4a4a4a); }
#${SCRIPT_ELEMENT_IDS.settingsPanel} .bili-plus-settings-buttons-right-group button { margin-left: 10px; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-save-settings { background-color: ${config.styles.bilibiliBlue}; color: white; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-save-settings:hover { background-color: #00b5e5; }
#${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-close-settings { background-color: var(--bg2_float_hover, #e7e7e7); color: var(--text2, #61666d); }
#${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-close-settings:hover { background-color: var(--bg2_float_active, #ddd); }
html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-close-settings { background-color: var(--graph_bg_thin, #383838); color: var(--text1, #ccc); }
html.dark #${SCRIPT_ELEMENT_IDS.settingsPanel} #bili-plus-close-settings:hover { background-color: var(--graph_bg, #4a4a4a); }
.${CSS_CLASSES.commentSidebar} {
flex-direction: column; position: fixed;
left: var(--biliplus-sidebar-left, auto);
top: var(--biliplus-sidebar-top, 75px);
width: var(--biliplus-sidebar-width, 320px);
height: var(--biliplus-sidebar-height, auto);
right: var(--biliplus-browser-edge-margin) !important;
background-color: var(--bg1_float, #fff);
border-radius: var(--biliplus-border-radius);
box-shadow: 0 0 0 var(--biliplus-border-stroke-width) var(--biliplus-themed-box-shadow-border-color),
0 0 var(--biliplus-shadow-blur) var(--biliplus-shadow-spread) var(--dynamic-shadow-color);
padding: 0; box-sizing: border-box; display: none;
}
.${CSS_CLASSES.commentSidebarActive} { display: flex !important; }
#biliMainHeader .v-popover, .bili-header .v-popover { z-index: 1300 !important; }
body.${CSS_CLASSES.bodyEnhancementsActive} .left-container .ad-report,
body.${CSS_CLASSES.bodyEnhancementsActive} [class*="strip-ad"] { display: none !important; }
#${SCRIPT_ELEMENT_IDS.commentContainer}.bili-sidebar--compact .sidebar-tab-text { display: none; }
#${SCRIPT_ELEMENT_IDS.commentContainer}.bili-sidebar--compact .sidebar-tab-icon { margin-right: 0; }
#${SCRIPT_ELEMENT_IDS.commentContainer}.bili-sidebar--compact .${CSS_CLASSES.sidebarTab} { padding: 0 2px; }
body.${CSS_CLASSES.bodyEnhancementsActive} ${SELECTORS.commentBottomFixedWrapper}:not([data-bili-plus-comment-input-projected="true"]) { opacity: 0 !important; pointer-events: none !important; }
.${CSS_CLASSES.sidebarTabHeader} { display: flex; height: ${config.styles.sidebarTabHeaderHeight}; flex-shrink: 0; position: relative; border-bottom: ${config.styles.sidebarHeaderBorderWidth} solid var(--line_regular, #ddd);}
.${CSS_CLASSES.sidebarTab} { flex: 1; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 14px; color: var(--text2, #61666d); box-sizing: border-box; transition: color 0.2s, fill 0.2s; padding: 0 5px; white-space: nowrap; }
.${CSS_CLASSES.sidebarTab}:hover { color: ${config.styles.bilibiliBlue}; }
.${CSS_CLASSES.sidebarTab}.${CSS_CLASSES.sidebarTabActive} { color: ${config.styles.bilibiliBlue}; }
.${CSS_CLASSES.sidebarTabIndicator} { position: absolute; bottom: -${config.styles.sidebarHeaderBorderWidth}; height: 2px; background-color: ${config.styles.bilibiliBlue}; transition: left 0.3s ease, width 0.3s ease; z-index: 1; }
.sidebar-tab-icon { width: 16px; height: 16px; margin-right: 6px; fill: var(--text2, #61666d); transition: fill 0.2s; vertical-align: middle; }
html.dark .sidebar-tab-icon { fill: var(--text3, #9499A0); }
.${CSS_CLASSES.sidebarTab}:hover .sidebar-tab-icon, .${CSS_CLASSES.sidebarTab}.${CSS_CLASSES.sidebarTabActive} .sidebar-tab-icon { fill: ${config.styles.bilibiliBlue}; }
#${SCRIPT_ELEMENT_IDS.allTabsContentArea} { flex-grow: 1; overflow: hidden; position: relative; margin: 6px 0; padding: 0; box-sizing: border-box; display: flex; flex-direction: column; }
.${CSS_CLASSES.sidebarTabContentWrapper} { box-sizing: border-box; display: none; flex-direction: column; width: 100%; height: 100%; padding: ${config.styles.sidebarContentPadding}; overflow-y: auto; scrollbar-width: thin; overscroll-behavior: contain; }
.${CSS_CLASSES.sidebarTabContentWrapper}::-webkit-scrollbar,
.${CSS_CLASSES.infoTabMiddle}::-webkit-scrollbar,
#${SCRIPT_ELEMENT_IDS.settingsPanel}::-webkit-scrollbar { width: 6px; height: 6px; }
.${CSS_CLASSES.sidebarTabContentWrapper}::-webkit-scrollbar-thumb,
.${CSS_CLASSES.infoTabMiddle}::-webkit-scrollbar-thumb,
#${SCRIPT_ELEMENT_IDS.settingsPanel}::-webkit-scrollbar-thumb { background-color: rgba(128, 128, 128, 0.4); border-radius: 3px; }
.${CSS_CLASSES.sidebarTabContentWrapper}::-webkit-scrollbar-track,
.${CSS_CLASSES.infoTabMiddle}::-webkit-scrollbar-track,
#${SCRIPT_ELEMENT_IDS.settingsPanel}::-webkit-scrollbar-track { background-color: transparent; }
#bili-custom-sidebar-wrapper-info { overflow-y: hidden !important; padding-right: 0 !important; }
#bili-custom-sidebar-wrapper-comments { padding-right: 0 !important; }
body.${CSS_CLASSES.bodyEnhancementsActive} #bili-custom-sidebar-wrapper-danmaku [class*="DanmukuBox"],
body.${CSS_CLASSES.bodyEnhancementsActive} #bili-custom-sidebar-wrapper-danmaku .bpx-docker-minor {
background-color: transparent !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaInfoWrap"] {
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box;
border-top: none !important;
padding: 0 !important;
gap: 10px;
flex-wrap: nowrap;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaCover"] {
flex: 0 0 33% !important;
width: 33% !important;
max-width: 33% !important;
min-width: 0 !important;
height: auto !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaToolbar"] {
position: static !important;
width: auto !important;
margin-top: 8px !important;
display: flex !important;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaRight"] {
flex: 1 1 0% !important;
min-width: 0 !important;
width: auto !important;
padding-left: 0 !important;
box-sizing: border-box;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_media_desc_section"],
#bili-custom-sidebar-wrapper-info [class*="mediainfo_descCompress"] {
max-height: none !important;
overflow: visible !important;
}
#bili-custom-sidebar-wrapper-info .bili-info-tab-middle-content [class*="mediainfo_media_desc_section"] {
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box;
margin: 0 !important;
padding: 0 !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaTitle"] {
padding-right: 0 !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_bottomBar"] {
flex-wrap: wrap !important;
gap: 6px 8px !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaRating"],
#bili-custom-sidebar-wrapper-info [class*="upinfo_upInfoCard"],
#bili-custom-sidebar-wrapper-info [class*="score_score"] {
flex-shrink: 0 !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_mediaRating"] {
margin-right: 0 !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_content_placeholder"] { display: none !important; }
#bili-custom-sidebar-wrapper-info [class*="mediainfo_ellipsis"] { display: none !important; }
#bili-custom-sidebar-wrapper-info [class*="mediainfo_display_area"] {
max-height: none !important;
overflow: visible !important;
}
#bili-custom-sidebar-wrapper-info [class*="mediainfo_bottomBar"] > div:not([class]) {
display: none !important;
}
#bili-custom-sidebar-wrapper-info .${CSS_CLASSES.infoTabTop},
#bili-custom-sidebar-wrapper-info .${CSS_CLASSES.infoTabBottom} { padding-right: 16px; }
#bili-custom-sidebar-wrapper-info .${CSS_CLASSES.infoTabMiddle} { padding-right: 16px; }
.${CSS_CLASSES.sidebarTabContentWrapper}.${CSS_CLASSES.sidebarTabContentWrapperActive} { display: flex !important; }
.${CSS_CLASSES.sidebarTabContent} { display: none; width: 100%; flex-grow: 1; box-sizing: border-box; }
.${CSS_CLASSES.sidebarTabContent}.${CSS_CLASSES.sidebarTabContentActive} { display: block !important; }
#bili-custom-sidebar-content-info.${CSS_CLASSES.sidebarTabContent}.${CSS_CLASSES.sidebarTabContentActive} { display: flex !important; flex-direction: column; height: 100%; }
.${CSS_CLASSES.infoTabTop} { flex-shrink: 0; padding-bottom: 10px; }
.${CSS_CLASSES.infoTabMiddle} { flex-grow: 1; overflow-y: auto; margin-top: 20px; min-height: 30px; width: 100%; box-sizing: border-box; }
.${CSS_CLASSES.infoTabBottom} { flex-shrink: 0; padding-top: 8px; margin-top: auto; }
.${CSS_CLASSES.infoTabTop} > *, .${CSS_CLASSES.infoTabBottom} > * { margin-bottom: 8px; }
.${CSS_CLASSES.infoTabTop} > :last-child, .${CSS_CLASSES.infoTabBottom} > :last-child { margin-bottom: 0; }
#bili-custom-sidebar-content-info .${CSS_CLASSES.infoTabBottom} ${SELECTORS.videoTagContainer} { margin: 0 !important; border-bottom: none !important; }
#bili-custom-sidebar-content-info .${CSS_CLASSES.infoTabTop} ${SELECTORS.upPanelContainer} { margin-top: 0 !important; border-top: none !important; border-bottom: 1px solid var(--line_regular, #ddd) !important; }
#bili-custom-sidebar-content-info ${SELECTORS.videoInfoMeta} { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
#bili-custom-sidebar-content-info ${SELECTORS.videoInfoMeta} > * { display: inline-flex; align-items: center; }
#bili-custom-sidebar-content-info ${SELECTORS.videoInfoMeta} ${SELECTORS.videoInfoDetailList} { display: flex !important; flex-wrap: wrap !important; gap: 8px !important; width: 100% !important; max-height: none !important; overflow: visible !important; }
#bili-custom-sidebar-content-info ${SELECTORS.videoInfoMeta} ${SELECTORS.videoInfoDetailList} > .item { white-space: normal !important; overflow: visible !important; word-break: break-word; max-width: 100%; }
#bili-custom-sidebar-content-info ${SELECTORS.showMoreBtnDetail} { display: none !important; }
#bili-custom-sidebar-content-info ${SELECTORS.basicDescInfo} { height: auto !important; max-height: none !important; }
#bili-custom-sidebar-content-info ${SELECTORS.videoDescContainer} .toggle-btn { display: none !important; }
#bili-custom-sidebar-content-comments > ${SELECTORS.commentApp} { width: 100%; height: 100%; box-sizing: border-box; display: flex; flex-direction: column; }
#bili-custom-sidebar-content-videos > .rcmd-tab { width: 100%; box-sizing: border-box; margin-bottom: 0 !important; }
#bili-custom-sidebar-content-videos > .action-list-container,
#bili-custom-sidebar-content-videos > .recommend-list-v1,
#bili-custom-sidebar-content-videos > .recommend-list-container { width: 100%; box-sizing: border-box; margin-bottom: 10px; }
#bili-custom-sidebar-content-danmaku > ${SELECTORS.danmakuModules} { width: 100%; height: 100%; margin: 0 !important; box-sizing: border-box; overflow: hidden; }
#bili-custom-sidebar-content-danmaku > ${SELECTORS.danmakuModules} > .video-pod-above-modules__inner { width: 100%; height: 100%; margin: 0 !important; box-sizing: border-box; overflow: hidden; }
#bili-custom-sidebar-content-danmaku > ${SELECTORS.danmakuModules} > .video-pod-above-modules__inner > ${SELECTORS.danmakuBox} { width: 100%; height: 100%; margin-top: 0 !important; box-sizing: border-box; overflow: hidden; }
#bili-custom-sidebar-content-danmaku > ${SELECTORS.danmakuBox} { width: 100%; height: 100%; margin-top: 0 !important; box-sizing: border-box; overflow: hidden; }
body.${CSS_CLASSES.bodyEnhancementsActive} ${SELECTORS.viewboxReport} { height: 0px !important; padding-top: 0px !important; padding-bottom: 0px !important; margin-top: 0px !important; margin-bottom: 0px !important; border: none !important; overflow: hidden !important; opacity: 0 !important; transition: height 0.25s ease-out, padding-top 0.25s ease-out, opacity 0.25s ease-out; }
html.${CSS_CLASSES.bodyEnhancementsActive},
html.${CSS_CLASSES.bodyEnhancementsActive} body { overflow: hidden !important; }
body.${CSS_CLASSES.miniPlayerActive} #${SCRIPT_ELEMENT_IDS.commentContainer},
body.${CSS_CLASSES.miniPlayerActive} #${SCRIPT_ELEMENT_IDS.bottomDrawerWrapper} { display: none !important; }
body.${CSS_CLASSES.bodyEnhancementsActive}:not(.${CSS_CLASSES.miniPlayerActive}) ${SELECTORS.fixedSidenavRail} { display: none !important; }
body.bili-plus-hide-native-noncomment .left-container .video-info-container,
body.bili-plus-hide-native-noncomment .left-container .video-desc-container,
body.bili-plus-hide-native-noncomment .left-container .video-tag-container,
body.bili-plus-hide-native-noncomment .left-container .up-panel-container,
body.bili-plus-hide-native-noncomment .right-container .rcmd-tab,
body.bili-plus-hide-native-noncomment .right-container .action-list-container,
body.bili-plus-hide-native-noncomment .right-container .recommend-list-v1,
body.bili-plus-hide-native-noncomment .right-container .recommend-list-container,
body.bili-plus-hide-native-noncomment .right-container .video-card-list {
visibility: hidden !important;
pointer-events: none !important;
}
body.bili-plus-bangumi .main-container {
margin-left: var(--biliplus-browser-edge-margin) !important;
margin-right: auto !important;
width: var(--biliplus-bangumi-main-width, auto) !important;
max-width: none !important;
padding-left: 0 !important;
padding-right: 0 !important;
}
body.bili-plus-bangumi .plp-l { height: 0 !important; overflow: hidden !important; }
#${SCRIPT_ELEMENT_IDS.bottomDrawerWrapper} {
position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); width: 45%;
z-index: 1000; display: none; flex-direction: column;
background-color: var(--bg1_float, #fff);
border-top-left-radius: var(--biliplus-border-radius); border-top-right-radius: var(--biliplus-border-radius);
overflow: hidden;
box-shadow: 0 0 0 var(--biliplus-border-stroke-width) var(--biliplus-themed-box-shadow-border-color),
0 0 var(--biliplus-shadow-blur) var(--biliplus-shadow-spread) var(--dynamic-shadow-color);
}
#${SCRIPT_ELEMENT_IDS.bottomDrawerButton} { height: ${config.styles.bottomDrawerHandleHeight}; width: 100%; display: flex; justify-content: center; align-items: center; cursor: default; overflow: hidden; background-color: transparent; transition: height 0.25s ease-out; }
#${SCRIPT_ELEMENT_IDS.bottomDrawerButton}::after { content: ''; width: 20%; height: 2px; background-color: var(--brand_blue, ${config.styles.bilibiliBlue}); border-radius: 1px; display: block; }
#${SCRIPT_ELEMENT_IDS.bottomDrawerContent}.${CSS_CLASSES.drawerContentExpanded} ~ #${SCRIPT_ELEMENT_IDS.bottomDrawerButton} { height: 0; padding: 0; margin: 0; }
#${SCRIPT_ELEMENT_IDS.bottomDrawerContent}.${CSS_CLASSES.drawerContentExpanded} ~ #${SCRIPT_ELEMENT_IDS.bottomDrawerButton}::after { display: none; }
#${SCRIPT_ELEMENT_IDS.bottomDrawerContent} {
background-color: var(--bg1_float, #fff); max-height: 0; overflow: hidden;
transition: max-height 0.25s ease-out; padding: 0 15px; margin: 0; box-sizing: border-box; width: 100%;
}
#${SCRIPT_ELEMENT_IDS.bottomDrawerContent}.${CSS_CLASSES.drawerContentExpanded} { padding-bottom: 0; }
#${SCRIPT_ELEMENT_IDS.bottomDrawerContent} > ${SELECTORS.videoToolbarContainer},
#${SCRIPT_ELEMENT_IDS.bottomDrawerContent} > ${SELECTORS.bangumiVideoToolbarRoot} { width: 100%; box-sizing: border-box; }
`;
}
function injectBaseStyles() {
const styleId = 'bili-custom-styles-base';
const css = generateBaseCssString();
const existing = document.getElementById(styleId);
if (existing) {
if (existing.textContent === css) return;
existing.textContent = css;
log("Base styles refreshed: existing style node had different content.");
return;
}
const styleElement = document.createElement('style');
styleElement.id = styleId;
styleElement.textContent = css;
document.head.appendChild(styleElement);
log("Base styles injected.");
}
// --- Settings Panel ---
function createSettingsPanel() {
if (document.getElementById(SCRIPT_ELEMENT_IDS.settingsPanel)) return;
const panel = document.createElement('div');
panel.id = SCRIPT_ELEMENT_IDS.settingsPanel;
const fragment = document.createDocumentFragment();
panel.innerHTML = `
B站宽屏+ 设置
功能设置
侧栏宽度
`;
fragment.appendChild(panel);
document.body.appendChild(fragment);
elements.settingsPanel = panel;
panel.querySelector('#bili-plus-save-settings').addEventListener('click', saveAndApplySettings);
panel.querySelector('#bili-plus-close-settings').addEventListener('click', toggleSettingsPanel);
panel.querySelector('#bili-plus-reset-settings').addEventListener('click', resetSettingsToDefault);
log("Settings panel created.");
}
function populateSettingsPanel() {
if (!elements.settingsPanel) return;
log("Populating settings panel with current values.");
elements.settingsPanel.querySelectorAll('input[data-key], select[data-key]').forEach(input => {
const key = input.dataset.key;
input.value = GM_getValue(key, input.dataset.default);
});
}
function saveAndApplySettings() {
if (!elements.settingsPanel) return;
log("Saving settings from panel...");
const previousSettings = {};
Object.keys(config.settingsKeys).forEach(key => {
previousSettings[config.settingsKeys[key]] = GM_getValue(config.settingsKeys[key], config.defaultSettings[key]);
});
const newSettings = {};
const validationErrors = [];
elements.settingsPanel.querySelectorAll('input[data-key], select[data-key]').forEach(input => {
const key = input.dataset.key;
const value = input.value;
try {
if (key === config.settingsKeys.autoWideDelay) {
const parsed = validateNonNegativeInt(value, parseInt(input.dataset.default, 10));
newSettings[key] = Math.min(5000, Math.max(0, parsed));
} else if (key === config.settingsKeys.playerCenterOffset ||
key === config.settingsKeys.minSidebarWidth ||
key === config.settingsKeys.maxSidebarWidth) {
newSettings[key] = Math.max(0, validateNonNegativeInt(value, parseInt(input.dataset.default, 10)));
} else if (key !== config.settingsKeys.defaultTab) {
const validated = validateCssLength(value, null);
if (!validated) {
newSettings[key] = validateCssLength(value, input.dataset.default);
} else {
if (key === config.settingsKeys.playerSidebarGap || key === config.settingsKeys.browserEdgeMargin) {
const num = parseFloat(validated);
if (Number.isFinite(num) && num < 0) {
throw new Error('不允许负数');
}
}
newSettings[key] = validated;
}
} else {
if (!VALID_SIDEBAR_TAB_IDS.includes(value)) {
throw new Error(`无效的标签页`);
}
newSettings[key] = value;
}
} catch (e) {
validationErrors.push(`字段 "${input.previousElementSibling.textContent}" 的值 "${value}" 无效: ${e.message}`);
}
});
const minW = newSettings[config.settingsKeys.minSidebarWidth];
const maxW = newSettings[config.settingsKeys.maxSidebarWidth];
if (minW !== undefined && maxW !== undefined && maxW > 0 && minW > maxW) {
validationErrors.push(`侧栏最小宽度 (${minW}px) 不能大于最大宽度 (${maxW}px)`);
}
if (validationErrors.length > 0) {
alert(`设置保存失败,存在无效输入:\n- ${validationErrors.join('\n- ')}\n\n请修正后重试。`);
return;
}
try {
for (const key in newSettings) {
GM_setValue(key, newSettings[key]);
}
} catch (e) {
error("saveAndApplySettings: Failed to save settings to GM_storage.", e);
try {
for (const key in previousSettings) {
GM_setValue(key, previousSettings[key]);
}
alert("错误:无法保存设置!已自动恢复到之前的设置。请检查浏览器控制台以获取详细信息。");
} catch (rollbackError) {
error("saveAndApplySettings: CRITICAL - Failed to rollback settings after save failure.", rollbackError);
alert("严重错误:无法保存设置且恢复失败!脚本可能处于不稳定状态,请刷新页面。");
}
return;
}
log("Settings saved successfully. Applying changes...");
loadAllSettings();
syncThemeDependentStyles();
updateMenuCommands();
if (document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) {
updateLayoutAndStyles();
}
}
function resetSettingsToDefault() {
if (!elements.settingsPanel) return;
log("Resetting settings to default...");
if (confirm("确定要将所有设置恢复为默认值吗?")) {
elements.settingsPanel.querySelectorAll('input[data-key], select[data-key]').forEach(input => {
const key = input.dataset.key;
const defaultValue = input.dataset.default;
GM_setValue(key, defaultValue);
input.value = defaultValue;
});
saveAndApplySettings();
}
}
function toggleSettingsPanel() {
if (!elements.settingsPanel) createSettingsPanel();
if (elements.settingsPanel) {
const isVisible = elements.settingsPanel.style.display === 'block';
if (!isVisible) populateSettingsPanel();
elements.settingsPanel.style.display = isVisible ? 'none' : 'block';
log(`Settings panel ${isVisible ? 'hidden' : 'shown'}.`);
}
}
function scrollToPosition(topPosition, options = {}) {
const { force = false, onComplete = null } = options;
if (pendingScrollOperation) {
cancelAnimationFrame(pendingScrollOperation.rafId);
if (pendingScrollOperation.timerId) clearTimeout(pendingScrollOperation.timerId);
pendingScrollOperation = null;
}
if (isScrolling && !force) return;
const now = Date.now();
if (!force && now - lastScrollTime < 100 && Math.abs(window.scrollY - topPosition) < 50) return;
log(`scrollToPosition: Scrolling to ${topPosition}.`);
lastScrollTime = now;
isScrolling = true;
const op = { rafId: null, timerId: null };
op.rafId = requestAnimationFrame(() => {
window.scrollTo({ top: topPosition, behavior: 'smooth' });
op.timerId = setTimeout(() => {
isScrolling = false;
if (onComplete && typeof onComplete === 'function') {
onComplete();
}
if (pendingScrollOperation === op) pendingScrollOperation = null;
}, config.animationDurations.scroll);
});
pendingScrollOperation = op;
}
function scrollToPlayer() {
log("scrollToPlayer: Attempting to scroll player into view.");
if (!elements.player) { warn("scrollToPlayer: Player element not cached."); return; }
requestAnimationFrame(() => {
const playerRect = elements.player.getBoundingClientRect();
if (playerRect.height > 0 && playerRect.width > 0) {
const desiredScrollTop = playerRect.top + window.scrollY - (currentSettings.playerCenterOffset ?? config.playerCenterOffset);
if (Math.abs(window.scrollY - desiredScrollTop) > 5) scrollToPosition(desiredScrollTop, { onComplete: () => updateCommentSidebar(0) });
} else warn("scrollToPlayer: Player height or width is 0.");
});
}
function scrollToTop() {
log("scrollToTop: Attempting to scroll to page top.");
if (window.scrollY > 0) scrollToPosition(0);
}
// --- Element Caching ---
function cacheSingleElement(key, selector, isReCache, specialCache = null, queryFn = document.querySelector.bind(document)) {
const holderKey = `original${key.charAt(0).toUpperCase() + key.slice(1)}Holder`;
const currentElementRef = elements[key];
const newElementInstance = queryFn(selector);
if (newElementInstance || !currentElementRef) {
elements[key] = newElementInstance;
}
if (elements[key]) {
const holder = elements[holderKey];
try {
if (specialCache) specialCache(elements[key], holder);
} catch (e) {
error(`cacheSingleElement: Error during special cache for "${key}":`, e);
}
} else {
const missingMsg = `cacheSingleElement (${isReCache ? 're-cache' : 'initial cache'}): Element not found ${key} ("${selector}").`;
if (missingElementWarned.has(key)) log(missingMsg);
else { missingElementWarned.add(key); warn(missingMsg); }
}
}
function cacheInfoTabElements(isReCache) {
cacheSingleElement('videoTitleElement', SELECTORS.videoTitle, isReCache, (el, holder) => {
if(holder) holder.originalFontSize = window.getComputedStyle(el).fontSize;
});
cacheSingleElement('videoInfoMetaElement', SELECTORS.videoInfoMeta, isReCache);
cacheSingleElement('videoDescContainerElement', SELECTORS.videoDescContainer, isReCache);
cacheSingleElement('videoTagContainerElement', SELECTORS.videoTagContainer, isReCache);
cacheSingleElement('upPanelContainerElement', SELECTORS.upPanelContainer, isReCache);
cacheSingleElement('videoInfoContainerWinElement', SELECTORS.videoInfoContainerWin, isReCache);
}
function cacheOtherTabElements(isReCache) {
cacheSingleElement('commentApp', SELECTORS.commentApp, isReCache, null, queryPageElement);
cacheSingleElement('rcmdTabElement', SELECTORS.rcmdTab, isReCache);
cacheSingleElement('actionListElement', SELECTORS.actionList, isReCache);
cacheSingleElement('recommendListV1Element', SELECTORS.recommendListV1, isReCache);
cacheSingleElement('recommendListContainerElement', SELECTORS.recommendListContainer, isReCache);
cacheSingleElement('episodeListElement', SELECTORS.episodeList, isReCache);
if (isBangumiPlayPage()) cacheSingleElement('bangumiMediaInfoElement', SELECTORS.bangumiMediaInfo, isReCache);
cacheSingleElement('recommendListBangumiElement', SELECTORS.recommendListBangumi, isReCache);
cacheSingleElement('danmakuModulesElement', SELECTORS.danmakuModules, isReCache);
}
function cacheLayoutElements(isReCache) {
cacheSingleElement('videoToolbarContainerElement', getNativeVideoToolbarSelector(), isReCache);
cacheSingleElement('viewboxReportElement', SELECTORS.viewboxReport, isReCache);
cacheSingleElement('mirrorVdcon', SELECTORS.mirrorVdcon, isReCache);
}
function cacheContentElements(isReCache = false) {
log(`cacheContentElements: Caching content elements. isReCache = ${isReCache}`);
if (!isReCache) {
elements.originalMirrorVdconHeight = '';
elements.originalMirrorVdconPaddingLeft = '';
}
cacheInfoTabElements(isReCache);
cacheOtherTabElements(isReCache);
cacheLayoutElements(isReCache);
log("cacheContentElements: Content element caching processed.");
}
async function cacheCorePlayerElements() {
log("cacheCorePlayerElements: Starting to cache core player elements.");
elements.player = await waitForSpecificElement(SELECTORS.player, { required: true });
if (!elements.player) return false;
elements.playerContainer = document.querySelector(SELECTORS.playerContainer)
|| await waitForSpecificElement(SELECTORS.playerContainer, {
attempts: config.attempts.contentElementWait,
interval: config.intervals.contentElementWait
})
|| document.querySelector(SELECTORS.playerAlternativeContainer)
|| elements.player;
if (elements.playerContainer === elements.player) {
warn("cacheCorePlayerElements: Using player element as its own container (fallback).");
}
elements.playerWrap = document.getElementById(SELECTORS.playerWrap.substring(1));
if (!elements.playerWrap) {
warn("cacheCorePlayerElements: playerWrap not found. Some layout features may not work correctly.");
}
elements.wideBtn = await waitForSpecificElement(SELECTORS.wideBtn, {
attempts: config.attempts.wideBtnWait,
interval: config.intervals.wideBtnWait,
required: false
});
if (!elements.wideBtn) {
warn(`cacheCorePlayerElements: Widescreen button not ready after ${config.attempts.wideBtnWait} attempts, retrying with extended budget.`);
elements.wideBtn = await waitForSpecificElement(SELECTORS.wideBtn, {
attempts: config.attempts.wideBtnExtendedWait,
interval: config.intervals.wideBtnWait,
required: false
});
}
if (!elements.wideBtn) {
warn(`cacheCorePlayerElements: Widescreen button ("${SELECTORS.wideBtn}") still missing. Continuing in degraded mode; will retry in background.`);
scheduleWideButtonRecovery();
}
log("Core player elements cached successfully.");
return true;
}
function scheduleWideButtonRecovery() {
if (elements.wideBtn && document.body.contains(elements.wideBtn)) return;
waitForElementObserved(SELECTORS.wideBtn, config.attempts.wideBtnRecoveryMaxRetries * 500).then(btn => {
if (!btn) {
warn('scheduleWideButtonRecovery: giving up on widescreen button recovery.');
return;
}
if (elements.wideBtn && document.body.contains(elements.wideBtn)) return;
elements.wideBtn = btn;
log('scheduleWideButtonRecovery: widescreen button recovered.');
if (elements.playerContainer
&& elements.playerContainer.getAttribute('data-screen') === PLAYER_STATES.NORMAL) {
conditionallyEnterWideMode().catch(e => error('scheduleWideButtonRecovery: conditionallyEnterWideMode failed.', e));
} else if (elements.playerContainer) {
handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'))
.catch(e => error('scheduleWideButtonRecovery: handleDataScreenChange failed.', e));
}
});
}
async function ensureAllElementsCached() {
log("ensureAllElementsCached: Verifying all necessary elements.");
if (elements.player && document.body.contains(elements.player) &&
elements.playerContainer && document.body.contains(elements.playerContainer)) {
if (!elements.wideBtn || !document.body.contains(elements.wideBtn)) {
elements.wideBtn = document.querySelector(SELECTORS.wideBtn);
if (!elements.wideBtn) scheduleWideButtonRecovery();
}
cacheContentElements();
log("ensureAllElementsCached: core elements still valid, reusing cache.");
return true;
}
if (!await cacheCorePlayerElements()) {
warn("ensureAllElementsCached: Core player element caching failed. Script might not function fully.");
return false;
}
cacheContentElements();
log("ensureAllElementsCached: Element verification attempt complete.");
return true;
}
// --- Sidebar and UI Creation ---
function getOrCreateCommentContainer() {
if (elements.commentContainer && document.body.contains(elements.commentContainer)) return elements.commentContainer;
let container = document.getElementById(SCRIPT_ELEMENT_IDS.commentContainer);
if (!container) {
container = document.createElement('div');
container.id = SCRIPT_ELEMENT_IDS.commentContainer;
container.classList.add(CSS_CLASSES.commentSidebar);
document.body.appendChild(container);
log("Sidebar container created.");
}
elements.commentContainer = container;
if (!elements.sidebarTabHeader || !elements.allTabsContentArea) createSidebarTabsAndContent();
return container;
}
function createSidebarTabsAndContent() {
if (!elements.commentContainer) { warn("createSidebarTabsAndContent: Sidebar container does not exist."); return; }
if (elements.sidebarTabHeader && elements.allTabsContentArea && elements.commentContainer.contains(elements.sidebarTabHeader)) {
log("createSidebarTabsAndContent: Tab structure appears to exist already."); return;
}
const fragment = document.createDocumentFragment();
elements.commentContainer.innerHTML = '';
elements.sidebarTabHeader = document.createElement('div');
elements.sidebarTabHeader.className = CSS_CLASSES.sidebarTabHeader;
const indicator = document.createElement('div');
indicator.className = CSS_CLASSES.sidebarTabIndicator;
elements.sidebarTabIndicator = indicator;
elements.sidebarTabHeader.appendChild(indicator);
elements.allTabsContentArea = document.createElement('div');
elements.allTabsContentArea.id = SCRIPT_ELEMENT_IDS.allTabsContentArea;
SIDEBAR_TABS_CONFIG.forEach(tabInfo => {
const tabElement = document.createElement('div');
tabElement.className = CSS_CLASSES.sidebarTab;
tabElement.dataset.tabId = tabInfo.id;
tabElement.innerHTML = `${tabInfo.svg}`;
elements[tabInfo.id + 'Tab'] = tabElement;
elements.sidebarTabHeader.appendChild(tabElement);
const tabContentWrapper = document.createElement('div');
tabContentWrapper.className = CSS_CLASSES.sidebarTabContentWrapper;
tabContentWrapper.id = `bili-custom-sidebar-wrapper-${tabInfo.id}`;
elements[tabInfo.wrapperId] = tabContentWrapper;
const contentPane = document.createElement('div');
contentPane.id = `bili-custom-sidebar-content-${tabInfo.id}`;
contentPane.className = CSS_CLASSES.sidebarTabContent;
elements[tabInfo.paneId] = contentPane;
tabContentWrapper.appendChild(contentPane);
elements.allTabsContentArea.appendChild(tabContentWrapper);
});
fragment.appendChild(elements.sidebarTabHeader);
fragment.appendChild(elements.allTabsContentArea);
elements.commentContainer.appendChild(fragment);
elements.sidebarTabHeader.addEventListener('click', (event) => {
const tabEl = event.target.closest?.(`.${CSS_CLASSES.sidebarTab}`);
if (!tabEl || !elements.sidebarTabHeader?.contains(tabEl)) return;
const tabId = tabEl.dataset.tabId;
if (tabId) setActiveSidebarTab(tabId);
}, true);
updateSidebarTabIndicator(currentActiveSidebarTabId);
log("Sidebar tab structure created/recreated using DocumentFragment.");
}
function getOrCreateBottomDrawer() {
if (elements.bottomDrawerWrapper && document.body.contains(elements.bottomDrawerWrapper)) return true;
elements.bottomDrawerWrapper = document.createElement('div');
elements.bottomDrawerWrapper.id = SCRIPT_ELEMENT_IDS.bottomDrawerWrapper;
elements.bottomDrawerButton = document.createElement('div');
elements.bottomDrawerButton.id = SCRIPT_ELEMENT_IDS.bottomDrawerButton;
elements.bottomDrawerContent = document.createElement('div');
elements.bottomDrawerContent.id = SCRIPT_ELEMENT_IDS.bottomDrawerContent;
elements.bottomDrawerWrapper.appendChild(elements.bottomDrawerContent);
elements.bottomDrawerWrapper.appendChild(elements.bottomDrawerButton);
document.body.appendChild(elements.bottomDrawerWrapper);
log("Bottom drawer created.");
elements.bottomDrawerWrapper.addEventListener('mouseenter', () => {
if (!elements.bottomDrawerContent) return;
elements.bottomDrawerContent.classList.add(CSS_CLASSES.drawerContentExpanded);
const arcToolbarReport = document.querySelector(SELECTORS.arcToolbarReport);
let targetHeight = 150;
if (arcToolbarReport && arcToolbarReport.offsetParent !== null) {
targetHeight = arcToolbarReport.offsetHeight;
} else if (elements.videoToolbarContainerElement) {
targetHeight = elements.videoToolbarContainerElement.offsetHeight;
} else if (arcToolbarReport) {
warn(`Bottom drawer: ${SELECTORS.arcToolbarReport} is not visible.`);
} else {
warn(`Bottom drawer: ${SELECTORS.arcToolbarReport} not found.`);
}
elements.bottomDrawerContent.style.maxHeight = targetHeight + 'px';
});
elements.bottomDrawerWrapper.addEventListener('mouseleave', () => {
if (!elements.bottomDrawerContent) return;
elements.bottomDrawerContent.classList.remove(CSS_CLASSES.drawerContentExpanded);
elements.bottomDrawerContent.style.maxHeight = '0';
});
return true;
}
// --- Sidebar Tab Management ---
function updateSidebarTabIndicator(tabId = currentActiveSidebarTabId, options = {}) {
const { animate = false } = options;
const targetTabId = VALID_SIDEBAR_TAB_IDS.includes(tabId) ? tabId : currentSettings.defaultTab;
if (!elements.sidebarTabIndicator) return;
const tabIndex = SIDEBAR_TABS_CONFIG.findIndex(tab => tab.id === targetTabId);
if (tabIndex < 0) {
elements.sidebarTabIndicator.style.width = '0px';
return;
}
const transitionValue = 'left 0.3s ease, width 0.3s ease';
const widthPercent = 100 / SIDEBAR_TABS_CONFIG.length;
elements.sidebarTabIndicator.style.transition = animate ? transitionValue : 'none';
elements.sidebarTabIndicator.style.left = `${tabIndex * widthPercent}%`;
elements.sidebarTabIndicator.style.width = `${widthPercent}%`;
if (!animate) {
requestAnimationFrame(() => {
if (elements.sidebarTabIndicator) elements.sidebarTabIndicator.style.transition = transitionValue;
});
}
}
function ensureSidebarShellVisibleDuringTransition() {
if (viewportSuspendedForSize) return false;
if (!document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) return false;
const container = getOrCreateCommentContainer();
if (!container) return false;
container.classList.add(CSS_CLASSES.commentSidebarActive);
container.style.display = 'flex';
return true;
}
function loadAndApplyTabState() {
const configuredDefaultTab = VALID_SIDEBAR_TAB_IDS.includes(currentSettings.defaultTab)
? currentSettings.defaultTab
: config.defaultSettings.defaultTab;
log(`loadAndApplyTabState: using configured default tab '${configuredDefaultTab}'.`);
setActiveSidebarTab(configuredDefaultTab, false);
}
function setActiveSidebarTab(tabIdToActivate, isUserClick = true) {
log(`setActiveSidebarTab: Activating tab '${tabIdToActivate}', isUserClick: ${isUserClick}`);
let targetTabId = tabIdToActivate;
if (!VALID_SIDEBAR_TAB_IDS.includes(tabIdToActivate)) {
warn(`setActiveSidebarTab: Invalid tab ID '${tabIdToActivate}'. Defaulting to '${currentSettings.defaultTab}'.`);
targetTabId = VALID_SIDEBAR_TAB_IDS.includes(currentSettings.defaultTab)
? currentSettings.defaultTab
: config.defaultSettings.defaultTab;
}
currentActiveSidebarTabId = targetTabId;
const tabSwitchToken = bumpSeq(SEQ.sidebarContent);
SIDEBAR_TABS_CONFIG.forEach(tabInfo => {
const tabEl = elements[tabInfo.id + 'Tab'];
const wrapperEl = elements[tabInfo.wrapperId];
const isActive = (tabInfo.id === targetTabId);
if (tabEl) tabEl.classList.toggle(CSS_CLASSES.sidebarTabActive, isActive);
if (wrapperEl) {
wrapperEl.classList.toggle(CSS_CLASSES.sidebarTabContentWrapperActive, isActive);
const paneEl = wrapperEl.querySelector(`.${CSS_CLASSES.sidebarTabContent}`);
if (paneEl) paneEl.classList.toggle(CSS_CLASSES.sidebarTabContentActive, isActive);
}
});
updateSidebarTabIndicator(targetTabId, { animate: isUserClick });
ensureSidebarShellVisibleDuringTransition();
if (targetTabId === 'comments') {
bumpSeq(SEQ.commentProjection);
updateCommentProjectionVisibility();
} else {
bumpSeq(SEQ.commentProjection);
deactivateCommentProjection({ keepReference: true, restoreToPage: false });
safeSetTimeout(() => refreshSidebarTabContentFast(targetTabId, 0, tabSwitchToken), 0);
}
}
// --- Content Management for Sidebar ---
const RESTORE_ANCHOR_PROP = '__biliPlusRestoreAnchor';
function isDirectlyInsideScriptContainer(element) {
const parent = element?.parentElement;
if (!parent) return false;
return parent.classList.contains(CSS_CLASSES.sidebarTabContent)
|| parent.classList.contains(CSS_CLASSES.infoTabTop)
|| parent.classList.contains(CSS_CLASSES.infoTabMiddle)
|| parent.classList.contains(CSS_CLASSES.infoTabBottom)
|| parent.id === SCRIPT_ELEMENT_IDS.bottomDrawerContent;
}
function markRestoreAnchor(element, label = 'element') {
if (!element || element.nodeType !== 1) return false;
const existing = element[RESTORE_ANCHOR_PROP];
if (existing && existing.parentNode) return true;
if (isDirectlyInsideScriptContainer(element)) return false;
const parent = element.parentNode;
if (!parent || parent.nodeType !== 1) return false;
const anchor = document.createComment(`biliplus:${label}`);
parent.insertBefore(anchor, element);
element[RESTORE_ANCHOR_PROP] = anchor;
return true;
}
function restoreElementToAnchor(element) {
if (!element) return 'missing';
const anchor = element[RESTORE_ANCHOR_PROP];
if (!anchor) return 'missing';
element[RESTORE_ANCHOR_PROP] = null;
if (!anchor.parentNode) return 'stale';
try {
anchor.replaceWith(element);
return 'restored';
} catch (e) {
return 'stale';
}
}
function restoreMovedElementToOriginalPlace(element, elementNameForLog = 'element') {
if (!element) return false;
const result = restoreElementToAnchor(element);
if (result === 'restored') return true;
if (result === 'stale') log(`restoreMovedElementToOriginalPlace: anchor detached for ${elementNameForLog}; skip restore.`);
return false;
}
function moveBangumiDescSectionToMiddle() {
const wrap = elements.bangumiMediaInfoElement;
const middle = elements.infoTabMiddleContent;
if (!wrap || !middle) return;
const descSection = wrap.querySelector(SELECTORS.bangumiMediaDescSection);
if (!descSection) return;
markRestoreAnchor(descSection, 'bangumiMediaDescSection');
elements.bangumiMediaDescSectionElement = descSection;
middle.appendChild(descSection);
}
function manageInfoTabContent(shouldDisplayInSidebar) {
log(`manageInfoTabContent: shouldDisplayInSidebar = ${shouldDisplayInSidebar}`);
const infoPane = elements.infoContentPane;
if (!infoPane) { warn("manageInfoTabContent: Info content pane not found."); return; }
const contentElementsConfig = [
{ key: 'upPanelContainerElement', targetContainerClass: CSS_CLASSES.infoTabTop },
{
key: 'videoTitleElement', targetContainerClass: CSS_CLASSES.infoTabTop,
styleChange: (el, inSidebar) => {
if (inSidebar) {
const originalFontSize = elements.originalVideoTitleElementHolder?.originalFontSize;
el.style.fontSize = (originalFontSize && originalFontSize !== '0px' && !originalFontSize.includes('auto')) ? originalFontSize : config.styles.defaultVideoTitleFontSize;
el.textContent = el.textContent.trim();
} else el.style.fontSize = '';
}
},
{ key: 'videoInfoMetaElement', targetContainerClass: CSS_CLASSES.infoTabTop },
{ key: 'videoInfoContainerWinElement', targetContainerClass: CSS_CLASSES.infoTabTop },
{
key: 'videoDescContainerElement', targetContainerClass: CSS_CLASSES.infoTabMiddle,
styleChange: (el, inSidebar) => {
if (!inSidebar) el.style.margin = '';
const basicDesc = el.querySelector(SELECTORS.basicDescInfo);
if (basicDesc) basicDesc.style.height = inSidebar ? 'auto' : '';
const descBtn = el.querySelector('.toggle-btn');
if (descBtn) descBtn.style.display = inSidebar ? 'none' : '';
}
},
{ key: 'videoTagContainerElement', targetContainerClass: CSS_CLASSES.infoTabBottom }
];
if (isBangumiPlayPage()) {
contentElementsConfig.unshift({
key: 'bangumiMediaInfoElement',
targetContainerClass: CSS_CLASSES.infoTabTop
});
}
if (shouldDisplayInSidebar) {
infoPane.innerHTML = '';
const fragment = document.createDocumentFragment();
elements.infoTabTopContent = document.createElement('div');
elements.infoTabTopContent.className = CSS_CLASSES.infoTabTop;
elements.infoTabMiddleContent = document.createElement('div');
elements.infoTabMiddleContent.className = CSS_CLASSES.infoTabMiddle;
elements.infoTabBottomContent = document.createElement('div');
elements.infoTabBottomContent.className = CSS_CLASSES.infoTabBottom;
contentElementsConfig.forEach(configItem => {
const el = elements[configItem.key];
if (el) {
let targetParent;
if (configItem.targetContainerClass === CSS_CLASSES.infoTabTop) targetParent = elements.infoTabTopContent;
else if (configItem.targetContainerClass === CSS_CLASSES.infoTabMiddle) targetParent = elements.infoTabMiddleContent;
else targetParent = elements.infoTabBottomContent;
markRestoreAnchor(el, configItem.key);
targetParent.appendChild(el);
if (configItem.styleChange) configItem.styleChange(el, true);
}
});
fragment.appendChild(elements.infoTabTopContent);
fragment.appendChild(elements.infoTabMiddleContent);
fragment.appendChild(elements.infoTabBottomContent);
infoPane.appendChild(fragment);
if (isBangumiPlayPage()) moveBangumiDescSectionToMiddle();
} else {
restoreMovedElementsForSidebarTab('info');
contentElementsConfig.forEach(configItem => {
const el = elements[configItem.key];
if (el && configItem.styleChange) configItem.styleChange(el, false);
});
const stillContainsMovedInfo = contentElementsConfig.some(configItem => {
const el = elements[configItem.key];
return !!(el && infoPane.contains(el));
}) || !!(elements.bangumiMediaDescSectionElement && infoPane.contains(elements.bangumiMediaDescSectionElement));
if (!stillContainsMovedInfo) infoPane.innerHTML = '';
elements.infoTabTopContent = null; elements.infoTabMiddleContent = null; elements.infoTabBottomContent = null;
}
}
function manageSidebarTabContent(shouldDisplayInSidebar, { elementKey, paneKey, selector, notFoundMessage }) {
const pane = elements[paneKey];
if (!pane) { warn(`manageSidebarTabContent: Pane '${paneKey}' not found.`); return; }
if (shouldDisplayInSidebar && !isLiveSource(elements[elementKey])) {
elements[elementKey] = document.querySelector(selector);
}
const contentElement = elements[elementKey];
if (!contentElement && shouldDisplayInSidebar) {
pane.textContent = notFoundMessage;
warn(`manageSidebarTabContent: Content element '${elementKey}' ('${selector}') not found.`);
return;
}
if (!contentElement) return;
if (shouldDisplayInSidebar) {
pane.textContent = '';
markRestoreAnchor(contentElement, elementKey);
if (contentElement.parentElement !== pane) pane.appendChild(contentElement);
} else {
if (contentElement.parentElement === pane) {
restoreMovedElementToOriginalPlace(contentElement, elementKey);
}
if (!pane.contains(contentElement)) pane.textContent = '';
}
}
function manageVideoTabContent(shouldDisplayInSidebar) {
log(`manageVideoTabContent: shouldDisplayInSidebar = ${shouldDisplayInSidebar}`);
const videosPane = elements.videosContentPane;
if (!videosPane) { warn("manageVideoTabContent: Video content pane not found."); return; }
const isVideoPage = /\/video\//.test(currentUrl);
const isListPage = /\/list\//.test(currentUrl);
const moveElementConditionally = (elementKey, targetParentForSidebar, elementNameForLog) => {
const element = elements[elementKey];
if (!element) return false;
if (!isLiveSource(element) && element.parentElement !== targetParentForSidebar) {
elements[elementKey] = null;
return false;
}
if (targetParentForSidebar && isAdElement(element)) {
warn(`manageVideoTabContent: refused to move ad element into sidebar (${elementNameForLog}).`);
elements[elementKey] = null;
return false;
}
if (targetParentForSidebar) {
markRestoreAnchor(element, elementNameForLog);
targetParentForSidebar.appendChild(element);
} else if (element.parentElement === videosPane) {
if (!restoreMovedElementToOriginalPlace(element, elementNameForLog)) return false;
}
return true;
};
if (shouldDisplayInSidebar) {
videosPane.textContent = '';
const batch = document.createDocumentFragment();
let contentMoved = false;
contentMoved = moveElementConditionally('episodeListElement', batch, "episodeListElement") || contentMoved;
contentMoved = moveElementConditionally('recommendListBangumiElement', batch, "recommendListBangumiElement") || contentMoved;
if (isVideoPage) {
let rcmdTabMoved = moveElementConditionally('rcmdTabElement', batch, "rcmdTabElement");
contentMoved = rcmdTabMoved || contentMoved;
let recommendListMoved = moveElementConditionally('recommendListV1Element', batch, "recommendListV1Element");
if (recommendListMoved && elements.recommendListV1Element && rcmdTabMoved) elements.recommendListV1Element.style.marginTop = '0px';
contentMoved = recommendListMoved || contentMoved;
if (!recommendListMoved) {
recommendListMoved = moveElementConditionally('recommendListContainerElement', batch, "recommendListContainerElement");
contentMoved = recommendListMoved || contentMoved;
}
if (!contentMoved) videosPane.textContent = '当前视频页无推荐内容模块或加载失败。';
} else if (isListPage) {
contentMoved = moveElementConditionally('actionListElement', batch, "actionListElement") || contentMoved;
let recommendListMovedInList = moveElementConditionally('recommendListContainerElement', batch, "recommendListContainerElement");
if (!recommendListMovedInList) recommendListMovedInList = moveElementConditionally('recommendListV1Element', batch, "recommendListV1Element");
contentMoved = recommendListMovedInList || contentMoved;
if (!contentMoved) videosPane.textContent = '当前列表页无相关内容模块或加载失败。';
} else if (!contentMoved) videosPane.textContent = '当前页面类型无相关视频内容。';
videosPane.appendChild(batch);
} else {
restoreMovedElementsForSidebarTab('videos');
moveElementConditionally('rcmdTabElement', null, "rcmdTabElement");
moveElementConditionally('actionListElement', null, "actionListElement");
if (moveElementConditionally('recommendListV1Element', null, "recommendListV1Element") && elements.recommendListV1Element) elements.recommendListV1Element.style.marginTop = '';
moveElementConditionally('recommendListContainerElement', null, "recommendListContainerElement");
if (!videosPane.children.length) videosPane.textContent = '';
}
}
function manageDanmakuTabContent(shouldDisplayInSidebar) {
if (!shouldDisplayInSidebar) restoreMovedElementsForSidebarTab('danmaku');
manageSidebarTabContent(shouldDisplayInSidebar, {
elementKey: 'danmakuModulesElement',
paneKey: 'danmakuContentPane',
selector: SELECTORS.danmakuModules,
notFoundMessage: `弹幕模块 (${SELECTORS.danmakuModules}) 未在页面找到或加载失败。`
});
}
function manageCommentTabContent(shouldDisplayInSidebar) {
const pane = elements.commentsContentPane;
if (!pane) { warn("manageCommentTabContent: Comments pane not found."); return; }
if (shouldDisplayInSidebar) {
if (currentActiveSidebarTabId === 'comments') {
activateCommentProjection(0, seqOf(SEQ.commentProjection));
} else {
deactivateCommentProjection({ keepReference: true, restoreToPage: false });
pane.textContent = '';
}
} else {
deactivateCommentProjection({ keepReference: false });
pane.textContent = '';
}
}
function getElementTextSnapshot(el) {
return (el?.textContent || '').replace(/\s+/g, ' ').trim();
}
function rememberNonCommentSourceElementsForNavigation(previousUrl, nextUrl) {
const oldRefs = new WeakSet();
[
'videoTitleElement', 'videoInfoMetaElement', 'videoDescContainerElement', 'videoTagContainerElement', 'upPanelContainerElement', 'videoInfoContainerWinElement',
'rcmdTabElement', 'actionListElement', 'recommendListV1Element', 'recommendListContainerElement', 'episodeListElement', 'recommendListBangumiElement', 'danmakuModulesElement'
].forEach(key => {
const el = elements[key];
if (el) oldRefs.add(el);
});
nonCommentNavigationState = {
active: true,
previousUrl,
nextUrl,
previousVideoId: getVideoIdFromUrl(previousUrl),
nextVideoId: getVideoIdFromUrl(nextUrl),
oldTitleText: getElementTextSnapshot(queryNativeSourceElement(SELECTORS.videoTitle) || elements.videoTitleElement),
oldDocumentTitle: document.title || '',
startedAt: Date.now(),
oldSourceElements: oldRefs,
ready: false
};
bumpSeq(SEQ.sidebarWarmup);
bumpSeq(SEQ.sidebarContent);
log('rememberNonCommentSourceElementsForNavigation:', nonCommentNavigationState.previousVideoId, '->', nonCommentNavigationState.nextVideoId);
}
function resetMovedNonCommentElementReferences() {
const keys = [
'videoTitleElement', 'videoInfoMetaElement', 'videoDescContainerElement', 'videoTagContainerElement', 'upPanelContainerElement', 'videoInfoContainerWinElement',
'rcmdTabElement', 'actionListElement', 'recommendListV1Element', 'recommendListContainerElement', 'episodeListElement', 'recommendListBangumiElement', 'danmakuModulesElement',
'bangumiMediaInfoElement', 'bangumiMediaDescSectionElement'
];
keys.forEach(key => { elements[key] = null; });
if (elements.originalVideoTitleElementHolder) elements.originalVideoTitleElementHolder.originalFontSize = '';
}
function setNativeNonCommentSourcesHidden(hidden) {
try {
document.body.classList.toggle('bili-plus-hide-native-noncomment', !!hidden);
} catch (e) {
warn('setNativeNonCommentSourcesHidden failed:', e);
}
}
function isNonCommentDomReadyForCurrentVideo() {
if (!nonCommentNavigationState.active) return true;
const elapsed = Date.now() - nonCommentNavigationState.startedAt;
const currentVideoId = getCurrentVideoId();
const titleEl = queryNativeSourceElement(SELECTORS.videoTitle, { ignoreStale: true });
const titleText = getElementTextSnapshot(titleEl);
const titleChanged = !!titleText && titleText !== nonCommentNavigationState.oldTitleText;
const documentTitleChanged = !!document.title && document.title !== nonCommentNavigationState.oldDocumentTitle;
const urlReached = !nonCommentNavigationState.nextVideoId || currentVideoId === nonCommentNavigationState.nextVideoId;
if (urlReached && (titleChanged || documentTitleChanged || (titleText && elapsed > 900) || elapsed > 1800)) {
nonCommentNavigationState.ready = true;
nonCommentNavigationState.active = false;
setNativeNonCommentSourcesHidden(false);
log('Non-comment native DOM considered ready. elapsed=', elapsed, 'titleChanged=', titleChanged, 'documentTitleChanged=', documentTitleChanged);
return true;
}
return false;
}
function isProbablyStaleNavigationElement(el) {
if (!el || !nonCommentNavigationState.active) return false;
if (!nonCommentNavigationState.oldSourceElements?.has(el)) return false;
return !nonCommentNavigationState.ready;
}
function restoreMovedNonCommentContentToPage() {
const activeBeforeRestore = currentActiveSidebarTabId;
try {
['info', 'videos', 'danmaku'].forEach(tabId => manageSidebarTabById(tabId, false));
manageVideoToolbarForDrawer(false);
} catch (e) {
warn('restoreMovedNonCommentContentToPage: failed to restore moved content before navigation.', e);
} finally {
resetMovedNonCommentElementReferences();
currentActiveSidebarTabId = activeBeforeRestore;
if (elements.commentContainer) {
elements.commentContainer.classList.add(CSS_CLASSES.commentSidebarActive);
elements.commentContainer.style.display = 'flex';
}
updateSidebarTabIndicator(currentActiveSidebarTabId);
}
}
function getPaneForSidebarTab(tabId) {
if (tabId === 'info') return elements.infoContentPane;
if (tabId === 'videos') return elements.videosContentPane;
if (tabId === 'danmaku') return elements.danmakuContentPane;
if (tabId === 'comments') return elements.commentsContentPane;
return null;
}
function isElementInsideScriptUI(el) {
return !!(el && (
el.closest?.(`#${SCRIPT_ELEMENT_IDS.commentContainer}`) ||
el.closest?.(`#${SCRIPT_ELEMENT_IDS.bottomDrawerWrapper}`) ||
el.closest?.(`#${SCRIPT_ELEMENT_IDS.settingsPanel}`)
));
}
function isAdElement(el) {
if (!el || el.nodeType !== 1) return false;
if (el.matches?.(`${SELECTORS.adCard}, ${SELECTORS.adReport}`)) return true;
if (el.closest?.(SELECTORS.adCard) || el.closest?.(SELECTORS.adReport)) return true;
return false;
}
function queryNativeSourceElement(selector, options = {}) {
const { ignoreStale = false } = options;
const cacheKey = `${ignoreStale ? '1' : '0'}::${selector}`;
const now = performance.now();
const cached = layoutQueryCache.get(cacheKey);
if (cached && now - cached.at < LAYOUT_QUERY_CACHE_TTL_MS) {
return cached.value;
}
const candidates = Array.from(document.querySelectorAll(selector)).filter(el =>
document.body.contains(el) && !isElementInsideScriptUI(el) && (ignoreStale || !isProbablyStaleNavigationElement(el))
);
const visibleCandidates = candidates.filter(el => {
const rect = el.getBoundingClientRect();
const style = window.getComputedStyle(el);
return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden';
});
const source = visibleCandidates.length ? visibleCandidates : candidates;
const result = source.length ? pickRichestElement(source) : null;
layoutQueryCache.set(cacheKey, { at: now, value: result });
return result;
}
function cacheNativeSourceElement(key, selector) {
const nativeElement = queryNativeSourceElement(selector);
elements[key] = nativeElement;
if (nativeElement && key === 'videoTitleElement') {
const holder = elements.originalVideoTitleElementHolder;
if (holder) holder.originalFontSize = window.getComputedStyle(nativeElement).fontSize;
}
return nativeElement;
}
function hasNativeSourceForSidebarTab(tabId) {
if (tabId === 'info') {
return !!queryNativeSourceElement(SELECTORS.videoTitle) ||
!!queryNativeSourceElement(SELECTORS.videoInfoMeta) ||
!!queryNativeSourceElement(SELECTORS.videoDescContainer) ||
!!queryNativeSourceElement(SELECTORS.upPanelContainer);
}
if (tabId === 'videos') {
return !!queryNativeSourceElement(SELECTORS.episodeList) ||
!!queryNativeSourceElement(SELECTORS.recommendListBangumi) ||
!!queryNativeSourceElement(SELECTORS.rcmdTab) ||
!!queryNativeSourceElement(SELECTORS.actionList) ||
!!queryNativeSourceElement(SELECTORS.recommendListV1) ||
!!queryNativeSourceElement(SELECTORS.recommendListContainer) ||
!!queryNativeSourceElement(SELECTORS.recommendListFallback);
}
if (tabId === 'danmaku') {
return !!queryNativeSourceElement(SELECTORS.danmakuModules);
}
return true;
}
function setPaneLoadingMessage(tabId) {
const pane = getPaneForSidebarTab(tabId);
if (!pane) return;
if (pane.children.length > 0) return;
const text = (pane.textContent || '').trim();
if (text && !/未在页面找到|加载失败|当前.*无|加载中/.test(text)) return;
if (tabId === 'info') pane.textContent = '信息模块加载中…';
else if (tabId === 'videos') pane.textContent = '推荐内容模块加载中…';
else if (tabId === 'danmaku') pane.textContent = '弹幕模块加载中…';
}
function restoreMovedElementsForSidebarTab(tabId) {
const configs = {
info: [
['videoTitleElement', SELECTORS.videoTitle],
['videoInfoMetaElement', SELECTORS.videoInfoMeta],
['videoDescContainerElement', SELECTORS.videoDescContainer],
['videoTagContainerElement', SELECTORS.videoTagContainer],
['upPanelContainerElement', SELECTORS.upPanelContainer],
['videoInfoContainerWinElement', SELECTORS.videoInfoContainerWin],
['bangumiMediaDescSectionElement', SELECTORS.bangumiMediaDescSection],
['bangumiMediaInfoElement', SELECTORS.bangumiMediaInfo]
],
videos: [
['rcmdTabElement', SELECTORS.rcmdTab],
['actionListElement', SELECTORS.actionList],
['recommendListV1Element', SELECTORS.recommendListV1],
['recommendListContainerElement', SELECTORS.recommendListContainer],
['episodeListElement', SELECTORS.episodeList],
['recommendListBangumiElement', SELECTORS.recommendListBangumi]
],
danmaku: [
['danmakuModulesElement', SELECTORS.danmakuModules]
]
};
const pane = getPaneForSidebarTab(tabId);
const list = configs[tabId] || [];
list.forEach(([elementKey, selector]) => {
let el = elements[elementKey];
if ((!el || !document.body.contains(el)) && pane && selector) {
el = pane.querySelector(selector);
if (el) elements[elementKey] = el;
}
if (!el || !pane || !pane.contains(el)) return;
if (!restoreMovedElementToOriginalPlace(el, elementKey)) return;
if (elementKey === 'bangumiMediaDescSectionElement') elements.bangumiMediaDescSectionElement = null;
});
if (pane && !list.some(([elementKey]) => elements[elementKey] && pane.contains(elements[elementKey]))) {
pane.textContent = '';
}
}
function recacheElementsForSidebarTab(tabId) {
restoreMovedElementsForSidebarTab(tabId);
if (tabId === 'info') {
cacheNativeSourceElement('videoTitleElement', SELECTORS.videoTitle);
cacheNativeSourceElement('videoInfoMetaElement', SELECTORS.videoInfoMeta);
cacheNativeSourceElement('videoDescContainerElement', SELECTORS.videoDescContainer);
cacheNativeSourceElement('videoTagContainerElement', SELECTORS.videoTagContainer);
cacheNativeSourceElement('upPanelContainerElement', SELECTORS.upPanelContainer);
cacheNativeSourceElement('videoInfoContainerWinElement', SELECTORS.videoInfoContainerWin);
} else if (tabId === 'videos') {
cacheNativeSourceElement('episodeListElement', SELECTORS.episodeList);
cacheNativeSourceElement('recommendListBangumiElement', SELECTORS.recommendListBangumi);
cacheNativeSourceElement('rcmdTabElement', SELECTORS.rcmdTab);
cacheNativeSourceElement('actionListElement', SELECTORS.actionList);
cacheNativeSourceElement('recommendListV1Element', SELECTORS.recommendListV1);
const primaryRecommend = cacheNativeSourceElement('recommendListContainerElement', SELECTORS.recommendListContainer);
if (!primaryRecommend) {
const fallback = queryNativeSourceElement(SELECTORS.recommendListFallback);
const fallbackContainer = fallback && !isAdElement(fallback)
? (fallback.closest?.('.recommend-list-container, .recommend-list-v1, .video-card-list') || fallback)
: null;
const safeContainer = (fallbackContainer && !isAdElement(fallbackContainer)) ? fallbackContainer : null;
elements.recommendListContainerElement = safeContainer;
}
} else if (tabId === 'danmaku') {
cacheNativeSourceElement('danmakuModulesElement', SELECTORS.danmakuModules);
}
}
function recacheAllNonCommentSidebarSourceElements() {
recacheElementsForSidebarTab('info');
recacheElementsForSidebarTab('videos');
recacheElementsForSidebarTab('danmaku');
}
function mountAllNonCommentSidebarTabsFromNative() {
recacheAllNonCommentSidebarSourceElements();
manageInfoTabContent(true);
manageVideoTabContent(true);
manageDanmakuTabContent(true);
updateCommentSidebar(0);
}
function scheduleFullNonCommentMountAfterNavigation(retryCount = 0, token = seqOf(SEQ.sidebarWarmup)) {
if (isStaleSeq(SEQ.sidebarWarmup, token)) return;
if (!getLayoutSnapshot().enhanced) {
setNativeNonCommentSourcesHidden(false);
return;
}
if (retryCount === 0) {
manageVideoToolbarForDrawer(true);
scheduleVideoToolbarDrawerRefresh(0, bumpSeq(SEQ.toolbarDrawer));
}
if (!isNonCommentDomReadyForCurrentVideo()) {
setNativeNonCommentSourcesHidden(true);
const waitedMs = nonCommentNavigationState.startedAt ? Date.now() - nonCommentNavigationState.startedAt : 0;
if (waitedMs < 12000) {
waitForDomChange(() => scheduleFullNonCommentMountAfterNavigation(retryCount + 1, token), { tokenName: SEQ.sidebarWarmup, token, timeoutMs: 800 });
return;
}
warn('scheduleFullNonCommentMountAfterNavigation: readiness timeout, mounting latest available native DOM.');
nonCommentNavigationState.active = false;
}
setNativeNonCommentSourcesHidden(false);
const nonCommentTabs = ['info', 'videos', 'danmaku'];
const missingNonCommentTabs = nonCommentTabs.filter(tabId => !sidebarPaneHasUsableContent(tabId));
if (missingNonCommentTabs.length === nonCommentTabs.length) {
mountAllNonCommentSidebarTabsFromNative();
} else {
missingNonCommentTabs.forEach(tabId => {
recacheElementsForSidebarTab(tabId);
manageSidebarTabById(tabId, true);
});
updateCommentSidebar(0);
}
manageVideoToolbarForDrawer(true);
scheduleVideoToolbarDrawerRefresh(0, bumpSeq(SEQ.toolbarDrawer));
manageCommentTabContent(true);
updateSidebarTabIndicator(currentActiveSidebarTabId);
}
function manageSidebarTabById(tabId, shouldDisplayInSidebar) {
if (tabId === 'info') manageInfoTabContent(shouldDisplayInSidebar);
else if (tabId === 'videos') manageVideoTabContent(shouldDisplayInSidebar);
else if (tabId === 'danmaku') manageDanmakuTabContent(shouldDisplayInSidebar);
else if (tabId === 'comments') manageCommentTabContent(shouldDisplayInSidebar);
}
function sidebarPaneHasUsableContent(tabId) {
const pane = getPaneForSidebarTab(tabId);
if (!pane) return false;
if (tabId === 'comments') return !!commentProjectionState.active;
const text = (pane.textContent || '').trim();
if (/未在页面找到|加载失败|当前.*无|加载中/.test(text)) return false;
return pane.children.length > 0;
}
function warmSidebarTabContent(tabId, retryCount = 0, token = seqOf(SEQ.sidebarWarmup), startedAt = Date.now()) {
if (!['info', 'videos', 'danmaku'].includes(tabId)) return;
if (isStaleSeq(SEQ.sidebarWarmup, token)) return;
if (!getLayoutSnapshot().enhanced) return;
if (!elements.commentContainer?.classList.contains(CSS_CLASSES.commentSidebarActive)) {
if (!ensureSidebarShellVisibleDuringTransition()) return;
}
if (sidebarPaneHasUsableContent(tabId)) return;
if (!isNonCommentDomReadyForCurrentVideo() || !hasNativeSourceForSidebarTab(tabId)) {
if (Date.now() - startedAt < 11000) {
waitForDomChange(() => warmSidebarTabContent(tabId, retryCount + 1, token, startedAt), { tokenName: SEQ.sidebarWarmup, token, timeoutMs: 800 });
}
return;
}
setNativeNonCommentSourcesHidden(false);
recacheElementsForSidebarTab(tabId);
manageSidebarTabById(tabId, true);
updateCommentSidebar(0);
}
function warmAllNonCommentSidebarTabs() {
if (!document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) return;
const token = bumpSeq(SEQ.sidebarWarmup);
['info', 'videos', 'danmaku'].forEach((tabId, index) => {
safeSetTimeout(() => warmSidebarTabContent(tabId, 0, token), index * 30);
});
}
function refreshSidebarTabContentFast(tabId = currentActiveSidebarTabId, retryCount = 0, token = seqOf(SEQ.sidebarContent), startedAt = Date.now()) {
if (!VALID_SIDEBAR_TAB_IDS.includes(tabId)) return;
if (isStaleSeq(SEQ.sidebarContent, token)) return;
if (!getLayoutSnapshot().enhanced) return;
if (!elements.commentContainer?.classList.contains(CSS_CLASSES.commentSidebarActive)) {
if (!ensureSidebarShellVisibleDuringTransition()) return;
}
if (currentActiveSidebarTabId !== tabId) return;
if (tabId === 'comments') {
updateCommentProjectionVisibility();
return;
}
if (!isNonCommentDomReadyForCurrentVideo() || !hasNativeSourceForSidebarTab(tabId)) {
setPaneLoadingMessage(tabId);
updateCommentSidebar(0);
if (Date.now() - startedAt < 11000 && currentActiveSidebarTabId === tabId) {
waitForDomChange(() => refreshSidebarTabContentFast(tabId, retryCount + 1, token, startedAt), { tokenName: SEQ.sidebarContent, token, timeoutMs: 600 });
}
return;
}
recacheElementsForSidebarTab(tabId);
manageSidebarTabById(tabId, true);
updateCommentSidebar(0);
if (!sidebarPaneHasUsableContent(tabId) && Date.now() - startedAt < 3000 && currentActiveSidebarTabId === tabId) {
waitForDomChange(() => refreshSidebarTabContentFast(tabId, retryCount + 1, token, startedAt), { tokenName: SEQ.sidebarContent, token, timeoutMs: 400 });
}
}
function isVideoToolbarMountedInDrawer() {
return !!(elements.videoToolbarContainerElement && elements.bottomDrawerContent?.contains(elements.videoToolbarContainerElement));
}
function getNativeVideoToolbarSelector() {
if (isBangumiPlayPage() && document.querySelector(SELECTORS.bangumiVideoToolbar)) {
return SELECTORS.bangumiVideoToolbar;
}
return SELECTORS.videoToolbarContainer;
}
function findToolbarInsideDrawerContent() {
if (!elements.bottomDrawerContent) return null;
if (elements.videoToolbarContainerElement
&& elements.bottomDrawerContent.contains(elements.videoToolbarContainerElement)) {
return elements.videoToolbarContainerElement;
}
return elements.bottomDrawerContent.querySelector(SELECTORS.videoToolbarContainer)
|| elements.bottomDrawerContent.querySelector(SELECTORS.bangumiVideoToolbarRoot);
}
function findNativeVideoToolbarElement() {
const candidates = Array.from(document.querySelectorAll(getNativeVideoToolbarSelector()))
.filter(el => document.body.contains(el) && !isElementInsideScriptUI(el));
if (!candidates.length) return null;
const visibleCandidates = candidates.filter(el => {
const rect = el.getBoundingClientRect();
const style = window.getComputedStyle(el);
return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden';
});
const source = visibleCandidates.length ? visibleCandidates : candidates;
return pickRichestElement(source);
}
function manageVideoToolbarForDrawer(moveToDrawer) {
if (moveToDrawer) getOrCreateBottomDrawer();
if (moveToDrawer && isVideoToolbarMountedInDrawer()) {
if (elements.bottomDrawerWrapper) elements.bottomDrawerWrapper.style.display = 'flex';
return true;
}
const toolbarInDrawer = !!(elements.bottomDrawerContent
&& elements.videoToolbarContainerElement
&& elements.bottomDrawerContent.contains(elements.videoToolbarContainerElement));
if (!moveToDrawer && elements.bottomDrawerContent) {
const toolbarInsideDrawerContent = findToolbarInsideDrawerContent();
if (toolbarInsideDrawerContent) elements.videoToolbarContainerElement = toolbarInsideDrawerContent;
}
const toolbarDetached = !!elements.videoToolbarContainerElement
&& !document.body.contains(elements.videoToolbarContainerElement);
const needsRefetch = !elements.videoToolbarContainerElement
|| (moveToDrawer && isElementInsideScriptUI(elements.videoToolbarContainerElement))
|| (!moveToDrawer && toolbarDetached && !toolbarInDrawer);
if (needsRefetch) {
elements.videoToolbarContainerElement = findNativeVideoToolbarElement();
}
if (!elements.videoToolbarContainerElement) {
warn(`manageVideoToolbarForDrawer: Video toolbar (${getNativeVideoToolbarSelector()}) not found.`);
if (elements.bottomDrawerWrapper) elements.bottomDrawerWrapper.style.display = 'none';
return false;
}
if (moveToDrawer) {
if (!elements.bottomDrawerWrapper && !getOrCreateBottomDrawer()) return false;
if (isBangumiPlayPage()) {
Array.from(elements.bottomDrawerContent.querySelectorAll(SELECTORS.bangumiVideoToolbarRoot))
.forEach(el => {
if (el !== elements.videoToolbarContainerElement) el.remove();
});
}
if (elements.videoToolbarContainerElement.parentElement !== elements.bottomDrawerContent) {
markRestoreAnchor(elements.videoToolbarContainerElement, 'videoToolbarContainerElement');
elements.bottomDrawerContent.appendChild(elements.videoToolbarContainerElement);
}
if (elements.bottomDrawerWrapper) elements.bottomDrawerWrapper.style.display = 'flex';
return true;
}
if ((!elements.videoToolbarContainerElement || !document.body.contains(elements.videoToolbarContainerElement)) && elements.bottomDrawerContent) {
elements.videoToolbarContainerElement = findToolbarInsideDrawerContent();
}
if (elements.videoToolbarContainerElement && elements.videoToolbarContainerElement.parentElement === elements.bottomDrawerContent) {
restoreMovedElementToOriginalPlace(elements.videoToolbarContainerElement, 'videoToolbarContainerElement');
}
if (elements.bottomDrawerWrapper) elements.bottomDrawerWrapper.style.display = 'none';
return true;
}
function scheduleVideoToolbarDrawerRefresh(retryCount = 0, token = seqOf(SEQ.toolbarDrawer), startedAt = Date.now()) {
if (isStaleSeq(SEQ.toolbarDrawer, token)) return;
if (!getLayoutSnapshot().enhanced) return;
if (isVideoToolbarMountedInDrawer()) return;
const mounted = manageVideoToolbarForDrawer(true);
if (!mounted && Date.now() - startedAt < 12000) {
waitForDomChange(() => scheduleVideoToolbarDrawerRefresh(retryCount + 1, token, startedAt), { tokenName: SEQ.toolbarDrawer, token, timeoutMs: 800 });
}
}
function restorePlayerHostLayoutForNativeMode() {
const mirrorVdconEl = document.getElementById(SELECTORS.mirrorVdcon.substring(1)) || elements.mirrorVdcon;
if (mirrorVdconEl && document.body.contains(mirrorVdconEl)) {
mirrorVdconEl.style.paddingLeft = '';
mirrorVdconEl.style.height = '';
mirrorVdconEl.style.justifyContent = '';
}
releasePlayerYieldWidth();
}
function notifyNativeLayoutRecalculated() {
try {
window.dispatchEvent(new Event('resize'));
} catch (e) { }
}
function isMiniPlayerModeActive() {
const targets = [elements.playerWrap, elements.playerContainer, elements.player].filter(Boolean);
if (!targets.length) return false;
const classAndAttrText = targets.map(el => {
const attrs = ['class', 'style', 'data-screen', 'data-player-mode', 'data-mode']
.map(name => el.getAttribute?.(name) || '')
.join(' ');
return `${el.id || ''} ${el.className || ''} ${attrs}`;
}).join(' ').toLowerCase();
if (/(^|[\s_-])(mini|pip|float|floating|small-window|smallwindow|picture-in-picture|pictureinpicture|小窗)([\s_-]|$)/i.test(classAndAttrText)) {
return true;
}
const host = elements.playerWrap || elements.playerContainer || elements.player;
if (!host || !document.body.contains(host)) return false;
const rect = host.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return false;
const style = window.getComputedStyle(host);
const fixedLike = style.position === 'fixed' || style.position === 'sticky';
const smallEnough = rect.width < window.innerWidth * 0.68 && rect.height < window.innerHeight * 0.68;
const awayFromNormalTop = rect.top > 24 || rect.left > 24;
return fixedLike && smallEnough && awayFromNormalTop;
}
function updateMiniPlayerCompatibilityMode() {
const snapshot = getLayoutSnapshot();
const isMiniActive = snapshot.mini;
const wasEnhanced = snapshot.enhanced;
if (!wasEnhanced && !miniPlayerCompatibilityActive) {
document.body.classList.remove(CSS_CLASSES.miniPlayerActive);
return false;
}
document.body.classList.toggle(CSS_CLASSES.miniPlayerActive, isMiniActive);
if (isMiniActive) {
miniPlayerCompatibilityActive = true;
document.documentElement.classList.remove(CSS_CLASSES.bodyEnhancementsActive);
if (wasEnhanced) {
restorePlayerHostLayoutForNativeMode();
if (elements.commentContainer) elements.commentContainer.style.display = 'none';
if (elements.bottomDrawerWrapper) elements.bottomDrawerWrapper.style.display = 'none';
deactivateCommentProjection({ keepReference: true, restoreToPage: false });
}
return true;
}
if (miniPlayerCompatibilityActive) {
miniPlayerCompatibilityActive = false;
document.body.classList.remove(CSS_CLASSES.miniPlayerActive);
if (document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) {
setupEnhancedLayout();
updateCommentSidebar(0);
syncThemeDependentStyles();
applyPlayerStyling();
const miniRecoverToken = bumpSeq(SEQ.sidebarContent);
refreshSidebarTabContentFast(currentActiveSidebarTabId, 0, miniRecoverToken);
warmAllNonCommentSidebarTabs();
scheduleVideoToolbarDrawerRefresh(0, bumpSeq(SEQ.toolbarDrawer));
}
}
return false;
}
// --- Layout and Style Updates ---
function isNativeFullscreen() {
return !!(
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
);
}
function shouldSidebarBeActive(screenState) {
if (screenState !== PLAYER_STATES.WIDE && screenState !== PLAYER_STATES.WEB_FULLSCREEN) return false;
if (!getFeatureToggle(config.featureTogglesKeys.enableSidebar)) return false;
return !pageSpecificModeChecks().isReplyPage;
}
function getLayoutSnapshot(screenOverride = null) {
const container = elements.playerContainer;
const screen = screenOverride || (container ? container.getAttribute('data-screen') : null);
return {
screen,
pageType: isBangumiPlayPage() ? 'bangumi' : (isTargetPage(window.location.href) ? 'video' : 'other'),
replyPage: pageSpecificModeChecks().isReplyPage,
fullscreen: isNativeFullscreen(),
enhanced: document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive),
sidebarVisible: !!elements.commentContainer?.classList.contains(CSS_CLASSES.commentSidebarActive),
sidebarWanted: shouldSidebarBeActive(screen),
viewportSuspended: viewportSuspendedForSize,
mini: isMiniPlayerModeActive(),
activeTab: currentActiveSidebarTabId
};
}
let appliedPlayerYieldMaxWidth = null;
let appliedPlayerYieldScreen = null;
function releasePlayerYieldWidth() {
if (appliedPlayerYieldMaxWidth === null) return;
if (elements.player) elements.player.style.maxWidth = '';
appliedPlayerYieldMaxWidth = null;
appliedPlayerYieldScreen = null;
log("releasePlayerYieldWidth: player max-width released.");
}
function syncPlayerYieldWidth() {
if (!elements.player) return;
const playerEl = elements.player;
const screenState = elements.playerContainer ? elements.playerContainer.getAttribute('data-screen') : null;
if (screenState === PLAYER_STATES.WEB_FULLSCREEN) { releasePlayerYieldWidth(); return; }
if (isBangumiPlayPage()) { releasePlayerYieldWidth(); return; }
if (appliedPlayerYieldMaxWidth !== null
&& appliedPlayerYieldScreen !== screenState
&& screenState
&& appliedPlayerYieldScreen) {
releasePlayerYieldWidth();
}
const windowWidth = window.innerWidth;
const { gap, edgeMargin: browserEdgeMargin, minSidebarWidth, maxSidebarWidth } = readLayoutSettings();
const playerRect = playerEl.getBoundingClientRect();
const playerLeft = Math.round(playerRect.x);
const currentWidth = Math.round(playerRect.width);
const roomForPair = windowWidth - browserEdgeMargin - playerLeft - gap;
let sidebarTarget = Math.round(roomForPair * config.styles.sidebarWidthRatio);
sidebarTarget = Math.max(minSidebarWidth, sidebarTarget);
if (maxSidebarWidth > 0) sidebarTarget = Math.min(maxSidebarWidth, sidebarTarget);
const playerBudget = Math.floor(Math.max(config.styles.minPlayerWidth, roomForPair - sidebarTarget));
if (!(playerBudget > 0)) {
releasePlayerYieldWidth();
return;
}
if (appliedPlayerYieldMaxWidth === null) {
if (currentWidth <= playerBudget + 1) return;
playerEl.style.maxWidth = `${playerBudget}px`;
appliedPlayerYieldMaxWidth = playerBudget;
appliedPlayerYieldScreen = screenState;
log(`syncPlayerYieldWidth: capped player max-width to ${playerBudget}px (was ${currentWidth}px, budget ${playerBudget}px, viewport ${windowWidth}px).`);
return;
}
if (playerBudget === appliedPlayerYieldMaxWidth) return;
playerEl.style.maxWidth = `${playerBudget}px`;
appliedPlayerYieldMaxWidth = playerBudget;
log(`syncPlayerYieldWidth: updated player max-width to ${playerBudget}px (viewport ${windowWidth}px).`);
}
const VIEWPORT_SUSPEND = { minWidth: 900, minHeight: 480, resumeWidth: 960, resumeHeight: 520 };
function isViewportFatalForSidebar() {
const w = window.innerWidth, h = window.innerHeight;
return viewportSuspendedForSize
? (w < VIEWPORT_SUSPEND.resumeWidth || h < VIEWPORT_SUSPEND.resumeHeight)
: (w < VIEWPORT_SUSPEND.minWidth || h < VIEWPORT_SUSPEND.minHeight);
}
function syncViewportSuspension() {
if (!elements.player) return viewportSuspendedForSize;
const tooSmall = isViewportFatalForSidebar();
if (tooSmall && !viewportSuspendedForSize) {
viewportSuspendedForSize = true;
log('viewport too small for sidebar; suspending enhanced layout.');
if (getLayoutSnapshot().enhanced) resetEnhancedFeatures();
return true;
}
if (!tooSmall && viewportSuspendedForSize) {
viewportSuspendedForSize = false;
log('viewport recovered; re-applying enhanced layout.');
if (elements.playerContainer) {
handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'))
.catch(e => warn('syncViewportSuspension: re-apply failed.', e));
}
return true;
}
return viewportSuspendedForSize;
}
function applyBangumiMainWidthBudget(windowWidth, browserEdgeMargin, gap, minSidebarWidth, maxSidebarWidth) {
if (!isBangumiPlayPage()) return;
if (!document.querySelector('.main-container')) return;
if (!document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) {
setCssVarsIfChanged(document.body, { '--biliplus-bangumi-main-width': 'auto' });
return;
}
const roomForPair = windowWidth - browserEdgeMargin * 2 - gap;
let sidebarTarget = Math.round(roomForPair * config.styles.sidebarWidthRatio);
sidebarTarget = Math.max(minSidebarWidth, sidebarTarget);
if (maxSidebarWidth > 0) sidebarTarget = Math.min(maxSidebarWidth, sidebarTarget);
const budget = Math.floor(roomForPair - sidebarTarget);
if (!(budget > 0)) return;
setCssVarsIfChanged(document.body, { '--biliplus-bangumi-main-width': `${budget}px` });
}
function calculateSidebarLayout() {
const windowWidth = window.innerWidth;
const { gap, edgeMargin: browserEdgeMargin, minSidebarWidth, maxSidebarWidth } = readLayoutSettings();
applyBangumiMainWidthBudget(windowWidth, browserEdgeMargin, gap, minSidebarWidth, maxSidebarWidth);
syncPlayerYieldWidth();
discardOwnMutations();
const playerRect = elements.player.getBoundingClientRect();
const topPx = Math.max(0, Math.round(playerRect.top));
const availableHeight = Math.max(120, Math.round(window.innerHeight - topPx - browserEdgeMargin));
const sidebarHeight = availableHeight;
let left = playerRect.right + gap;
let width = windowWidth - left - browserEdgeMargin;
width = Math.max(minSidebarWidth, width);
if (maxSidebarWidth > 0) {
width = Math.min(maxSidebarWidth, width);
}
left = Math.max(left, windowWidth - browserEdgeMargin - width);
const maxLeft = windowWidth - browserEdgeMargin - width;
if (left > maxLeft) {
left = Math.max(0, maxLeft);
}
return {
left: left,
width: width > 0 ? width : minSidebarWidth,
height: sidebarHeight,
top: `${topPx}px`,
playerRect: playerRect
};
}
function updateCommentSidebar(retryCount = 0) {
if (sidebarUpdateRAFId) cancelAnimationFrame(sidebarUpdateRAFId);
const mainSidebarContainer = getOrCreateCommentContainer();
if (!mainSidebarContainer) {
warn("updateCommentSidebar: Sidebar container not found.");
return;
}
const snapshot = getLayoutSnapshot();
if (snapshot.viewportSuspended) return;
const currentPlayerScreen = snapshot.screen;
if (snapshot.fullscreen) return;
if (!currentPlayerScreen && snapshot.enhanced && snapshot.pageType !== 'other') {
ensureSidebarShellVisibleDuringTransition();
return;
}
if (!snapshot.sidebarWanted) {
if (snapshot.sidebarVisible) {
log("updateCommentSidebar: Conditions not met for sidebar, hiding.");
mainSidebarContainer.classList.remove(CSS_CLASSES.commentSidebarActive);
mainSidebarContainer.style.display = 'none';
deactivateCommentProjection({ keepReference: true });
restoreCommentNativeActivationAnchor();
manageInfoTabContent(false);
manageVideoTabContent(false);
manageDanmakuTabContent(false);
manageVideoToolbarForDrawer(false);
sidebarHiddenByCondition = true;
if (!document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) {
restorePlayerHostLayoutForNativeMode();
}
if (elements.playerWrap && elements.playerWrap.style.position === 'absolute' && elements.playerWrap.style.left !== '50%') {
elements.playerWrap.style.position = '';
elements.playerWrap.style.left = '';
elements.playerWrap.style.transform = '';
}
}
return;
}
if (!elements.player) {
warn("updateCommentSidebar: Player core elements not cached.");
return;
}
const layout = calculateSidebarLayout();
if (layout.playerRect.width < 100 || layout.playerRect.height < 50) {
if (retryCount < config.attempts.sidebarPollMaxRetries) {
sidebarUpdateRAFId = requestAnimationFrame(() => updateCommentSidebar(retryCount + 1));
return;
} else {
warn("updateCommentSidebar: Player dimensions too small after retries; keeping current sidebar shell during transition.");
return;
}
}
setCssVarsIfChanged(mainSidebarContainer, {
'--biliplus-sidebar-left': `${layout.left}px`,
'--biliplus-sidebar-width': `${layout.width}px`,
'--biliplus-sidebar-top': layout.top,
'--biliplus-sidebar-height': `${layout.height}px`
});
mainSidebarContainer.classList.add(CSS_CLASSES.commentSidebarActive);
mainSidebarContainer.classList.toggle('bili-sidebar--compact', layout.width < 300);
if (sidebarHiddenByCondition) {
sidebarHiddenByCondition = false;
if (currentActiveSidebarTabId !== 'comments') {
manageSidebarTabById(currentActiveSidebarTabId, true);
}
}
if (snapshot.enhanced) {
if (elements.commentContainer?.classList.contains(CSS_CLASSES.commentSidebarActive)) {
const videoIdForTabState = getCurrentVideoId() || window.location.href;
if (sidebarTabStateAppliedVideoId !== videoIdForTabState) {
sidebarTabStateAppliedVideoId = videoIdForTabState;
}
if (currentActiveSidebarTabId === 'comments') {
updateCommentProjectionVisibility();
syncCommentProjection();
}
}
}
}
function refreshSidebarForActiveScreen() {
updateCommentSidebar(0);
syncThemeDependentStyles();
applyPlayerStyling();
const refreshToken = bumpSeq(SEQ.sidebarContent);
refreshSidebarTabContentFast(currentActiveSidebarTabId, 0, refreshToken);
warmAllNonCommentSidebarTabs();
}
function isActuallyDarkMode() {
if (document.documentElement.classList.contains('dark')) return true;
if (document.documentElement.getAttribute('data-darkreader-scheme') === 'dark') return true;
try {
const bodyBgColor = window.getComputedStyle(document.body).backgroundColor;
const rgb = bodyBgColor.match(/\d+/g);
if (rgb && rgb.length >= 3) {
const r = parseInt(rgb[0]), g = parseInt(rgb[1]), b = parseInt(rgb[2]);
if ((r + g + b) < 382.5) return true;
}
} catch (e) { warn(`isActuallyDarkMode: Error: ${e.message}`); }
return false;
}
function syncThemeDependentStyles() {
log("Syncing theme-dependent styles.");
const isDark = isActuallyDarkMode();
setCssVarsIfChanged(document.documentElement, {
'--biliplus-themed-box-shadow-border-color': isDark ? 'rgba(255,255,255,0.15)' : 'rgba(0,0,0,0.1)',
'--dynamic-shadow-color': isDark ? 'rgba(0,0,0,0.15)' : 'rgba(0,0,0,0.08)'
});
if (elements.sidebarTabHeader) {
const themedBorderColor = window.getComputedStyle(document.documentElement).getPropertyValue('--line_regular').trim() || (isDark ? '#444' : '#ddd');
assignStyleIfChanged(elements.sidebarTabHeader, { borderBottomColor: themedBorderColor });
}
}
// --- Enhanced Features Management ---
function resetEnhancedFeatures() {
log("resetEnhancedFeatures: Starting full reset of enhanced features.");
manageInfoTabContent(false);
manageVideoTabContent(false);
manageDanmakuTabContent(false);
manageVideoToolbarForDrawer(false);
manageCommentTabContent(false);
if (elements.playerWrap) {
elements.playerWrap.style.position = '';
elements.playerWrap.style.left = '';
elements.playerWrap.style.transform = '';
elements.playerWrap.style.width = '';
elements.playerWrap.style.height = '';
elements.playerWrap.style.top = '';
}
restorePlayerHostLayoutForNativeMode();
log(`resetEnhancedFeatures: content restored, #mirror-vdcon layout restored to native values.`);
document.documentElement.style.overflowAnchor = 'none';
if (document.body) document.body.style.overflowAnchor = 'none';
document.body.classList.remove(CSS_CLASSES.bodyEnhancementsActive);
document.documentElement.classList.remove(CSS_CLASSES.bodyEnhancementsActive);
document.body.classList.remove('bili-plus-bangumi');
setNativeNonCommentSourcesHidden(false);
document.body.classList.remove(CSS_CLASSES.miniPlayerActive);
miniPlayerCompatibilityActive = false;
if (elements.commentContainer) {
elements.commentContainer.classList.remove(CSS_CLASSES.commentSidebarActive);
elements.commentContainer.style.display = 'none';
}
const leftContainer = document.querySelector(SELECTORS.leftContainer);
if (leftContainer) {
leftContainer.style.width = '';
leftContainer.style.marginTop = '';
}
const playerVideoArea = elements.playerContainer?.querySelector(SELECTORS.videoArea);
const playerPlaceholderTop = document.getElementById(SCRIPT_ELEMENT_IDS.playerPlaceholderTop);
const playerSendingBarEl = elements.playerContainer?.querySelector(SELECTORS.sendingBar);
const playerPlaceholderBottom = document.getElementById(SCRIPT_ELEMENT_IDS.playerPlaceholderBottom);
if (playerVideoArea) playerVideoArea.style.borderRadius = '';
if (playerPlaceholderTop) playerPlaceholderTop.style.borderRadius = '';
if (playerSendingBarEl) playerSendingBarEl.style.borderRadius = '';
if (playerPlaceholderBottom) playerPlaceholderBottom.style.borderRadius = '';
if (elements.player) elements.player.style.borderRadius = '';
if (elements.playerContainer) elements.playerContainer.style.borderRadius = '';
if (pendingNativeLayoutRestoreTimer) {
clearTimeout(pendingNativeLayoutRestoreTimer);
activeTimers.delete(pendingNativeLayoutRestoreTimer);
pendingNativeLayoutRestoreTimer = null;
}
pendingNativeLayoutRestoreTimer = safeSetTimeout(() => {
pendingNativeLayoutRestoreTimer = null;
if (document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) return;
restorePlayerHostLayoutForNativeMode();
}, 500);
notifyNativeLayoutRecalculated();
try { window.scrollTo(0, 0); } catch (e) { }
safeSetTimeout(() => {
try {
document.documentElement.style.overflowAnchor = '';
if (document.body) document.body.style.overflowAnchor = '';
} catch (e) { }
}, 600);
discardOwnMutations();
log("Enhanced features reset complete.");
}
function setupEnhancedLayout() {
if (window.scrollY > 0) {
try { window.scrollTo(0, 0); } catch (e) { }
}
const mirrorVdconEl = elements.mirrorVdcon || document.getElementById(SELECTORS.mirrorVdcon.substring(1));
if (mirrorVdconEl) {
mirrorVdconEl.style.paddingLeft = 'var(--biliplus-browser-edge-margin)';
mirrorVdconEl.style.justifyContent = 'space-between';
}
document.body.classList.add(CSS_CLASSES.bodyEnhancementsActive);
document.documentElement.classList.add(CSS_CLASSES.bodyEnhancementsActive);
if (isBangumiPlayPage()) document.body.classList.add('bili-plus-bangumi');
if (elements.playerWrap) {
elements.playerWrap.style.left = '';
elements.playerWrap.style.transform = '';
}
const leftContainer = document.querySelector(SELECTORS.leftContainer);
if (leftContainer && elements.player) {
leftContainer.style.marginTop = '11px';
}
}
function moveContentToSidebar() {
getOrCreateCommentContainer();
getOrCreateBottomDrawer();
if (!elements.commentContainer || !elements.infoContentPane) {
warn("moveContentToSidebar: Sidebar container or panels not ready.");
return;
}
if (elements.commentContainer) {
elements.commentContainer.classList.add(CSS_CLASSES.commentSidebarActive);
elements.commentContainer.style.display = 'flex';
}
if (nonCommentNavigationState.active && !isNonCommentDomReadyForCurrentVideo()) {
setNativeNonCommentSourcesHidden(true);
['info', 'videos', 'danmaku'].forEach(setPaneLoadingMessage);
manageVideoToolbarForDrawer(true);
scheduleVideoToolbarDrawerRefresh(0, bumpSeq(SEQ.toolbarDrawer));
manageCommentTabContent(true);
warmAllNonCommentSidebarTabs();
return;
}
setNativeNonCommentSourcesHidden(false);
mountAllNonCommentSidebarTabsFromNative();
manageVideoToolbarForDrawer(true);
scheduleVideoToolbarDrawerRefresh(0, bumpSeq(SEQ.toolbarDrawer));
manageCommentTabContent(true);
warmAllNonCommentSidebarTabs();
discardOwnMutations();
}
function applyPlayerStyling() {
const topOnlyRadius = `var(--biliplus-border-radius) var(--biliplus-border-radius) 0 0`;
const bottomOnlyRadius = `0 0 var(--biliplus-border-radius) var(--biliplus-border-radius)`;
const playerVideoArea = elements.playerContainer?.querySelector(SELECTORS.videoArea);
if (playerVideoArea) playerVideoArea.style.borderRadius = topOnlyRadius;
const playerPlaceholderTopEl = document.getElementById(SCRIPT_ELEMENT_IDS.playerPlaceholderTop);
if (playerPlaceholderTopEl) playerPlaceholderTopEl.style.borderRadius = topOnlyRadius;
const playerSendingBarEl = elements.playerContainer?.querySelector(SELECTORS.sendingBar);
if (playerSendingBarEl) playerSendingBarEl.style.borderRadius = bottomOnlyRadius;
const playerPlaceholderBottomEl = document.getElementById(SCRIPT_ELEMENT_IDS.playerPlaceholderBottom);
if (playerPlaceholderBottomEl) playerPlaceholderBottomEl.style.borderRadius = bottomOnlyRadius;
if (elements.player) elements.player.style.borderRadius = 'var(--biliplus-border-radius)';
if (elements.playerContainer) elements.playerContainer.style.borderRadius = 'var(--biliplus-border-radius)';
discardOwnMutations();
}
async function applyEnhancedFeatures() {
if (enhancedFeaturesApplyPromise) {
log("applyEnhancedFeatures: already in progress, awaiting current run.");
return enhancedFeaturesApplyPromise;
}
enhancedFeaturesApplyPromise = (async () => {
try {
log("applyEnhancedFeatures: Orchestrating enhanced features application.");
if (viewportSuspendedForSize) {
log("applyEnhancedFeatures: skipped (viewport too small).");
return;
}
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
if (!elements.player) {
if (!await ensureAllElementsCached()) {
warn("applyEnhancedFeatures: Critical elements not cached. Aborting apply.");
resetEnhancedFeatures();
return;
}
} else {
cacheContentElements(true);
}
setupEnhancedLayout();
moveContentToSidebar();
detectConflictingScripts();
applyPlayerStyling();
syncThemeDependentStyles();
loadAndApplyTabState();
sidebarTabStateAppliedVideoId = getCurrentVideoId() || window.location.href;
updateCommentSidebar(0);
const applyRefreshToken = bumpSeq(SEQ.sidebarContent);
refreshSidebarTabContentFast(currentActiveSidebarTabId, 0, applyRefreshToken);
log("Enhanced features applied successfully.");
} finally {
enhancedFeaturesApplyPromise = null;
}
})();
return enhancedFeaturesApplyPromise;
}
// --- Event Handlers and Observers ---
async function handleDataScreenChange(newScreenState) {
const snapshot = getLayoutSnapshot(newScreenState);
if (snapshot.fullscreen) {
log(`handleDataScreenChange: Ignored while in fullscreen (newScreenState = ${newScreenState})`);
return;
}
if (updateMiniPlayerCompatibilityMode()) {
log(`handleDataScreenChange: Suspended enhanced layout while mini player is active (newScreenState = ${newScreenState})`);
return;
}
log(`handleDataScreenChange: New screen state = ${newScreenState}`);
const isSidebarDesired = snapshot.sidebarWanted;
const isSidebarCurrentlyActive = snapshot.enhanced;
let didFullReset = false;
if (isSidebarDesired) {
if (!isSidebarCurrentlyActive) {
log("Sidebar inactive -> active, performing full initialization.");
await applyEnhancedFeatures();
} else {
log("Sidebar already active, updating layout only.");
if (!elements.player) {
await ensureAllElementsCached();
}
refreshSidebarForActiveScreen();
}
} else {
if (isSidebarCurrentlyActive) {
log("Sidebar active -> inactive, performing full reset.");
if (newScreenState === PLAYER_STATES.NORMAL) {
userManuallyExitedWide = true;
log("handleDataScreenChange: marked userManuallyExitedWide (exit to normal) to block auto re-entry.");
}
resetEnhancedFeatures();
didFullReset = true;
} else {
log("Sidebar inactive, no action needed.");
}
}
if (didFullReset) {
log("handleDataScreenChange: skip auto-scroll after full reset (stay at top).");
} else if (newScreenState === PLAYER_STATES.WIDE) {
safeSetTimeout(scrollToPlayer, config.delays.stateChangeProcess / 2);
} else if (newScreenState === PLAYER_STATES.NORMAL && isSidebarCurrentlyActive) {
try { window.scrollTo(0, 0); } catch (e) { }
}
}
function handlePlayerCtrlAreaClick(event) {
const target = event.target.closest('div[class^="bpx-player-ctrl-"]');
if (!target) return;
if (target.matches(SELECTORS.wideBtn)) {
if (!elements.playerContainer) return;
userManuallyExitedWide = elements.playerContainer.getAttribute('data-screen') === PLAYER_STATES.WIDE;
log(`handlePlayerCtrlAreaClick (wide): userManuallyExitedWide set to ${userManuallyExitedWide}`);
} else if (target.matches(SELECTORS.webFullBtn)) {
userManuallyExitedWide = false;
log("handlePlayerCtrlAreaClick (web-full): Reset manual exit flag.");
} else if (target.matches(SELECTORS.fullBtn)) {
log("handlePlayerCtrlAreaClick (full): Entering fullscreen.");
} else if (target.matches(SELECTORS.viewpointBtn)) {
log("handlePlayerCtrlAreaClick (viewpoint): Viewpoint button clicked.");
setActiveSidebarTab('danmaku');
}
}
async function ensureWideMode() {
const isAutoWidescreenEnabledGM = getFeatureToggle(config.featureTogglesKeys.enableWideScreen);
if (!isAutoWidescreenEnabledGM) {
if (elements.playerContainer) await handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'));
return;
}
if (!elements.playerContainer || !elements.wideBtn) {
if (!await ensureAllElementsCached()) { warn("ensureWideMode: Failed to cache critical elements."); return; }
}
if (!elements.playerContainer || !elements.wideBtn) { warn("ensureWideMode: Core player elements still not found after re-cache attempt."); return; }
const { isReplyPage } = pageSpecificModeChecks();
if (isReplyPage || userManuallyExitedWide) {
if (elements.playerContainer) await handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'));
return;
}
if (elements.playerContainer.getAttribute('data-screen') === PLAYER_STATES.NORMAL) {
log("ensureWideMode: Currently in normal mode, clicking wide button.");
elements.wideBtn.click();
} else await handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'));
}
async function conditionallyEnterWideMode() {
const isAutoWideEnabled = getFeatureToggle(config.featureTogglesKeys.enableWideScreen);
const { isReplyPage } = pageSpecificModeChecks();
if (isAutoWideEnabled && !isReplyPage && !userManuallyExitedWide) {
await ensureWideMode();
return true;
}
return false;
}
function handleKeyPress(event) {
if (!elements.playerContainer) return;
if (event.key === 'Escape') {
const inFullscreen = isNativeFullscreen();
const inPlayer = !!elements.playerContainer.contains(event.target);
if (!inFullscreen && !inPlayer) return;
const screenMode = elements.playerContainer.getAttribute('data-screen');
log(`handleKeyPress: Escape pressed in screen mode: ${screenMode}`);
if (screenMode === PLAYER_STATES.WIDE || screenMode === PLAYER_STATES.WEB_FULLSCREEN || screenMode === PLAYER_STATES.FULLSCREEN) {
userManuallyExitedWide = true;
log(`handleKeyPress: userManuallyExitedWide set to true due to Esc from ${screenMode}.`);
}
}
}
async function handleFullscreenChange() {
if (!elements.playerContainer) return;
safeSetTimeout(async () => {
const isFullScreenActive = isNativeFullscreen();
log(`handleFullscreenChange: isFullScreenActive = ${isFullScreenActive}`);
if (isFullScreenActive) {
if (elements.commentContainer) {
elements.commentContainer.style.display = 'none';
log("Fullscreen entered: sidebar hidden.");
}
return;
}
const currentScreen = elements.playerContainer.getAttribute('data-screen');
log(`Exited fullscreen. Player data-screen = ${currentScreen}`);
const shouldShowSidebar = shouldSidebarBeActive(currentScreen);
if (shouldShowSidebar) {
if (document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) {
if (elements.commentContainer) {
elements.commentContainer.style.display = 'flex';
}
refreshSidebarForActiveScreen();
log("Fullscreen exited: sidebar restored and content refresh scheduled.");
} else {
log("Fullscreen exited: sidebar not built, performing full init.");
await applyEnhancedFeatures();
}
} else {
if (document.body.classList.contains(CSS_CLASSES.bodyEnhancementsActive)) {
log("Fullscreen exited to normal mode, resetting sidebar.");
resetEnhancedFeatures();
} else {
if (elements.commentContainer) {
elements.commentContainer.style.display = 'none';
}
}
}
}, config.delays.stateChangeProcess);
}
function handleDynamicBackgroundChange() {
log("handleDynamicBackgroundChange: Page theme/background change detected.");
syncThemeDependentStyles();
}
function setupDynamicBackgroundObserver() {
if (dynamicBgObserver) dynamicBgObserver.disconnect();
if (dynamicBgDebouncedRef) dynamicBgDebouncedRef.cancel();
dynamicBgDebouncedRef = debounce(handleDynamicBackgroundChange, config.delays.debounce);
dynamicBgObserver = new MutationObserver(dynamicBgDebouncedRef);
dynamicBgObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-darkreader-scheme'] });
syncThemeDependentStyles();
log("Dynamic background/theme observer set up.");
}
function detectConflictingScripts() {
const hit = document.querySelector('[id^="bilibili-evolved"], [class*="bilibili-evolved"], [data-bilibili-evolved]');
if (!hit) return;
if (document.documentElement.dataset.biliplusConflict === 'bilibili-evolved') return;
document.documentElement.dataset.biliplusConflict = 'bilibili-evolved';
warn('Detected bilibili-evolved on this page; both scripts adjust native layout. Keep its related features off if layout looks wrong.');
}
function findReactClickHandler(target, boundary) {
for (let el = target; el && el !== boundary && el !== document.body; el = el.parentElement) {
const propsKey = Object.keys(el).find(k => k.startsWith('__reactProps$'));
const onClick = propsKey && el[propsKey]?.onClick;
if (typeof onClick === 'function') return onClick;
}
return null;
}
function preserveScrollAcrossSiteRoute() {
const savedY = window.scrollY;
if (savedY <= 0) return;
const onScroll = () => {
if (window.scrollY > 1) return;
window.removeEventListener('scroll', onScroll, true);
window.scrollTo({ top: savedY, behavior: 'instant' });
};
window.addEventListener('scroll', onScroll, true);
setTimeout(() => window.removeEventListener('scroll', onScroll, true), 2000);
}
function dispatchSiteRoute(target, anchor, event) {
const onClick = findReactClickHandler(target, null);
if (onClick) {
preserveScrollAcrossSiteRoute();
onClick(event);
if (anchor && !event.defaultPrevented) event.preventDefault();
return true;
}
if (!anchor) return false;
const reactRoot = document.querySelector('#__next');
if (!reactRoot || reactRoot.contains(anchor)) return false;
preserveScrollAcrossSiteRoute();
event.preventDefault();
event.stopPropagation();
const placeholder = document.createComment('bili-plus-route-anchor');
anchor.before(placeholder);
reactRoot.appendChild(anchor);
try {
anchor.click();
} finally {
if (placeholder.isConnected) placeholder.replaceWith(anchor);
else anchor.remove();
}
return true;
}
function forwardScriptUIAnchorClick(event) {
if (event.defaultPrevented || event.button !== 0) return;
if (!document.querySelector('#__next')) return;
const target = event.target;
if (!(target instanceof Element) || !isElementInsideScriptUI(target)) return;
if (target.closest('#bili-plus-settings-panel') || elements.sidebarTabHeader?.contains(target)) return;
const anchor = target.closest('a[href]');
if (anchor) {
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
if (anchor.target && anchor.target !== '_self') return;
let url;
try { url = new URL(anchor.href, window.location.href); } catch (e) { return; }
if (url.origin !== window.location.origin) return;
}
dispatchSiteRoute(target, anchor, event);
}
async function setupListeners() {
removeListenersAndObserver();
detectConflictingScripts();
if (!await ensureAllElementsCached()) {
warn("setupListeners: Failed to cache critical elements. Some listeners might not be attached.");
}
if (elements.playerContainer) {
if (playerStateObserver) playerStateObserver.disconnect();
playerStateObserver = new MutationObserver(async (mutationsList) => {
try {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'data-screen') {
const newScreenState = elements.playerContainer?.getAttribute('data-screen');
log(`playerStateObserver: data-screen changed to "${newScreenState}"`);
await handleDataScreenChange(newScreenState);
}
}
} catch (e) {
error('playerStateObserver: handleDataScreenChange failed.', e);
}
});
playerStateObserver.observe(elements.playerContainer, { attributes: true, attributeFilter: ['data-screen'] });
const playerCtrlArea = elements.playerContainer.querySelector(SELECTORS.playerCtrlArea) || elements.playerContainer;
playerCtrlArea.addEventListener('click', handlePlayerCtrlAreaClick);
const videoArea = elements.playerContainer.querySelector(SELECTORS.videoArea);
if (videoArea) {
if (videoAreaDblClickListenerRef) videoArea.removeEventListener('dblclick', videoAreaDblClickListenerRef);
videoAreaDblClickListenerRef = () => {
userManuallyExitedWide = false;
log("Video area dblclick: Reset manual exit flag.");
};
videoArea.addEventListener('dblclick', videoAreaDblClickListenerRef);
}
if (playerResizeObserver) playerResizeObserver.disconnect();
if (playerResizeDebouncedRef) playerResizeDebouncedRef.cancel();
playerResizeDebouncedRef = debounce(updateLayoutAndStyles, config.delays.debounce);
playerResizeObserver = new ResizeObserver(entries => {
const entry = entries[entries.length - 1];
if (!entry) return;
const inlineSize = entry.borderBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;
const blockSize = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;
const width = Math.round(inlineSize);
const height = Math.round(blockSize);
if (width === lastObservedPlayerWidth && height === lastObservedPlayerHeight) return;
lastObservedPlayerWidth = width;
lastObservedPlayerHeight = height;
playerResizeDebouncedRef();
});
lastObservedPlayerWidth = 0;
lastObservedPlayerHeight = 0;
if (miniPlayerObserver) miniPlayerObserver.disconnect();
if (miniPlayerDebouncedRef) miniPlayerDebouncedRef.cancel();
miniPlayerDebouncedRef = debounce(updateLayoutAndStyles, config.delays.debounce);
miniPlayerObserver = new MutationObserver(miniPlayerDebouncedRef);
[elements.playerWrap, elements.playerContainer, elements.player].filter(Boolean).forEach(el => {
try { miniPlayerObserver.observe(el, { attributes: true, attributeFilter: ['class', 'style', 'data-screen', 'data-player-mode', 'data-mode'] }); } catch (e) { }
});
log("ResizeObserver and mini-player observer for player container set up.");
} else {
warn("Player container not found. Listeners for player interactions and ResizeObserver cannot be set.");
if (!windowResizeHandlerRef) {
windowResizeHandlerRef = debounce(updateLayoutAndStyles, config.delays.debounce);
}
window.addEventListener('resize', windowResizeHandlerRef);
}
fsHandlerRef = handleFullscreenChange;
document.addEventListener('fullscreenchange', fsHandlerRef);
document.addEventListener('webkitfullscreenchange', fsHandlerRef);
document.addEventListener('mozfullscreenchange', fsHandlerRef);
document.addEventListener('MSFullscreenChange', fsHandlerRef);
document.addEventListener('keydown', handleKeyPress);
scriptUIAnchorClickRef = forwardScriptUIAnchorClick;
document.addEventListener('click', scriptUIAnchorClickRef, true);
setupDynamicBackgroundObserver();
log("Event listeners and core observers (attempted to be) set up.");
}
// --- Page Navigation and Script Lifecycle ---
function pageSpecificModeChecks() {
return { isReplyPage: window.location.hash.startsWith('#reply') };
}
function clearNonCoreElementReferences() {
log("clearNonCoreElementReferences: Clearing non-UI core element references.");
const keysToClear = ['commentApp', 'rcmdTabElement', 'actionListElement', 'recommendListV1Element', 'recommendListContainerElement', 'episodeListElement', 'bangumiMediaInfoElement', 'bangumiMediaDescSectionElement', 'recommendListBangumiElement', 'videoTitleElement', 'videoInfoMetaElement', 'videoDescContainerElement', 'videoTagContainerElement', 'upPanelContainerElement', 'danmakuModulesElement', 'videoToolbarContainerElement', 'videoInfoContainerWinElement', 'viewboxReportElement', 'mirrorVdcon'];
keysToClear.forEach(key => { elements[key] = null; });
if (elements.originalVideoTitleElementHolder) elements.originalVideoTitleElementHolder.originalFontSize = '';
elements.originalMirrorVdconHeight = '';
elements.originalMirrorVdconPaddingLeft = '';
}
function removeListenersAndObserver({ resetLayout = false } = {}) {
log(`removeListenersAndObserver: resetLayout = ${resetLayout}`);
cancelDomWaits();
clearAllTimers();
if (pendingScrollOperation) {
cancelAnimationFrame(pendingScrollOperation.rafId);
if (pendingScrollOperation.timerId) clearTimeout(pendingScrollOperation.timerId);
pendingScrollOperation = null;
}
isScrolling = false;
if (pendingNativeLayoutRestoreTimer) {
clearTimeout(pendingNativeLayoutRestoreTimer);
activeTimers.delete(pendingNativeLayoutRestoreTimer);
pendingNativeLayoutRestoreTimer = null;
}
layoutQueryCache.clear();
if (sidebarUpdateRAFId) cancelAnimationFrame(sidebarUpdateRAFId); sidebarUpdateRAFId = null;
if (playerStateObserver) { playerStateObserver.disconnect(); playerStateObserver = null; }
if (coreElementsObserver) { coreElementsObserver.disconnect(); coreElementsObserver = null; }
if (dynamicBgObserver) { dynamicBgObserver.disconnect(); dynamicBgObserver = null; }
if (dynamicBgDebouncedRef) { dynamicBgDebouncedRef.cancel(); dynamicBgDebouncedRef = null; }
if (playerResizeObserver) { playerResizeObserver.disconnect(); playerResizeObserver = null; }
if (playerResizeDebouncedRef) { playerResizeDebouncedRef.cancel(); playerResizeDebouncedRef = null; }
if (miniPlayerObserver) { miniPlayerObserver.disconnect(); miniPlayerObserver = null; }
if (miniPlayerDebouncedRef) { miniPlayerDebouncedRef.cancel(); miniPlayerDebouncedRef = null; }
if (elements.playerContainer) {
const playerCtrlArea = elements.playerContainer.querySelector(SELECTORS.playerCtrlArea) || elements.playerContainer;
if (playerCtrlArea) playerCtrlArea.removeEventListener('click', handlePlayerCtrlAreaClick);
const videoArea = elements.playerContainer.querySelector(SELECTORS.videoArea);
if (videoArea && videoAreaDblClickListenerRef) { videoArea.removeEventListener('dblclick', videoAreaDblClickListenerRef); videoAreaDblClickListenerRef = null; }
}
document.removeEventListener('keydown', handleKeyPress);
if (scriptUIAnchorClickRef) {
document.removeEventListener('click', scriptUIAnchorClickRef, true);
scriptUIAnchorClickRef = null;
}
if (fsHandlerRef) {
document.removeEventListener('fullscreenchange', fsHandlerRef); document.removeEventListener('webkitfullscreenchange', fsHandlerRef);
document.removeEventListener('mozfullscreenchange', fsHandlerRef); document.removeEventListener('MSFullscreenChange', fsHandlerRef);
fsHandlerRef = null;
}
if (windowResizeHandlerRef) {
windowResizeHandlerRef.cancel?.();
window.removeEventListener('resize', windowResizeHandlerRef);
windowResizeHandlerRef = null;
}
if (resetLayout) resetEnhancedFeatures();
deactivateCommentProjection({ keepReference: true });
manageCommentTabContent(false);
if (!resetLayout) restoreMovedNonCommentContentToPage();
clearNonCoreElementReferences();
['player', 'playerContainer', 'playerWrap', 'wideBtn'].forEach(key => {
if (!(elements[key] && document.body.contains(elements[key]))) elements[key] = null;
});
log("Event listeners and observers removed.");
}
async function updateLayoutAndStyles() {
log("updateLayoutAndStyles: Updating layout and styles due to resize or other trigger.");
syncThemeDependentStyles();
if (updateMiniPlayerCompatibilityMode()) {
log("updateLayoutAndStyles: Mini player compatibility mode active; enhanced layout update suspended.");
return;
}
if (syncViewportSuspension()) {
log("updateLayoutAndStyles: enhanced layout suspended for viewport size.");
return;
}
if (getLayoutSnapshot().enhanced && elements.playerContainer) {
updateCommentSidebar(0);
syncCommentProjection();
}
log("updateLayoutAndStyles: Update complete.");
}
// --- GM Menu Commands ---
function updateMenuCommands() {
if (typeof GM_unregisterMenuCommand !== 'function' || typeof GM_registerMenuCommand !== 'function') return;
const autoWidescreenEnabledGM = getFeatureToggle(config.featureTogglesKeys.enableWideScreen);
const sidebarFeatureEnabledGM = getFeatureToggle(config.featureTogglesKeys.enableSidebar);
const onTargetPage = isTargetPage(currentUrl);
const { isReplyPage } = pageSpecificModeChecks();
const baseStatus = (enabled) => enabled ? '✅ 开启' : '❌ 关闭';
let autoWideText = `自动宽屏模式 (${baseStatus(autoWidescreenEnabledGM)})`;
if (!onTargetPage) autoWideText = "自动宽屏模式 (当前页不支持)";
else if (isReplyPage) autoWideText = `自动宽屏模式 (${baseStatus(autoWidescreenEnabledGM)} - 回复页禁用)`;
let sidebarText = `侧边栏增强 (${baseStatus(sidebarFeatureEnabledGM)} - 宽屏/网页全屏时生效)`;
if (!onTargetPage) sidebarText = "侧边栏增强 (当前页不支持)";
else if (isReplyPage) sidebarText = `侧边栏增强 (${baseStatus(sidebarFeatureEnabledGM)} - 回复页禁用)`;
if (lastMenuTexts.autoWide !== autoWideText) {
if (autoWideMenuId) try { GM_unregisterMenuCommand(autoWideMenuId); } catch (e) {}
autoWideMenuId = GM_registerMenuCommand(autoWideText, toggleWideScreenFeature);
lastMenuTexts.autoWide = autoWideText;
}
if (lastMenuTexts.sidebar !== sidebarText) {
if (sidebarMenuId) try { GM_unregisterMenuCommand(sidebarMenuId); } catch (e) {}
sidebarMenuId = GM_registerMenuCommand(sidebarText, toggleSidebarFeature);
lastMenuTexts.sidebar = sidebarText;
}
if (lastMenuTexts.settings !== 'open') {
if (openSettingsPanelMenuId) try { GM_unregisterMenuCommand(openSettingsPanelMenuId); } catch (e) {}
openSettingsPanelMenuId = GM_registerMenuCommand("⚙️ 打开设置面板", toggleSettingsPanel);
lastMenuTexts.settings = 'open';
}
log("GM menu commands updated.");
}
async function toggleWideScreenFeature() {
const intendedState = !getFeatureToggle(config.featureTogglesKeys.enableWideScreen);
const { isReplyPage } = pageSpecificModeChecks();
if (!isTargetPage(currentUrl) && intendedState) { alert("此页面不支持自动宽屏功能。"); return; }
if (isReplyPage && intendedState) alert("自动宽屏功能不适用于评论回复(#reply)页面。\n设置已保存,但在此页面无效。");
setFeatureToggle(config.featureTogglesKeys.enableWideScreen, intendedState);
userManuallyExitedWide = !intendedState;
updateMenuCommands();
if (isTargetPage(currentUrl)) {
if (intendedState && !isReplyPage) await ensureWideMode();
else if (elements.playerContainer) {
if (elements.playerContainer.getAttribute('data-screen') === PLAYER_STATES.WIDE && !intendedState && !isReplyPage) {
if(elements.wideBtn) elements.wideBtn.click();
} else await handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'));
}
}
}
async function toggleSidebarFeature() {
const intendedState = !getFeatureToggle(config.featureTogglesKeys.enableSidebar);
const { isReplyPage } = pageSpecificModeChecks();
if (!isTargetPage(currentUrl) && intendedState) { alert("侧边栏增强功能仅在视频/列表页面可用。"); return; }
if (isReplyPage && intendedState) alert("侧边栏增强功能不适用于评论回复(#reply)页面。\n设置已保存,但在此页面无效。");
setFeatureToggle(config.featureTogglesKeys.enableSidebar, intendedState);
updateMenuCommands();
if (isTargetPage(currentUrl) && elements.playerContainer) {
await handleDataScreenChange(elements.playerContainer.getAttribute('data-screen'));
}
}
// --- Script Initialization and SPA Navigation Handling ---
async function initializeScriptLogic(isReInit = false, fromObserver = false) {
const initSeq = bumpSeq(SEQ.init);
log(`initializeScriptLogic: Start. isReInit = ${isReInit}, fromObserver = ${fromObserver}, seq = ${initSeq}`);
reInitScheduled = false; clearAllTimers();
injectBaseStyles();
loadAllSettings();
getOrCreateCommentContainer();
getOrCreateBottomDrawer();
createSettingsPanel();
const elementsCached = await ensureAllElementsCached();
if (isStaleSeq(SEQ.init, initSeq)) {
log('initializeScriptLogic: superseded by a newer init; abandoning this run.');
return;
}
if (elementsCached) {
log("initializeScriptLogic: All necessary elements cached. Proceeding to setup.");
await setupListeners();
if (isStaleSeq(SEQ.init, initSeq)) return;
if (elements.playerContainer) {
const initialScreen = elements.playerContainer.getAttribute('data-screen');
if (initialScreen) await handleDataScreenChange(initialScreen);
}
loadAndApplyTabState();
const delay = currentSettings.autoWideDelay;
log(`Auto-widescreen check scheduled in ${delay}ms.`);
safeSetTimeout(async () => {
if (isStaleSeq(SEQ.init, initSeq)) return;
if (isTargetPage(window.location.href) && elements.playerContainer?.getAttribute('data-screen') === PLAYER_STATES.NORMAL) {
log("Auto-widescreen delay ended: checking conditions.");
await conditionallyEnterWideMode();
} else {
log("Auto-widescreen delay ended: Conditions not met or not in normal mode.");
}
}, delay);
return;
}
if (isStaleSeq(SEQ.init, initSeq)) return;
warn("initializeScriptLogic: ensureAllElementsCached returned false. Setting up observer.");
if (fromObserver) { error("initializeScriptLogic (from observer): Critical elements still missing after internal wait."); return; }
if (coreElementsObserver) coreElementsObserver.disconnect();
coreElementsObserver = new MutationObserver(async (mutations, observer) => {
log("MutationObserver: Checking for core player elements...");
if (document.querySelector(SELECTORS.player) && (document.querySelector(SELECTORS.playerContainer) || document.querySelector(SELECTORS.playerAlternativeContainer)) ) {
log("initializeScriptLogic (MutationObserver): Core player elements detected.");
observer.disconnect();
coreElementsObserver = null;
await initializeScriptLogic(true, true);
}
});
const observeTarget = document.getElementById(SELECTORS.biliReportWrap.substring(1)) || document.body;
coreElementsObserver.observe(observeTarget, { childList: true, subtree: true });
log(`initializeScriptLogic: Core element observer started on ${observeTarget.id || 'document.body'}.`);
safeSetTimeout(async () => {
if (coreElementsObserver) {
coreElementsObserver.disconnect(); coreElementsObserver = null;
warn("Core element observer timed out. Attempting final initialization.");
await initializeScriptLogic(true, false);
}
}, config.delays.observerMaxWait);
}
function handleUrlChange() {
requestAnimationFrame(async () => {
try {
const newHref = window.location.href;
if (newHref === currentUrl) return;
const oldUrl = currentUrl;
if (getNavigationKey(newHref) === getNavigationKey(oldUrl)) {
currentUrl = newHref;
log(`URL modified in place; skipping re-init. from ${oldUrl} to ${newHref}`);
return;
}
currentUrl = newHref;
log(`URL changed: from ${oldUrl} to ${newHref}`);
userManuallyExitedWide = false;
if (navigationObserver) {
navigationObserver.disconnect();
navigationObserver = null;
}
loadAllSettings();
updateMenuCommands();
const wasTargetPage = isTargetPage(oldUrl);
const isNowTargetPage = isTargetPage(newHref);
if (isNowTargetPage) {
await scheduleReInitialization(oldUrl, newHref);
} else if (wasTargetPage && !isNowTargetPage) {
removeListenersAndObserver({ resetLayout: true });
if (elements.settingsPanel) elements.settingsPanel.style.display = 'none';
}
} catch (e) {
error('handleUrlChange: failed.', e);
}
});
}
async function scheduleReInitialization(previousUrl = currentUrl, nextUrl = window.location.href) {
log(`scheduleReInitialization: reInitScheduled = ${reInitScheduled}`);
if (reInitScheduled) return;
const previousVideoId = getVideoIdFromUrl(previousUrl);
const expectedVideoId = getVideoIdFromUrl(nextUrl) || getCurrentVideoId();
bumpSeq(SEQ.commentProjection);
bumpSeq(SEQ.commentPreactivation);
bumpSeq(SEQ.sidebarContent);
bumpSeq(SEQ.sidebarWarmup);
bumpSeq(SEQ.toolbarDrawer);
scheduledCommentPreactivationVideoId = null;
sidebarTabStateAppliedVideoId = null;
lastCommentActivationNudgeVideoId = null;
deactivateCommentProjection({ keepReference: true });
clearCommentAppReferences();
rememberNonCommentSourceElementsForNavigation(previousUrl, nextUrl);
restoreMovedNonCommentContentToPage();
setNativeNonCommentSourcesHidden(true);
reInitScheduled = true;
removeListenersAndObserver();
clearCommentAppReferences();
scheduleCommentNativePreactivation({ force: true, reason: 'navigation-start' });
const finishReInit = async (reason, observer = null, observerTimeout = null, settleTimer = null) => {
log(`Navigation: finishing re-init. reason=${reason}`);
if (settleTimer) { clearTimeout(settleTimer); activeTimers.delete(settleTimer); }
if (observerTimeout) {
activeTimers.delete(observerTimeout);
clearTimeout(observerTimeout);
}
if (observer) observer.disconnect();
if (navigationObserver) {
navigationObserver.disconnect();
navigationObserver = null;
}
await initializeScriptLogic(true, false);
ensureSidebarShellVisibleDuringTransition();
updateSidebarTabIndicator(currentActiveSidebarTabId);
scheduleCommentNativePreactivation({ force: true, reason: 'navigation-finish' });
const navMountToken = bumpSeq(SEQ.sidebarWarmup);
scheduleFullNonCommentMountAfterNavigation(0, navMountToken);
const navRefreshToken = bumpSeq(SEQ.sidebarContent);
refreshSidebarTabContentFast(currentActiveSidebarTabId, 0, navRefreshToken);
};
const isNewVideoReady = () => {
const currentVideoId = getCurrentVideoId();
const newPlayer = document.querySelector(SELECTORS.player);
if (!newPlayer) return false;
if (expectedVideoId && currentVideoId !== expectedVideoId) return false;
if (previousVideoId && currentVideoId === previousVideoId) {
return true;
}
return true;
};
let settleTimer = null;
const observerTimeout = safeSetTimeout(() => {
warn("Navigation observer timed out. Forcing re-initialization with the latest DOM.");
finishReInit('timeout', navigationObserver, null, settleTimer);
}, 20000);
const scheduleFinishIfReady = (reason, observer) => {
if (!isNewVideoReady()) return;
clearTimeout(settleTimer);
if (settleTimer) activeTimers.delete(settleTimer);
settleTimer = safeSetTimeout(() => {
settleTimer = null;
finishReInit(reason, observer, observerTimeout, settleTimer);
}, 120);
};
const observerTarget = await waitForSpecificElement(SELECTORS.mainContentContainer, {
attempts: config.attempts.contentElementWait,
interval: config.intervals.contentElementWait
}) || document.body;
navigationObserver = new MutationObserver((mutations, observer) => {
const hasRelevantChange = mutations.some(m =>
m.type === 'childList' && (m.addedNodes.length > 0 || m.removedNodes.length > 0)
);
if (hasRelevantChange) scheduleFinishIfReady('dom-mutated', observer);
});
navigationObserver.observe(observerTarget, { childList: true, subtree: true });
safeSetTimeout(() => {
scheduleFinishIfReady('early-url-check', navigationObserver);
}, 60);
safeSetTimeout(() => {
scheduleFinishIfReady('post-url-check', navigationObserver);
}, config.delays.stateChangeProcess);
}
function isTargetPage(url) { return /\/(video|list|bangumi\/play)\//.test(url); }
function isBangumiPlayPage() { return /\/bangumi\/play\//.test(window.location.href); }
async function main() {
log(`Script starting. Version ${GM_info.script.version}. Debug Mode: ${config.debugMode}`);
for (const key in config.featureTogglesKeys) {
if (GM_getValue(config.featureTogglesKeys[key]) === undefined) {
GM_setValue(config.featureTogglesKeys[key], config.defaultFeatureToggles[key]);
}
}
for (const key in config.settingsKeys) {
if (GM_getValue(config.settingsKeys[key]) === undefined) {
GM_setValue(config.settingsKeys[key], config.defaultSettings[key]);
}
}
loadAllSettings();
updateMenuCommands();
window.addEventListener('popstate', handleUrlChange);
if (!window.__biliPlusHistoryPatched) {
window.__biliPlusHistoryPatched = true;
const origPushState = history.pushState;
history.pushState = function(...args) {
const oldHref = window.location.href;
origPushState.apply(this, args);
if (window.location.href !== oldHref) {
handleUrlChange();
}
};
const origReplaceState = history.replaceState;
history.replaceState = function(...args) {
const oldHref = window.location.href;
origReplaceState.apply(this, args);
if (window.location.href !== oldHref) {
handleUrlChange();
}
};
}
if (isTargetPage(currentUrl)) await initializeScriptLogic();
else log("Initial page is not a target page.");
window.addEventListener('pagehide', () => {
removeListenersAndObserver({ resetLayout: true });
if(playerResizeObserver) playerResizeObserver.disconnect();
if(navigationObserver) navigationObserver.disconnect();
});
}
log(`Script parsed. document.readyState: ${document.readyState}`);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', main);
} else {
main();
}
})();