跳到正文

休闲·娱乐

想要装饰你的洛谷吗?试试铍洛谷吧!

Breakon约 198 分钟
原文

这是 2026年10月10日 存档的第 3 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月4日
收录
2026年10月4日
更新
2026年11月21日
篇幅
约 198 分钟

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1
成品展示

洛谷题目列表 洛谷主页

一、这是什么

「铍洛谷」是一个 Tampermonkey 用户脚本,给洛谷全站加上:

  • 自定义背景板:跟随你的洛谷主题,或手动指定一张图
  • 毛玻璃卡片:所有卡片半透明,露出背景图
  • 文字加深:浅色文字自动加深,配合半透明背景更好读
  • 跨标签同步:一个标签改了设置,其他标签秒跟

二、安装

  1. 浏览器装 Tampermonkey 扩展
  2. 打开 Tampermonkey 面板 → 新建脚本
  3. 把整份脚本粘进去 → 保存(Ctrl+S)
  4. 打开任意洛谷页面,F5 刷新,看到控制台打印 [铍洛谷] v5.4.1 已启动。 就说明成功了
脚本

// ==UserScript== // @name 铍洛谷 // @namespace http://tampermonkey.net/ // @version 5.4.1 // @description 洛谷主站(含用户主页)+ 网校 + 有题 + image/paste/ticket 统一背景板 // @author Breakon and DeepSeek // @match https://www.luogu.com.cn/* // @match https://class.luogu.com.cn/* // @match https://ti.luogu.com.cn/* // @grant GM_setValue // @grant GM_getValue // @grant GM_addValueChangeListener // @grant unsafeWindow // @run-at document-idle // ==/UserScript==

(function () { ‘use strict’;

代码
try {
    if (window.top !== window.self) return;
} catch (e) {
    return;
}

const PAGE_WIN = (typeof unsafeWindow !== 'undefined') ? unsafeWindow : window;

/* ============================================================
 * 常量
 * ============================================================ */
const KEY_ENABLED      = 'bg_custom_enabled';
const KEY_COLOR        = 'bg_custom_color';
const KEY_ALPHA        = 'bg_custom_alpha';
const KEY_THEME_BG_URL = 'bg_theme_bg_url';
const KEY_AUTO_BG_URL  = 'bg_auto_bg_url';
const KEY_AUTO_BG_BACK = 'bg_auto_back_color';
const KEY_AUTO_BG_GRAD = 'bg_auto_gradient';

const PANEL_ID          = 'luogu-bg-panel';
const STYLE_ID          = 'luogu-bg-panel-style';
const HITOKOTO_PANEL_ID = 'luogu-hitokoto-panel';
const GLASS_STYLE_ID    = 'luogu-glass-style';

const GLASS_VAR_BG             = '--luogu-glass-bg';
const GLASS_VAR_BG_HD          = '--luogu-glass-bg-hd';
const GLASS_VAR_BORDER         = '--luogu-glass-border';
const GLASS_VAR_SHADOW         = '--luogu-glass-shadow';
const GLASS_VAR_TICKET_DIVIDER = '--luogu-glass-ticket-divider';

const PAINT_MARK         = 'data-bg-painted';
const ORIG_BG_ATTR       = 'data-bg-orig-bg';
const TICKET_TOPBAR_ATTR = 'data-ticket-topbar';
const NAV_SOLID_ATTR     = 'data-nav-solid';
const SHELL_CLEARED_ATTR = 'data-shell-cleared';
const INNER_TRANSPARENT_ATTR = 'data-luogu-inner-transparent';

const FORCE_ID = 'luogu-glass-force';
const FALLBACK_BG_IMAGE = 'https://cdn.luogu.com.cn/upload/image_hosting/e5xgx75m.webp';

const INPUT_SKIP_CLASS = 'luogu-bg-skip';

const GLASS_BORDER   = '1px solid rgba(255, 255, 255, 0.55)';
const GLASS_SHADOW   = `0 8px 32px rgba(31, 38, 135, 0.12),
                        0 2px 8px rgba(0, 0, 0, 0.05),
                        inset 0 1px 0 rgba(255, 255, 255, 0.6)`;
const USER_CARD_BLUR = 'blur(24px) saturate(180%)';
const FEED_HEADER_DARKEN      = 25;
const FEED_HEADER_ALPHA_BOOST = 0.15;

const HOST = location.hostname;
const IS_MAIN_SITE  = HOST === 'www.luogu.com.cn' || HOST === 'www.luogu.org';
const IS_CLASS_SITE = HOST === 'class.luogu.com.cn';
const IS_TI_SITE    = HOST === 'ti.luogu.com.cn';

const GRAY_MARK  = 'data-darkened-gray';
const DARK_GRAY  = 'rgb(60, 60, 70)';

const SKIP_TAGS = new Set([
    'INPUT', 'TEXTAREA', 'BUTTON', 'SELECT',
    'IMG', 'SVG', 'PATH', 'IFRAME', 'VIDEO', 'CANVAS',
    'SCRIPT', 'STYLE', 'LINK', 'META', 'HR', 'BR',
]);
const INLINE_TAGS = new Set([
    'SPAN', 'A', 'B', 'I', 'EM', 'STRONG', 'SMALL',
    'CODE', 'KBD', 'TIME', 'LABEL', 'CITE', 'Q', 'S', 'U',
    'SUB', 'SUP', 'MARK',
]);

const FLOATING_EXCLUDE = [
    '.v-popper__popper', '.v-popper__inner',
    '[class*="popper"]', '[class*="popup"]', '[class*="popover"]',
    '[class*="tooltip"]', '[class*="dropdown"]',
    '.dropdown',
    '[role="tooltip"]', '[role="menu"]',
    '[aria-hidden="true"]',
].join(', ');

const CONTENT_EXCLUDE = [
    '.markdown-body',
    '.lfe-markdown',
    '.lg-article-content',
    '.article-content',
    '.feed-comment',
    '.am-comment-bd',
    '[class*="markdown-body"]',
    '[class*="markdown-content"]',
].join(', ');

const NAV_SELECTOR = [
    '.top-bar',
    'nav.sidebar',
    'nav.sidebar.lside',
    '.sidebar.lside.bar',
    '.user-nav.rside',
    '#app-sidenav',
    '#app-header',
].join(', ');

const SHELL_SELECTOR = [
    '.theme-page',
    '.theme-mid-full',
    '.theme-mid',
    '.main-container',
    '.columba-content-wrap',
    '.main-content',
    '#app',
    '#app-old',
    '.lg-index-content',
    '.lfe-body',
    'main',
].join(', ');

const CSS_OWNED_SELECTOR = [
    '.tag-button',
    '.refined-input.search-text',
    '.list-scroll',
].join(', ');

const CSS_OWNED_SUBTREE = [
    '.refined-input.search-text',
    '.list-scroll',
].join(', ');

const CARD_SELECTOR_RAW = [
    '.l-card', '.lg-article', '.lg-index-stat', '.lg-index-contest',
    '.am-panel', '.n-card', '.training-card', '.category-card',
    '.srqc', '.course-card', '.lesson-card', '.chapter-card',
    '.class-card', '.problemsets', '.problemset-item',
    '.lg-punch',
].join(', ');

const TEXT_DARKEN_SELECTOR = [
    'a', 'span', 'strong', 'em', 'small', 'p', 'i', 'b',
    'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
    'li', 'td', 'th', 'dt', 'dd', 'label', 'time',
    'blockquote', 'figcaption', 'cite', 'q', 'mark',
    'section', 'article', 'header', 'footer', 'aside',
].join(', ');

/* ============================================================
 * 状态
 * ============================================================ */
function readAlpha() {
    let v = parseFloat(GM_getValue(KEY_ALPHA, 0.78));
    if (isNaN(v) || v <= 0.01) v = 0.78;
    return Math.min(1, Math.max(0.05, v));
}
let currentEnabled = !!GM_getValue(KEY_ENABLED, false);
let currentColor   = GM_getValue(KEY_COLOR, '#232329') || '#232329';
let currentAlpha   = readAlpha();

let lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
let themeHostEl = null;

let paintVersion = 0;
let paintedElements = new WeakMap();
let darkenedElements = new WeakSet();

let preferenceFetched = false;
let preferenceFetching = false;
let serverThemeFetched = false;
let serverThemeFetching = false;
let serverThemeAttempted = false;

let luoguThemePollTimer = null;
let lastLuoguThemeImage = '';

let userCardGlassTimer = null;

/* ============================================================
 * 工具
 * ============================================================ */
function hexToRgb(hex) {
    let h = String(hex || '#232329').replace('#', '').trim();
    if (h.length === 3) h = h.split('').map(c => c + c).join('');
    if (h.length !== 6 || /[^0-9a-fA-F]/.test(h)) h = '232329';
    return {
        r: parseInt(h.slice(0, 2), 16) || 0,
        g: parseInt(h.slice(2, 4), 16) || 0,
        b: parseInt(h.slice(4, 6), 16) || 0,
    };
}
function buildBgValue(hex, alpha) {
    const { r, g, b } = hexToRgb(hex);
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
function buildFeedHeaderBg(hex, alpha) {
    const { r, g, b } = hexToRgb(hex);
    const dr = Math.max(0, r - FEED_HEADER_DARKEN);
    const dg = Math.max(0, g - FEED_HEADER_DARKEN);
    const db = Math.max(0, b - FEED_HEADER_DARKEN);
    const a  = Math.min(1, alpha + FEED_HEADER_ALPHA_BOOST);
    return `rgba(${dr}, ${dg}, ${db}, ${a})`;
}
function buildTicketDividerColor(hex) {
    const { r, g, b } = hexToRgb(hex);
    const lum = 0.299 * r + 0.587 * g + 0.114 * b;
    if (lum > 128) return 'rgba(0, 0, 0, 0.55)';
    return 'rgba(255, 255, 255, 0.55)';
}
function parseRgb(str) {
    if (!str) return null;
    const m = str.match(/rgba?\(\s*(\d+)\s*[,\s]\s*(\d+)\s*[,\s]\s*(\d+)/);
    if (!m) return null;
    return { r: +m[1], g: +m[2], b: +m[3] };
}
function parseUrlFromCssValue(raw) {
    if (!raw) return null;
    const s = String(raw).trim();
    if (!s || s === 'none' || s === 'initial' || s === 'unset' || s === 'inherit') return null;
    const m = s.match(/url\(\s*["']?([^"')]+)["']?\s*\)/);
    return m && m[1] ? m[1].trim() : null;
}
function readVarFrom(el, name) {
    if (!el) return '';
    try { return getComputedStyle(el).getPropertyValue(name).trim(); } catch (e) { return ''; }
}
function readAllThemeVarsFrom(el) {
    if (!el) return { image: '', back: '', gradient: '' };
    return {
        image:    readVarFrom(el, '--theme-body-image'),
        back:     readVarFrom(el, '--theme-body-back'),
        gradient: readVarFrom(el, '--theme-body-color'),
    };
}
function isVarsNonEmpty(vars) {
    const imgOk = !!parseUrlFromCssValue(vars.image);
    const backOk = vars.back && vars.back !== 'none' && vars.back !== '';
    const gradOk = vars.gradient && vars.gradient !== 'none' && vars.gradient !== '';
    return imgOk || backOk || gradOk;
}

function findUrlInObject(obj, depth) {
    depth = depth || 0;
    if (depth > 6 || !obj) return null;
    if (typeof obj === 'string') {
        if (/^https?:\/\/.*\.(webp|jpg|jpeg|png|gif|svg)(\?|$)/i.test(obj.trim())) {
            return obj.trim();
        }
        const m = obj.match(/url\(\s*["']?(https?:\/\/[^"')]+)["']?\s*\)/);
        if (m && m[1]) return m[1].trim();
        return null;
    }
    if (Array.isArray(obj)) {
        for (const item of obj) {
            const u = findUrlInObject(item, depth + 1);
            if (u) return u;
        }
        return null;
    }
    if (typeof obj === 'object') {
        for (const k of Object.keys(obj)) {
            if (/image|background|bg/i.test(k)) {
                const u = findUrlInObject(obj[k], depth + 1);
                if (u) return u;
            }
        }
        for (const k of Object.keys(obj)) {
            if (/image|background|bg/i.test(k)) continue;
            if (/avatar|icon|logo/i.test(k)) continue;
            const u = findUrlInObject(obj[k], depth + 1);
            if (u) return u;
        }
    }
    return null;
}

function extractLuoguThemeFromDoc(doc) {
    try {
        const el = doc.getElementById('luogu-theme');
        if (!el) return null;
        return JSON.parse(el.textContent);
    } catch (e) {
        return null;
    }
}

function extractLuoguThemeFromHtml(html) {
    if (!html || typeof html !== 'string') return null;
    const m = html.match(/<script[^>]*id=["']luogu-theme["'][^>]*>([\s\S]*?)<\/script>/);
    if (!m || !m[1]) return null;
    try {
        return JSON.parse(m[1]);
    } catch (e) {
        return null;
    }
}

function parseLBody(lBody) {
    if (!lBody) return null;
    const imageUrl = lBody.image;
    if (!imageUrl || !/^https?:\/\//i.test(imageUrl)) return null;
    const backColor = (typeof lBody.back === 'string' && lBody.back) ? lBody.back : null;
    const colorArr = Array.isArray(lBody.color) ? lBody.color : null;
    const grad = (colorArr && colorArr.length >= 2)
        ? `linear-gradient(167deg, ${colorArr.join(', ')})`
        : null;
    return { imageUrl, backColor, colorGradient: grad };
}

/* ============================================================
 * 主题变量提取
 * ============================================================ */
function getManualBgUrl() {
    const u = (GM_getValue(KEY_THEME_BG_URL, '') || '').trim();
    return u || null;
}
function getAutoBgUrl() {
    const u = (GM_getValue(KEY_AUTO_BG_URL, '') || '').trim();
    return u || null;
}

function readThemeVarsFromPage() {
    const candidates = [];
    if (themeHostEl && document.contains(themeHostEl)) candidates.push(themeHostEl);

    const selectors = [
        '.theme-page', '.theme-mid-full', '.theme-mid',
        '.columba-content-wrap', '.main-container',
        '#app', '#app-old', 'main', 'body', 'html',
    ];
    for (const sel of selectors) {
        const el = sel === 'html' ? document.documentElement : document.querySelector(sel);
        if (el && !candidates.includes(el)) candidates.push(el);
    }

    for (const el of candidates) {
        if (!el) continue;
        const vars = readAllThemeVarsFrom(el);
        const u = parseUrlFromCssValue(vars.image);
        if (u) {
            themeHostEl = el;
            return {
                imageUrl: u,
                backColor: (vars.back && vars.back !== 'none') ? vars.back : null,
                colorGradient: (vars.gradient && vars.gradient !== 'none') ? vars.gradient : null,
            };
        }
    }

    const lsUrl = tryReadThemeFromLocalStorage();
    if (lsUrl) {
        return { imageUrl: lsUrl, backColor: null, colorGradient: null };
    }

    return { imageUrl: null, backColor: null, colorGradient: null };
}

function tryReadThemeFromLocalStorage() {
    const fixedKeys = [
        'luogu-theme', 'LFE_THEME', 'lfe-theme',
        'columba-theme', 'lentille-theme',
        'theme', 'theme-data', 'themeData',
        'luogu-theme-store', 'theme-store',
    ];
    for (const key of fixedKeys) {
        const url = tryExtractUrlFromStorage(key);
        if (url) return url;
    }
    try {
        const n = localStorage.length;
        for (let i = 0; i < n; i++) {
            const key = localStorage.key(i);
            if (!key) continue;
            if (!/theme|columba|lentille|background|wallpaper/i.test(key)) continue;
            if (fixedKeys.includes(key)) continue;
            const url = tryExtractUrlFromStorage(key);
            if (url) return url;
        }
    } catch (e) {}
    return null;
}

function tryExtractUrlFromStorage(key) {
    let raw;
    try { raw = localStorage.getItem(key); } catch (e) { return null; }
    if (!raw) return null;
    const trimmed = raw.trim();
    if (!trimmed) return null;

    if (/^https?:\/\//i.test(trimmed) &&
        /\.(webp|jpg|jpeg|png|gif)(\?|$)/i.test(trimmed)) {
        return trimmed;
    }
    const m = trimmed.match(/--theme-body-image\s*:\s*url\(\s*["']?([^"')]+)["']?\s*\)/);
    if (m && m[1]) return m[1].trim();
    const m2 = trimmed.match(/url\(\s*["']?(https?:\/\/[^"')]+)["']?\s*\)/);
    if (m2 && m2[1]) return m2[1].trim();
    try {
        const obj = JSON.parse(trimmed);
        const u = findUrlInObject(obj);
        if (u) return u;
    } catch (e) {}
    return null;
}

async function fetchThemeFromPreference() {
    if (preferenceFetched || preferenceFetching) return;
    if (!IS_MAIN_SITE) return;
    preferenceFetching = true;
    try {
        const resp = await fetch('/user/setting/preference', {
            credentials: 'same-origin',
            headers: { 'Accept': 'text/html' },
        });
        preferenceFetched = true;
        if (!resp.ok) return;
        const html = await resp.text();
        const themeData = extractLuoguThemeFromHtml(html);
        const parsed = themeData ? parseLBody(themeData.lBody) : null;
        if (parsed && parsed.imageUrl !== GM_getValue(KEY_AUTO_BG_URL, '')) {
            GM_setValue(KEY_AUTO_BG_URL, parsed.imageUrl);
            if (parsed.backColor) GM_setValue(KEY_AUTO_BG_BACK, parsed.backColor);
            if (parsed.colorGradient) GM_setValue(KEY_AUTO_BG_GRAD, parsed.colorGradient);
            applyCustomBg();
        }
    } catch (e) {
    } finally {
        preferenceFetching = false;
    }
}

async function fetchThemeFromApi(force) {
    if (serverThemeFetching) return null;
    if (serverThemeFetched && !force) return null;
    if (serverThemeAttempted && !force) return null;
    if (!IS_MAIN_SITE) return null;

    serverThemeFetching = true;
    serverThemeAttempted = true;

    try {
        let themeData = extractLuoguThemeFromDoc(document);
        let source = 'current-doc';

        if (!themeData) {
            const resp = await fetch('/theme', {
                credentials: 'same-origin',
                headers: { 'Accept': 'text/html' },
            });
            if (!resp.ok) return null;
            const html = await resp.text();
            themeData = extractLuoguThemeFromHtml(html);
            source = 'fetched-html';
        }

        if (!themeData) return null;

        const parsed = parseLBody(themeData.lBody);
        if (!parsed) return null;

        if (parsed.backColor) GM_setValue(KEY_AUTO_BG_BACK, parsed.backColor);
        if (parsed.colorGradient) GM_setValue(KEY_AUTO_BG_GRAD, parsed.colorGradient);

        serverThemeFetched = true;
        if (PAGE_WIN.__LUOGU_BG_VERBOSE) {
            console.log('[铍洛谷] 从', source, '提取到主题背景:', parsed.imageUrl);
        }
        return parsed.imageUrl;
    } catch (e) {
        return null;
    } finally {
        serverThemeFetching = false;
    }
}

function getThemeBackgroundInfo() {
    const manual = getManualBgUrl();
    if (manual) {
        return { imageUrl: manual, backColor: null, colorGradient: null, source: 'manual' };
    }

    const themeData = extractLuoguThemeFromDoc(document);
    const parsed = themeData ? parseLBody(themeData.lBody) : null;
    if (parsed) {
        const old = GM_getValue(KEY_AUTO_BG_URL, '');
        if (old !== parsed.imageUrl) {
            GM_setValue(KEY_AUTO_BG_URL, parsed.imageUrl);
        }
        if (parsed.backColor) GM_setValue(KEY_AUTO_BG_BACK, parsed.backColor);
        if (parsed.colorGradient) GM_setValue(KEY_AUTO_BG_GRAD, parsed.colorGradient);
        return {
            imageUrl: parsed.imageUrl,
            backColor: parsed.backColor,
            colorGradient: parsed.colorGradient,
            source: 'luogu-theme',
        };
    }

    const live = readThemeVarsFromPage();
    if (live.imageUrl) {
        const old = GM_getValue(KEY_AUTO_BG_URL, '');
        if (old !== live.imageUrl) {
            GM_setValue(KEY_AUTO_BG_URL, live.imageUrl);
        }
        return { ...live, source: 'live' };
    }

    const auto = getAutoBgUrl();
    if (auto) {
        const autoBack = GM_getValue(KEY_AUTO_BG_BACK, '');
        const autoGrad = GM_getValue(KEY_AUTO_BG_GRAD, '');
        return {
            imageUrl: auto,
            backColor: autoBack || null,
            colorGradient: autoGrad || null,
            source: 'auto-cache',
        };
    }
    return { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
}

/* ============================================================
 * 路径判断
 * ============================================================ */
function isSettingPage() {
    return IS_MAIN_SITE && location.href.includes('/user/setting/preference');
}
function isImagePage() {
    return IS_MAIN_SITE && /^\/image(\/|$)/.test(location.pathname);
}
function isPastePage() {
    return IS_MAIN_SITE && /^\/paste(\/|$)/.test(location.pathname);
}
function isTicketPage() {
    return IS_MAIN_SITE && /^\/ticket(\/|$)/.test(location.pathname);
}
function isArticleDetailPage() {
    if (!IS_MAIN_SITE) return false;
    const p = location.pathname;
    return /^\/article\/[^\/]+\/?$/.test(p) && !/^\/article\/(mine|_new)\/?$/.test(p);
}
function isHomePage() {
    if (!IS_MAIN_SITE) return false;
    const p = location.pathname;
    return p === '/' || p === '' || p === '/index';
}
function isGlassApplyPage() {
    return IS_MAIN_SITE && (
        /^\/user\/setting(\/|$)/.test(location.pathname) ||
        /^\/theme(\/|$)/.test(location.pathname) ||
        /^\/paste(\/|$)/.test(location.pathname) ||
        /^\/article(\/|$)/.test(location.pathname) ||
        /^\/training(\/|$)/.test(location.pathname) ||
        /^\/problem(\/|$)/.test(location.pathname) ||
        /^\/benben(\/|$)/.test(location.pathname) ||
        /^\/chat(\/|$)/.test(location.pathname) ||
        /^\/contest(\/|$)/.test(location.pathname)
    );
}

/* ============================================================
 * CSS 变量同步
 * ============================================================ */
function syncGlassVars() {
    const root = document.documentElement;
    root.style.setProperty(GLASS_VAR_BG, buildBgValue(currentColor, currentAlpha));
    root.style.setProperty(GLASS_VAR_BG_HD, buildFeedHeaderBg(currentColor, currentAlpha));
    root.style.setProperty(GLASS_VAR_BORDER, GLASS_BORDER);
    root.style.setProperty(GLASS_VAR_SHADOW, GLASS_SHADOW);
    root.style.setProperty(GLASS_VAR_TICKET_DIVIDER, buildTicketDividerColor(currentColor));
}
function clearGlassVars() {
    const root = document.documentElement;
    root.style.removeProperty(GLASS_VAR_BG);
    root.style.removeProperty(GLASS_VAR_BG_HD);
    root.style.removeProperty(GLASS_VAR_BORDER);
    root.style.removeProperty(GLASS_VAR_SHADOW);
    root.style.removeProperty(GLASS_VAR_TICKET_DIVIDER);
}

/* ============================================================
 * 内联画背景
 * ============================================================ */
function paintBackgroundInline() {
    if (!currentEnabled) return;
    const body = document.body;
    if (!body) return;
    const root = document.documentElement;

    const info = lastThemeInfo;
    const imageUrl = info.imageUrl || FALLBACK_BG_IMAGE;

    if (info.backColor && info.backColor !== 'transparent') {
        root.style.setProperty('background-color', info.backColor, 'important');
    } else {
        root.style.setProperty('background-color', 'transparent', 'important');
    }

    const layers = [];
    if (imageUrl) layers.push(`url("${imageUrl}")`);
    if (info.colorGradient && info.colorGradient !== 'none') {
        layers.push(info.colorGradient);
    }
    const n = layers.length;
    if (n > 0) {
        const rep = Array(n).fill('cover').join(', ');
        const pos = Array(n).fill('center').join(', ');
        const rpt = Array(n).fill('no-repeat').join(', ');
        const att = Array(n).fill('fixed').join(', ');
        root.style.setProperty('background-image', layers.join(', '), 'important');
        root.style.setProperty('background-size', rep, 'important');
        root.style.setProperty('background-position', pos, 'important');
        root.style.setProperty('background-repeat', rpt, 'important');
        root.style.setProperty('background-attachment', att, 'important');
    } else {
        root.style.setProperty('background-image', 'none', 'important');
        root.style.removeProperty('background-attachment');
    }

    body.style.setProperty('background', 'transparent', 'important');

    const shells = document.querySelectorAll(SHELL_SELECTOR);
    shells.forEach(el => {
        if (el.matches && el.matches(NAV_SELECTOR)) return;
        el.style.setProperty('background', 'transparent', 'important');
        el.style.setProperty('background-color', 'transparent', 'important');
        el.style.setProperty('background-image', 'none', 'important');
        el.setAttribute(SHELL_CLEARED_ATTR, '1');
    });
}

function clearPaintedBackground() {
    const root = document.documentElement;
    const body = document.body;
    ['background-color', 'background-image', 'background-size',
     'background-position', 'background-repeat', 'background-attachment']
        .forEach(p => root.style.removeProperty(p));
    if (body) body.style.removeProperty('background');

    document.querySelectorAll(`[${SHELL_CLEARED_ATTR}]`).forEach(el => {
        el.style.removeProperty('background');
        el.style.removeProperty('background-color');
        el.style.removeProperty('background-image');
        el.removeAttribute(SHELL_CLEARED_ATTR);
    });
}

/* ============================================================
 * 输入框玻璃化
 * ============================================================ */
function buildInputGlassRules() {
    const inputSel = [
        'input[type="text"]', 'input[type="search"]', 'input[type="email"]',
        'input[type="password"]', 'input[type="url"]', 'input[type="number"]',
        'input[type="tel"]', 'input:not([type])', 'textarea',
        '.am-form-field', '.l-input', '.lfe-input',
    ].join(', ');

    return `
        main :is(${inputSel}):not(.${INPUT_SKIP_CLASS}):not(#${FORCE_ID}):not([type="hidden"]):not([type="color"]):not([type="range"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]):not([type="submit"]):not([type="button"]):not([type="reset"]) {
            background-color: rgba(255, 255, 255, 0.45) !important;
            background-image: none !important;
            border: 1px solid rgba(255, 255, 255, 0.65) !important;
            border-radius: 8px !important;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.06) !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            transition: background-color 0.2s ease,
                        border-color 0.2s ease,
                        box-shadow 0.2s ease;
        }
        main :is(${inputSel}):not(.${INPUT_SKIP_CLASS}):not(#${FORCE_ID}):not([type="hidden"]):not([type="color"]):not([type="range"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]):not([type="submit"]):not([type="button"]):not([type="reset"]):hover {
            background-color: rgba(255, 255, 255, 0.55) !important;
            border-color: rgba(255, 255, 255, 0.8) !important;
        }
        main :is(${inputSel}):not(.${INPUT_SKIP_CLASS}):not(#${FORCE_ID}):not([type="hidden"]):not([type="color"]):not([type="range"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]):not([type="submit"]):not([type="button"]):not([type="reset"]):focus {
            background-color: rgba(255, 255, 255, 0.75) !important;
            border-color: rgba(52, 152, 219, 0.8) !important;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.18),
                        inset 0 1px 2px rgba(0, 0, 0, 0.06) !important;
            outline: none !important;
        }
        main .am-input-group:not(#${FORCE_ID}),
        main .am-input-group:not(#${FORCE_ID}) .am-input-group-label,
        main .am-input-group:not(#${FORCE_ID}) .am-input-group-btn,
        main .image-input:not(#${FORCE_ID}) {
            background-color: transparent !important;
            background-image: none !important;
        }
    `;
}

/* ============================================================
 * 题目列表专属元素 + 横向滚动条玻璃化 + 搜索框文字加深
 * ============================================================ */
function buildProblemListGlassRules() {
    return `
        .tag-button:not(#${FORCE_ID}) {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            transition: background-color 0.2s ease,
                        border-color 0.2s ease,
                        box-shadow 0.2s ease;
        }
        .tag-button:not(#${FORCE_ID}):hover {
            background-color: rgba(255, 255, 255, 0.6) !important;
            border-color: rgba(255, 255, 255, 0.85) !important;
        }
        .refined-input.search-text:not(#${FORCE_ID}) {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            border-radius: 0 !important;
        }
        .refined-input.search-text:not(#${FORCE_ID}) input,
        .refined-input.search-text:not(#${FORCE_ID}) input:not(#${FORCE_ID}),
        .refined-input.search-text:not(#${FORCE_ID}) input[type="text"],
        .refined-input.search-text:not(#${FORCE_ID}) input.search-text,
        .refined-input.search-text:not(#${FORCE_ID}) input:hover,
        .refined-input.search-text:not(#${FORCE_ID}) input:focus {
            background: transparent !important;
            background-color: transparent !important;
            background-image: none !important;
            border: none !important;
            border-radius: 0 !important;
            box-shadow: none !important;
            outline: none !important;
        }
        .refined-input.search-text:not(#${FORCE_ID}) > *,
        .refined-input.search-text:not(#${FORCE_ID}) .east,
        .refined-input.search-text:not(#${FORCE_ID}) .east *,
        .refined-input.search-text:not(#${FORCE_ID}) .search-icon {
            background: transparent !important;
            background-color: transparent !important;
            background-image: none !important;
            box-shadow: none !important;
        }
        .refined-input.search-text:not(#${FORCE_ID}) .search-icon {
            color: #2c3e50 !important;
        }
        section .search-option .lfe-caption,
        section .search-option .lfe-caption label,
        section .search-option .lfe-caption span,
        section .search-option .lfe-caption label svg {
            color: #2c3e50 !important;
        }
        section .search-option .lfe-caption input[type="checkbox"] {
            color: inherit;
        }

        .refined-input.text:not(#${FORCE_ID}):not(.search-text) *,
        .refined-input.text:not(#${FORCE_ID}):not(.search-text)::before,
        .refined-input.text:not(#${FORCE_ID}):not(.search-text)::after,
        .refined-input.text:not(#${FORCE_ID}):not(.search-text) > *::before,
        .refined-input.text:not(#${FORCE_ID}):not(.search-text) > *::after {
            background-color: transparent !important;
            background-image: none !important;
            border-color: transparent !important;
            box-shadow: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
        .refined-input.text:not(#${FORCE_ID}):not(.search-text) input,
        .refined-input.text:not(#${FORCE_ID}):not(.search-text) input:hover,
        .refined-input.text:not(#${FORCE_ID}):not(.search-text) input:focus {
            background-color: transparent !important;
            background-image: none !important;
            border: none !important;
            border-radius: 0 !important;
            box-shadow: none !important;
            outline: none !important;
        }
        .refined-input.text:not(#${FORCE_ID}):not(.search-text) .search-icon {
            color: #2c3e50 !important;
        }

        .solution-filter.lfe-caption,
        .solution-filter.lfe-caption label,
        .solution-filter.lfe-caption span,
        .solution-filter.lfe-caption label svg {
            color: #2c3e50 !important;
        }
        .solution-filter.lfe-caption input[type="checkbox"] {
            color: inherit;
        }

        .list-scroll:not(#${FORCE_ID}),
        .list-scroll.overflow:not(#${FORCE_ID}) {
            scrollbar-width: thin;
            scrollbar-color: rgba(255, 255, 255, 0.65) rgba(255, 255, 255, 0.2);
        }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar {
            width: 10px; height: 10px; background: transparent;
        }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar:horizontal { height: 10px; }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar:vertical { width: 10px; }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.18) !important;
            border-radius: 5px;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.55) !important;
            background-image: linear-gradient(180deg, rgba(255,255,255,0.75), rgba(255,255,255,0.4)) !important;
            border: 1px solid rgba(255, 255, 255, 0.7) !important;
            border-radius: 5px;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.8), 0 1px 3px rgba(31,38,135,0.08);
        }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.75) !important;
        }
        .list-scroll:not(#${FORCE_ID})::-webkit-scrollbar-corner { background: transparent; }
        .list-scroll:not(#${FORCE_ID}) .list-wrap:not(#${FORCE_ID}),
        .list-scroll:not(#${FORCE_ID}) .header-wrap:not(#${FORCE_ID}),
        .list-scroll:not(#${FORCE_ID}) .row-wrap:not(#${FORCE_ID}),
        .list-scroll:not(#${FORCE_ID}) .row:not(#${FORCE_ID}) {
            background-color: transparent !important;
            background-image: none !important;
        }
    `;
}

/* ============================================================
 * 用户名悬停卡片 —— CSS 层面兜底(JS 内联是主方案)
 * ============================================================ */
function buildUserCardGlassRules() {
    return `
        body .l-card.float-card:not(#${FORCE_ID}),
        body .dropdown.shown .l-card:not(#${FORCE_ID}),
        body .dropdown.shown > .l-card.float-card:not(#${FORCE_ID}),
        body .dropdown .l-card.float-card:not(#${FORCE_ID}) {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
            border: 1px solid rgba(255, 255, 255, 0.55) !important;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.2),
                        0 2px 8px rgba(0, 0, 0, 0.08),
                        inset 0 1px 0 rgba(255, 255, 255, 0.6) !important;
            backdrop-filter: ${USER_CARD_BLUR} !important;
            -webkit-backdrop-filter: ${USER_CARD_BLUR} !important;
            border-radius: 12px !important;
        }

        body .l-card.float-card:not(#${FORCE_ID}) .user-info,
        body .l-card.float-card:not(#${FORCE_ID}) .user-action {
            background-color: transparent !important;
            background-image: none !important;
        }
    `;
}

/* ============================================================
 * 玻璃 CSS
 * ============================================================ */
function injectGlassCSS() {
    let styleEl = document.getElementById(GLASS_STYLE_ID);
    if (!styleEl) {
        styleEl = document.createElement('style');
        styleEl.id = GLASS_STYLE_ID;
        document.head.appendChild(styleEl);
    }
    if (!currentEnabled) {
        if (styleEl.textContent !== '') styleEl.textContent = '';
        return;
    }

    const imageRules = isImagePage() ? `
        .image-card, .image-item,
        [class*="image-card"], [class*="image-item"] {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
    ` : '';

    const pasteRules = isPastePage() ? `
        .code-block, .paste-code,
        .am-pre-scrollable, .markdown-body pre,
        [class*="paste-code"], [class*="code-block"] {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            border-radius: 8px !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
    ` : '';

    const ticketRules = isTicketPage() ? `
        .ticket-card {
            background-color: transparent !important;
            background-image: none !important;
            border-color: transparent !important;
            box-shadow: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
        .ticket-card > *,
        .list-wrap, .list-wrap > *,
        .row-wrap, .row-wrap > *,
        .wrapper, .wrapper > *,
        .left-status, .left-status > * {
            background-color: transparent !important;
            background-image: none !important;
            box-shadow: none !important;
        }
        .list-wrap:not(#${FORCE_ID}) > .row-wrap:not(#${FORCE_ID}):not(:first-child),
        .list-wrap:not(#${FORCE_ID}) > .row:not(#${FORCE_ID}):not(:first-child) {
            border-top: 1px solid var(${GLASS_VAR_TICKET_DIVIDER}, rgba(128, 128, 128, 0.6)) !important;
            margin-top: 16px !important;
            padding-top: 16px !important;
        }
        .list-wrap:not(#${FORCE_ID}) > .row:not(#${FORCE_ID}) {
            border-bottom: none !important;
        }
    ` : '';

    const classSiteRules = IS_CLASS_SITE ? `
        .fix nav.hidden, .fix .hidden { display: none !important; }
    ` : '';

    const tiRules = IS_TI_SITE ? `
        #app-header, #app-body, #app-footer,
        .width-wrap, .full-container {
            background-color: transparent !important;
            background-image: none !important;
            box-shadow: none !important;
            border-color: transparent !important;
        }
        .bg-wrap:not(#${FORCE_ID}),
        .bg-wrap:not(#${FORCE_ID}) .bg {
            background: transparent !important;
            background-color: transparent !important;
            background-image: none !important;
            border: none !important;
            box-shadow: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
        .problemsets.card, .problemsets {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            border-radius: 12px !important;
        }
        .problemsets .problemset-item,
        .problemsets .row,
        .problemsets .problemset-item *,
        .problemsets .row * {
            background-color: transparent !important;
            background-image: none !important;
            box-shadow: none !important;
        }
    ` : '';

    const navSolidRules = `
        .top-bar:not(#${FORCE_ID}),
        nav.sidebar:not(#${FORCE_ID}),
        nav.sidebar.lside:not(#${FORCE_ID}),
        .sidebar.lside.bar:not(#${FORCE_ID}),
        .user-nav.rside:not(#${FORCE_ID}),
        #app-sidenav:not(#${FORCE_ID}),
        #app-header:not(#${FORCE_ID}) {
            background-color: var(--theme-navi-back, #1f1f28) !important;
            background-image: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
    `;

    const pseudoMaskRules = `
        .theme-page:not(#${FORCE_ID})::before,
        .theme-page:not(#${FORCE_ID})::after,
        .theme-mid-full:not(#${FORCE_ID})::before,
        .theme-mid-full:not(#${FORCE_ID})::after,
        .theme-mid:not(#${FORCE_ID})::before,
        .theme-mid:not(#${FORCE_ID})::after,
        #app:not(#${FORCE_ID})::before,
        #app:not(#${FORCE_ID})::after,
        #app-old:not(#${FORCE_ID})::before,
        #app-old:not(#${FORCE_ID})::after,
        body:not(#${FORCE_ID})::before,
        body:not(#${FORCE_ID})::after {
            background: transparent !important;
            background-color: transparent !important;
            background-image: none !important;
            box-shadow: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
    `;

    const helperTextRules = `
        .lg-small:not(#${FORCE_ID}):not([class*="lg-fg-"]):not([class*="lcolor--"]) {
            color: rgb(60, 60, 70) !important;
        }
    `;

    const inputGlassRules = buildInputGlassRules();
    const problemListGlassRules = buildProblemListGlassRules();
    const userCardGlassRules = buildUserCardGlassRules();

    const content = `
        ${navSolidRules}
        ${pseudoMaskRules}
        ${helperTextRules}

        .l-card, .lg-article, .lg-index-stat, .lg-index-contest,
        .am-panel, .n-card, .training-card, .category-card,
        .srqc, .course-card, .lesson-card, .chapter-card,
        .class-card, .problemsets, .problemset-item {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
        }

        .lg-punch {
            background-color: transparent !important;
            background-image: none !important;
        }

        .l-card > div:not(.user-header-top),
        .l-card > section, .l-card > header, .l-card > footer,
        .l-card > ul, .l-card > li,
        .l-card .list-scroll, .l-card .list-wrap, .l-card .header-wrap,
        .l-card .header, .l-card .row-wrap, .l-card .row, .l-card .block,
        .l-card .filter-section, .l-card .search-row, .l-card .combo-wrapper,
        .l-card .toolbar, .l-card .result,
        .lg-article > div, .lg-article > section,
        .n-card > .n-card-header, .n-card > .n-card__content, .n-card > .n-card__footer,
        .am-panel > .am-panel-hd, .am-panel > .am-panel-bd, .am-panel > .am-panel-ft {
            background-color: transparent !important;
            background-image: none !important;
        }

        footer, .footer, [class*="footer"] {
            background-color: transparent !important;
            background-image: none !important;
            border: none !important;
            box-shadow: none !important;
        }

        .am-comment-main {
            background-color: var(${GLASS_VAR_BG}) !important;
            background-image: none !important;
        }
        .am-comment-hd {
            background-color: var(${GLASS_VAR_BG_HD}) !important;
            background-image: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            border-bottom: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            border-radius: 8px 8px 0 0 !important;
        }
        .am-comment-bd, .am-comment-meta {
            background-color: transparent !important;
            background-image: none !important;
        }
        li.feed-li {
            background-color: transparent !important;
            background-image: none !important;
        }

        .bottom-wrap.float {
            background: var(${GLASS_VAR_BG}) !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            border-radius: 12px !important;
            padding: 6px 10px !important;
        }
        .bottom-wrap.float .btn-checkbox {
            background: transparent !important;
            background-color: transparent !important;
            background-image: none !important;
            border-color: transparent !important;
            box-shadow: none !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
        }
        .bottom-wrap.float .page-bar button {
            background: var(${GLASS_VAR_BG}) !important;
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            border: var(${GLASS_VAR_BORDER}) !important;
            box-shadow: var(${GLASS_VAR_SHADOW}) !important;
            border-radius: 8px !important;
        }
        .bottom-wrap.float .toolbar {
            background: transparent !important;
        }

        ${imageRules}
        ${pasteRules}
        ${ticketRules}
        ${classSiteRules}
        ${tiRules}

        ${inputGlassRules}
        ${problemListGlassRules}
        ${userCardGlassRules}

        .user-header-top:not(#${FORCE_ID}) {
            background-color: transparent !important;
            box-shadow: none !important;
            border: none !important;
        }
    `;

    if (styleEl.textContent !== content) styleEl.textContent = content;
}

/* ============================================================
 * 导航栏不透明兜底
 * ============================================================ */
function solidifyNavigationBars() {
    if (!currentEnabled) return;
    const els = document.querySelectorAll(NAV_SELECTOR);
    els.forEach(el => {
        if (el.matches && el.matches(SHELL_SELECTOR)) {
            if (el.hasAttribute(NAV_SOLID_ATTR)) {
                el.removeAttribute(NAV_SOLID_ATTR);
                el.style.removeProperty('background-color');
                el.style.removeProperty('background-image');
                el.style.removeProperty('backdrop-filter');
                el.style.removeProperty('-webkit-backdrop-filter');
            }
            return;
        }
        const cs = getComputedStyle(el);
        const bg = cs.backgroundColor;
        const rgb = parseRgb(bg);
        if (!rgb) return;
        const isOpaque = !/rgba\(/.test(bg) || /rgba\([^)]*,\s*1(\.0*)?\s*\)/.test(bg);
        if (isOpaque && el.hasAttribute(NAV_SOLID_ATTR)) return;

        el.style.setProperty('background-color', `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`, 'important');
        el.style.setProperty('background-image', 'none', 'important');
        el.style.setProperty('backdrop-filter', 'none', 'important');
        el.style.setProperty('-webkit-backdrop-filter', 'none', 'important');
        el.setAttribute(NAV_SOLID_ATTR, '1');
    });
}

function clearSolidNavigationBars() {
    document.querySelectorAll(`[${NAV_SOLID_ATTR}]`).forEach(el => {
        el.style.removeProperty('background-color');
        el.style.removeProperty('background-image');
        el.style.removeProperty('backdrop-filter');
        el.style.removeProperty('-webkit-backdrop-filter');
        el.removeAttribute(NAV_SOLID_ATTR);
    });
}

/* ============================================================
 * 白卡玻璃化
 * ============================================================ */
function bumpPaintVersion() {
    paintVersion++;
}

function applyWhiteCardsGlass() {
    if (!isGlassApplyPage() || !currentEnabled) return;
    const userBg = buildBgValue(currentColor, currentAlpha);
    const ver = paintVersion;

    const all = document.querySelectorAll('body *');
    all.forEach(el => {
        if (SKIP_TAGS.has(el.tagName)) return;
        if (INLINE_TAGS.has(el.tagName)) return;
        if (el.matches && el.matches('.l-card')) return;
        if (el.matches && el.matches('.user-header-top')) return;
        if (el.matches && el.matches(NAV_SELECTOR)) return;
        if (el.matches && el.matches(CSS_OWNED_SELECTOR)) return;
        if (el.closest && el.closest(`#${PANEL_ID}`)) return;
        try { if (el.closest('svg')) return; } catch (e) {}
        try { if (el.closest(CONTENT_EXCLUDE)) return; } catch (e) {}
        try { if (el.closest(CSS_OWNED_SUBTREE)) return; } catch (e) {}
        try { if (el.closest(NAV_SELECTOR)) return; } catch (e) {}
        try { if (el.closest('.l-card.float-card, .dropdown.shown .l-card')) return; } catch (e) {}
        try { if (el.closest(FLOATING_EXCLUDE)) return; } catch (e) {}

        if (paintedElements.get(el) === ver) return;

        const inlineBg = el.style && el.style.backgroundColor;
        if (inlineBg && inlineBg !== 'transparent' && inlineBg !== 'rgba(0, 0, 0, 0)') {
            const rgb = parseRgb(inlineBg);
            if (rgb) {
                const max = Math.max(rgb.r, rgb.g, rgb.b);
                const min = Math.min(rgb.r, rgb.g, rgb.b);
                if (!(max - min <= 20 && min >= 240)) return;
            } else return;
        }

        let cs;
        try { cs = getComputedStyle(el); } catch { return; }
        const bg = cs.backgroundColor;
        if (!bg || bg === 'transparent' || bg === 'rgba(0, 0, 0, 0)') return;

        const rgb = parseRgb(bg);
        if (!rgb) return;
        const max = Math.max(rgb.r, rgb.g, rgb.b);
        const min = Math.min(rgb.r, rgb.g, rgb.b);
        if (max - min > 25) return;
        if (min < 210) return;

        if (!el.hasAttribute(ORIG_BG_ATTR)) {
            const orig = el.style.getPropertyValue('background-color');
            if (orig && orig !== 'transparent' && orig !== 'rgba(0, 0, 0, 0)') {
                el.setAttribute(ORIG_BG_ATTR, orig);
            }
        }

        el.style.setProperty('background-color', userBg, 'important');
        el.style.setProperty('background-image', 'none', 'important');
        el.style.setProperty('backdrop-filter', 'none', 'important');
        el.style.setProperty('-webkit-backdrop-filter', 'none', 'important');
        el.style.setProperty('border', GLASS_BORDER, 'important');
        el.style.setProperty('box-shadow', GLASS_SHADOW, 'important');
        el.setAttribute(PAINT_MARK, '1');
        paintedElements.set(el, ver);
    });
}

function clearWhiteCardsPaint() {
    document.querySelectorAll(`[${PAINT_MARK}]`).forEach(el => {
        el.style.removeProperty('background-color');
        if (el.hasAttribute(ORIG_BG_ATTR)) {
            const orig = el.getAttribute(ORIG_BG_ATTR);
            if (orig) el.style.setProperty('background-color', orig);
            el.removeAttribute(ORIG_BG_ATTR);
        }
        el.style.removeProperty('background-image');
        el.style.removeProperty('backdrop-filter');
        el.style.removeProperty('-webkit-backdrop-filter');
        el.style.removeProperty('border');
        el.style.removeProperty('box-shadow');
        el.removeAttribute(PAINT_MARK);
    });
    paintedElements = new WeakMap();

    document.querySelectorAll('.l-card.float-card, .dropdown.shown .l-card').forEach(el => {
        el.style.removeProperty('background-color');
        el.style.removeProperty('background-image');
        el.style.removeProperty('backdrop-filter');
        el.style.removeProperty('-webkit-backdrop-filter');
        el.style.removeProperty('border');
        el.style.removeProperty('box-shadow');
        el.style.removeProperty('border-radius');
    });

    /* ★ 修复 4:补清 forceUserCardGlass 在 user-info / user-action 上留下的内联样式 */
    document.querySelectorAll(
        '.l-card.float-card .user-info, .l-card.float-card .user-action, ' +
        '.dropdown.shown .l-card .user-info, .dropdown.shown .l-card .user-action'
    ).forEach(el => {
        el.style.removeProperty('background-color');
        el.style.removeProperty('background-image');
    });
}

/* ============================================================
 * JS 内联 !important 强制悬停卡片毛玻璃
 * ============================================================ */
function forceUserCardGlass() {
    if (!currentEnabled) return;
    const bg = buildBgValue(currentColor, currentAlpha);
    const cards = document.querySelectorAll('.l-card.float-card, .dropdown.shown .l-card');
    if (!cards.length) return;

    cards.forEach(el => {
        el.style.setProperty('background-color', bg, 'important');
        el.style.setProperty('background-image', 'none', 'important');
        el.style.setProperty('backdrop-filter', USER_CARD_BLUR, 'important');
        el.style.setProperty('-webkit-backdrop-filter', USER_CARD_BLUR, 'important');
        el.style.setProperty('border', GLASS_BORDER, 'important');
        el.style.setProperty('box-shadow', GLASS_SHADOW, 'important');
        el.style.setProperty('border-radius', '12px', 'important');
    });

    document.querySelectorAll('.l-card.float-card .user-info, .l-card.float-card .user-action').forEach(el => {
        el.style.setProperty('background-color', 'transparent', 'important');
        el.style.setProperty('background-image', 'none', 'important');
    });
}

function startUserCardGlassLoop() {
    if (userCardGlassTimer) return;
    userCardGlassTimer = setInterval(forceUserCardGlass, 300);
}

function stopUserCardGlassLoop() {
    if (userCardGlassTimer) {
        clearInterval(userCardGlassTimer);
        userCardGlassTimer = null;
    }
}

/* ============================================================
 * 强制 .refined-input.text 的内层元素透明
 * ============================================================ */
function forceTextInnerTransparent() {
    if (!currentEnabled) return;
    const containers = document.querySelectorAll('.refined-input.text:not(.search-text)');
    if (!containers.length) return;

    containers.forEach(container => {
        const inner = container.querySelectorAll('*');
        inner.forEach(el => {
            if (el.closest('svg') && el.tagName.toLowerCase() !== 'svg') return;
            el.style.setProperty('background-color', 'transparent', 'important');
            el.style.setProperty('background-image', 'none', 'important');
            el.style.setProperty('background', 'transparent', 'important');
            el.style.setProperty('border', 'none', 'important');
            el.style.setProperty('box-shadow', 'none', 'important');
            el.style.setProperty('outline', 'none', 'important');
            el.style.setProperty('backdrop-filter', 'none', 'important');
            el.style.setProperty('-webkit-backdrop-filter', 'none', 'important');
            el.setAttribute(INNER_TRANSPARENT_ATTR, '1');
        });
    });
}

function clearTextInnerTransparent() {
    document.querySelectorAll(`[${INNER_TRANSPARENT_ATTR}]`).forEach(el => {
        el.style.removeProperty('background-color');
        el.style.removeProperty('background-image');
        el.style.removeProperty('background');
        el.style.removeProperty('border');
        el.style.removeProperty('box-shadow');
        el.style.removeProperty('outline');
        el.style.removeProperty('backdrop-filter');
        el.style.removeProperty('-webkit-backdrop-filter');
        el.removeAttribute(INNER_TRANSPARENT_ATTR);
    });
}

/* ============================================================
 * 工单顶栏黑
 * ============================================================ */
function applyTicketTopBarBlack() {
    if (!isTicketPage() || !currentEnabled) return;
    const topBar = document.querySelector('.top-bar');
    if (!topBar) return;
    const rect = topBar.getBoundingClientRect();
    if (rect.top > 100) return;
    if (topBar.hasAttribute(TICKET_TOPBAR_ATTR)) return;

    topBar.style.setProperty('background-color', '#1a1a1a', 'important');
    topBar.style.setProperty('background-image', 'none', 'important');
    topBar.style.setProperty('backdrop-filter', 'none', 'important');
    topBar.style.setProperty('-webkit-backdrop-filter', 'none', 'important');
    topBar.style.setProperty('border-bottom', '1px solid rgba(255,255,255,0.1)', 'important');
    topBar.setAttribute(TICKET_TOPBAR_ATTR, '1');

    topBar.querySelectorAll('a, span, div, h1, h2, h3, h4, p, li').forEach(child => {
        if (child.closest('svg')) return;
        child.style.setProperty('color', '#e0e0e0', 'important');
    });
    topBar.querySelectorAll('svg').forEach(svg => {
        svg.style.setProperty('color', '#e0e0e0', 'important');
    });
}
function clearTicketTopBarBlack() {
    document.querySelectorAll(`[${TICKET_TOPBAR_ATTR}]`).forEach(el => {
        el.style.removeProperty('background-color');
        el.style.removeProperty('background-image');
        el.style.removeProperty('backdrop-filter');
        el.style.removeProperty('-webkit-backdrop-filter');
        el.style.removeProperty('border-bottom');
        el.querySelectorAll('a, span, div, h1, h2, h3, h4, p, li, svg').forEach(child => {
            child.style.removeProperty('color');
        });
        el.removeAttribute(TICKET_TOPBAR_ATTR);
    });
}

/* ============================================================
 * 文字加深 —— 只保留灰色
 * ============================================================ */
function isGrayish(r, g, b) {
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    if (max - min > 30) return false;
    if (max < 40) return false;
    if (min > 220) return false;
    return true;
}
function isAlreadyDarkGray(r, g, b) {
    return Math.abs(r - 60) < 12 && Math.abs(g - 60) < 12 && Math.abs(b - 70) < 12;
}

function darkenColorText() {
    if (IS_CLASS_SITE || IS_TI_SITE) return;
    if (isArticleDetailPage()) return;

    const containers = document.querySelectorAll(CARD_SELECTOR_RAW);
    if (!containers.length) return;

    containers.forEach(card => {
        if (card.closest && card.closest(`#${PANEL_ID}`)) return;
        card.querySelectorAll(TEXT_DARKEN_SELECTOR).forEach(el => {
            if (el.children.length > 0) return;

            if (SKIP_TAGS.has(el.tagName)) return;
            if (el.closest('svg')) return;
            if (el.closest('input, textarea, button, select')) return;
            if (el.closest('.bottom-wrap.float')) return;
            if (el.closest('.user-header-top')) return;
            if (el.closest(NAV_SELECTOR)) return;
            if (el.closest(`.${INPUT_SKIP_CLASS}`)) return;
            if (el.closest(`#${PANEL_ID}`)) return;
            try { if (el.closest(CONTENT_EXCLUDE)) return; } catch (e) {}
            try { if (el.closest('.refined-input.search-text')) return; } catch (e) {}
            try { if (el.closest('.refined-input.text')) return; } catch (e) {}
            try { if (el.closest('.search-option')) return; } catch (e) {}

            if (darkenedElements.has(el)) return;

            const inlineBg = el.style && el.style.backgroundColor;
            if (inlineBg && inlineBg !== 'transparent' && inlineBg !== 'rgba(0, 0, 0, 0)') {
                const rgb = parseRgb(inlineBg);
                if (rgb) {
                    const max = Math.max(rgb.r, rgb.g, rgb.b);
                    const min = Math.min(rgb.r, rgb.g, rgb.b);
                    if (!(max - min <= 20 && min >= 240)) return;
                } else return;
            }
            const parentInlineBg = el.parentElement && el.parentElement.style && el.parentElement.style.backgroundColor;
            if (parentInlineBg && parentInlineBg !== 'transparent' && parentInlineBg !== 'rgba(0, 0, 0, 0)') {
                const rgb = parseRgb(parentInlineBg);
                if (rgb) {
                    const max = Math.max(rgb.r, rgb.g, rgb.b);
                    const min = Math.min(rgb.r, rgb.g, rgb.b);
                    if (!(max - min <= 20 && min >= 240)) return;
                } else return;
            }

            let cs;
            try { cs = getComputedStyle(el); } catch { return; }
            const rgb = parseRgb(cs.color);
            if (!rgb) return;

            if (!isAlreadyDarkGray(rgb.r, rgb.g, rgb.b) && isGrayish(rgb.r, rgb.g, rgb.b)) {
                el.style.setProperty('color', DARK_GRAY, 'important');
                el.setAttribute(GRAY_MARK, '1');
                darkenedElements.add(el);
            }
        });
    });
}

function clearColorText() {
    document.querySelectorAll(`[${GRAY_MARK}]`).forEach(el => {
        el.style.removeProperty('color');
        el.removeAttribute(GRAY_MARK);
    });
    darkenedElements = new WeakSet();
}

/* ============================================================
 * 主入口
 * ============================================================ */
function applyCustomBg() {
    try {
        if (!currentEnabled) {
            const styleEl = document.getElementById(GLASS_STYLE_ID);
            if (styleEl && styleEl.textContent !== '') styleEl.textContent = '';
            clearGlassVars();
            clearColorText();
            clearTicketTopBarBlack();
            clearWhiteCardsPaint();
            clearTextInnerTransparent();
            clearSolidNavigationBars();
            clearPaintedBackground();
            stopThemeBgWatcher();
            stopLuoguThemePoll();
            stopUserCardGlassLoop();
            lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
            return;
        }

        const info = getThemeBackgroundInfo();
        lastThemeInfo = info;

        syncGlassVars();
        injectGlassCSS();
        solidifyNavigationBars();
        paintBackgroundInline();
        applyTicketTopBarBlack();
        applyWhiteCardsGlass();
        forceUserCardGlass();
        startUserCardGlassLoop();
        forceTextInnerTransparent();
        darkenColorText();
        startThemeBgWatcher();
        startLuoguThemePoll();
    } catch (err) {
        console.error('[铍洛谷] applyCustomBg 出错:', err);
    }
}

/* ============================================================
 * 观察器 + 节流
 * ============================================================ */
let observer = null;
let repaintTimer = null;

function scheduleRepaint() {
    if (repaintTimer) return;
    repaintTimer = setTimeout(() => {
        repaintTimer = null;
        applyCustomBg();
    }, 200);
}

function startWatching() {
    if (observer || !document.body) return;
    observer = new MutationObserver(scheduleRepaint);
    observer.observe(document.body, { childList: true, subtree: true });
}

/* ============================================================
 * 主题变化轮询
 * ============================================================ */
let themeBgPollTimer = null;
function startThemeBgWatcher() {
    if (themeBgPollTimer) return;
    themeBgPollTimer = setInterval(() => {
        if (!currentEnabled) return;
        const latest = getThemeBackgroundInfo();
        const changed =
            latest.imageUrl      !== lastThemeInfo.imageUrl ||
            latest.backColor     !== lastThemeInfo.backColor ||
            latest.colorGradient !== lastThemeInfo.colorGradient;
        if (changed) {
            lastThemeInfo = latest;
            paintBackgroundInline();
        }
    }, 800);
}
function stopThemeBgWatcher() {
    if (themeBgPollTimer) {
        clearInterval(themeBgPollTimer);
        themeBgPollTimer = null;
    }
}

function startLuoguThemePoll() {
    if (luoguThemePollTimer) return;
    luoguThemePollTimer = setInterval(() => {
        if (!currentEnabled) return;
        const themeData = extractLuoguThemeFromDoc(document);
        const parsed = themeData ? parseLBody(themeData.lBody) : null;
        if (!parsed) return;
        if (parsed.imageUrl === lastLuoguThemeImage) return;
        lastLuoguThemeImage = parsed.imageUrl;

        GM_setValue(KEY_AUTO_BG_URL, parsed.imageUrl);
        if (parsed.backColor) GM_setValue(KEY_AUTO_BG_BACK, parsed.backColor);
        if (parsed.colorGradient) GM_setValue(KEY_AUTO_BG_GRAD, parsed.colorGradient);

        if (PAGE_WIN.__LUOGU_BG_VERBOSE) {
            console.log('[铍洛谷] 检测到 #luogu-theme 变化:', parsed.imageUrl);
        }
        applyCustomBg();
    }, 1500);
}
function stopLuoguThemePoll() {
    if (luoguThemePollTimer) {
        clearInterval(luoguThemePollTimer);
        luoguThemePollTimer = null;
    }
}

/* ============================================================
 * 跨标签同步
 * ============================================================ */
let listenersAdded = false;
const listenedKeys = new Set();
function addValueListeners() {
    if (listenersAdded) return;
    listenersAdded = true;
    if (typeof GM_addValueChangeListener === 'undefined') return;
    const sync = (name, oldVal, newVal) => {
        if (name === KEY_ENABLED) currentEnabled = !!newVal;
        if (name === KEY_COLOR)   currentColor = newVal || '#232329';
        if (name === KEY_ALPHA)   currentAlpha = Math.min(1, Math.max(0.05, parseFloat(newVal) || 0.78));
        if (name === KEY_THEME_BG_URL || name === KEY_AUTO_BG_URL) {
            themeHostEl = null;
        }
        if (name === KEY_COLOR || name === KEY_ALPHA) {
            bumpPaintVersion();
        }
        setTimeout(applyCustomBg, 50);
    };
    const register = (key) => {
        if (listenedKeys.has(key)) return;
        listenedKeys.add(key);
        GM_addValueChangeListener(key, sync);
    };
    register(KEY_ENABLED);
    register(KEY_COLOR);
    register(KEY_ALPHA);
    register(KEY_THEME_BG_URL);
    register(KEY_AUTO_BG_URL);
    register(KEY_AUTO_BG_BACK);
    register(KEY_AUTO_BG_GRAD);
}

/* ============================================================
 * 设置面板
 * ============================================================ */
function injectPanelStyle() {
    if (document.getElementById(STYLE_ID)) return;
    const s = document.createElement('style');
    s.id = STYLE_ID;
    s.textContent = `
        #${PANEL_ID} {
            margin: 20px auto; max-width: 900px; padding: 20px 24px;
            position: relative;
            background: rgba(255, 255, 255, 0.35);
            backdrop-filter: blur(30px) saturate(160%) brightness(1.08);
            -webkit-backdrop-filter: blur(30px) saturate(160%) brightness(1.08);
            border: 1px solid rgba(255, 255, 255, 0.55);
            border-radius: 14px;
            box-shadow: 0 8px 32px rgba(31,38,135,0.12),
                        0 2px 8px rgba(0,0,0,0.05),
                        inset 0 1px 0 rgba(255,255,255,0.6);
            font-family: -apple-system, BlinkMacSystemFont, "PingFang SC",
                         "Microsoft YaHei", "Segoe UI", sans-serif;
            box-sizing: border-box; overflow: hidden; color: #2c3e50;
        }
        #${PANEL_ID}::before {
            content: ""; position: absolute; top: 0; left: 0; right: 0; height: 50%;
            background: linear-gradient(to bottom, rgba(255,255,255,0.35), transparent);
            pointer-events: none; border-radius: 14px 14px 0 0;
        }
        #${PANEL_ID} > * { position: relative; z-index: 1; }
        #${PANEL_ID} .panel-title {
            display: flex; align-items: center; gap: 6px;
            font-size: 15px; font-weight: 600; color: #2c3e50;
            margin-bottom: 16px; letter-spacing: 0.3px;
            text-shadow: 0 1px 2px rgba(255, 255, 255, 0.6);
        }
        #${PANEL_ID} .panel-title::before {
            content: ""; width: 3px; height: 14px;
            background: linear-gradient(to bottom, #3498db, #5dade2);
            border-radius: 2px; box-shadow: 0 0 6px rgba(52,152,219,0.5);
        }
        #${PANEL_ID} .setting-row {
            display: flex; align-items: center; justify-content: space-between;
            padding: 10px 12px; border-radius: 10px;
            background: rgba(255, 255, 255, 0.25);
            border: 1px solid rgba(255, 255, 255, 0.45);
        }
        #${PANEL_ID} .setting-label { font-size: 14px; color: #2c3e50; font-weight: 500; }
        #${PANEL_ID} .setting-desc { font-size: 12px; color: #5a6a7a; margin-top: 2px; }
        #${PANEL_ID} .toggle-switch {
            position: relative; width: 46px; height: 26px; flex-shrink: 0; cursor: pointer;
        }
        #${PANEL_ID} .toggle-switch input { opacity: 0; width: 0; height: 0; }
        #${PANEL_ID} .toggle-slider {
            position: absolute; inset: 0;
            background: rgba(180, 190, 205, 0.45);
            border: 1px solid rgba(255, 255, 255, 0.55);
            border-radius: 26px; transition: background 0.3s;
        }
        #${PANEL_ID} .toggle-slider::before {
            content: ""; position: absolute; width: 20px; height: 20px;
            left: 2px; top: 2px; background: #fff; border-radius: 50%;
            transition: transform 0.3s cubic-bezier(.4, 1.4, .6, 1);
            box-shadow: 0 2px 4px rgba(0,0,0,0.15);
        }
        #${PANEL_ID} .toggle-switch input:checked + .toggle-slider {
            background: linear-gradient(135deg, #3498db, #5dade2);
            box-shadow: 0 0 12px rgba(52,152,219,0.45);
        }
        #${PANEL_ID} .toggle-switch input:checked + .toggle-slider::before {
            transform: translateX(20px);
        }
        #${PANEL_ID} .bg-input-area { margin-top: 14px; transition: opacity 0.3s; }
        /* ★ 修复 2:只把“输入区”变灰不可点,按钮行在 DOM 上已移出本容器,所以不受影响 */
        #${PANEL_ID} .bg-input-area.disabled { opacity: 0.45; pointer-events: none; }
        #${PANEL_ID} .bg-input-area.disabled .btn-row { pointer-events: auto; }
        #${PANEL_ID} .bg-row {
            display: flex; align-items: center; gap: 12px;
            padding: 10px 12px; border-radius: 10px;
            background: rgba(255, 255, 255, 0.25);
            border: 1px solid rgba(255, 255, 255, 0.45);
            margin-top: 10px;
        }
        #${PANEL_ID} .bg-row label {
            font-size: 13px; color: #4a5a6a; width: 80px; flex-shrink: 0;
        }
        #${PANEL_ID} .bg-row .bg-value {
            font-size: 12px; color: #5a6a7a; min-width: 60px; text-align: right;
            font-family: ui-monospace, Menlo, Consolas, monospace;
        }
        #${PANEL_ID} input[type="color"] {
            width: 44px; height: 30px; padding: 0;
            border: 1px solid rgba(255, 255, 255, 0.6);
            border-radius: 8px; background: transparent;
            cursor: pointer; outline: none; flex-shrink: 0;
        }
        #${PANEL_ID} input[type="range"] {
            flex: 1; height: 6px; border-radius: 3px;
            background: rgba(255, 255, 255, 0.5);
            outline: none; -webkit-appearance: none;
            appearance: none; cursor: pointer;
        }
        #${PANEL_ID} input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 18px; height: 18px; border-radius: 50%;
            background: linear-gradient(135deg, #3498db, #5dade2);
            box-shadow: 0 2px 6px rgba(52,152,219,0.5);
            cursor: pointer; border: 2px solid #fff;
        }
        #${PANEL_ID} input[type="text"] {
            flex: 1; padding: 6px 10px; font-size: 12px;
            border: 1px solid rgba(255, 255, 255, 0.6);
            border-radius: 8px; background: rgba(255, 255, 255, 0.5);
            outline: none; font-family: ui-monospace, Menlo, Consolas, monospace;
            color: #2c3e50; min-width: 0;
        }
        #${PANEL_ID} input[type="text"]:focus {
            background: rgba(255, 255, 255, 0.8);
            border-color: #3498db;
        }
        #${PANEL_ID} .bg-preview {
            margin-top: 12px; height: 64px; border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.6);
            position: relative; overflow: hidden;
            background-image:
                linear-gradient(45deg, rgba(0,0,0,0.08) 25%, transparent 25%),
                linear-gradient(-45deg, rgba(0,0,0,0.08) 25%, transparent 25%),
                linear-gradient(45deg, transparent 75%, rgba(0,0,0,0.08) 75%),
                linear-gradient(-45deg, transparent 75%, rgba(0,0,0,0.08) 75%);
            background-size: 16px 16px;
            background-position: 0 0, 0 8px, 8px -8px, -8px 0;
        }
        #${PANEL_ID} .bg-preview-color {
            position: absolute; inset: 0; transition: background-color 0.2s;
        }
        #${PANEL_ID} .bg-preview span {
            position: absolute; inset: 0;
            display: flex; align-items: center; justify-content: center;
            font-size: 13px; color: #fff;
            text-shadow: 0 1px 3px rgba(0,0,0,0.5);
            pointer-events: none; z-index: 1;
        }
        #${PANEL_ID} .debug-info {
            margin-top: 10px; padding: 8px 12px; border-radius: 8px;
            background: rgba(0, 0, 0, 0.06);
            font-family: ui-monospace, Menlo, Consolas, monospace;
            font-size: 11px; color: #4a5a6a;
            word-break: break-all; line-height: 1.6;
        }
        #${PANEL_ID} .btn-row {
            display: flex; gap: 10px; margin-top: 12px; align-items: center;
            flex-wrap: wrap;
        }
        #${PANEL_ID} .btn {
            padding: 8px 20px; border-radius: 8px;
            font-size: 13px; font-weight: 500;
            cursor: pointer; border: 1px solid transparent;
            font-family: inherit;
        }
        #${PANEL_ID} .btn-primary {
            background: linear-gradient(135deg, #3498db, #5dade2);
            color: #fff; box-shadow: 0 4px 12px rgba(52,152,219,0.35);
        }
        #${PANEL_ID} .btn-secondary {
            background: rgba(255, 255, 255, 0.35);
            color: #5a6a7a;
            border-color: rgba(255, 255, 255, 0.55);
        }
        #${PANEL_ID} .btn-mini {
            padding: 4px 10px; font-size: 11px;
        }
        #${PANEL_ID} .save-status {
            font-size: 12px; color: #27ae60; margin-left: 4px;
            opacity: 0; transition: opacity 0.3s;
        }
        #${PANEL_ID} .save-status.show { opacity: 1; }
    `;
    document.head.appendChild(s);
}

function createPanel() {
    const manualUrl = GM_getValue(KEY_THEME_BG_URL, '') || '';

    const panel = document.createElement('div');
    panel.id = PANEL_ID;
    /* ★ 修复 1:把 .btn-row 移出 .bg-input-area,这样关闭开关时按钮不会被 pointer-events:none 波及 */
    panel.innerHTML = `
        <div class="panel-title">铍洛谷 设置</div>
        <div class="setting-row">
            <div>
                <div class="setting-label">启用自定义背景板</div>
                <div class="setting-desc">全站统一应用颜色与透明度</div>
            </div>
            <label class="toggle-switch">
                <input type="checkbox" id="bg-toggle" ${currentEnabled ? 'checked' : ''}>
                <span class="toggle-slider"></span>
            </label>
        </div>
        <div class="bg-input-area ${currentEnabled ? '' : 'disabled'}" id="bg-input-area">
            <div class="bg-row">
                <label>背景图 URL</label>
                <input type="text" id="bg-url" placeholder="留空则跟随主题" value="${manualUrl.replace(/"/g, '&quot;')}">
                <button class="btn btn-primary btn-mini" id="bg-url-apply">应用</button>
            </div>
            <div class="bg-row">
                <label>颜色</label>
                <input type="color" id="bg-color" value="${currentColor}">
                <span class="bg-value" id="bg-color-text">${currentColor}</span>
            </div>
            <div class="bg-row">
                <label>透明度</label>
                <input type="range" id="bg-alpha" min="5" max="100" value="${Math.round(currentAlpha * 100)}">
                <span class="bg-value" id="bg-alpha-text">${Math.round(currentAlpha * 100)}%</span>
            </div>
            <div class="bg-preview">
                <div class="bg-preview-color" id="bg-preview-color"></div>
                <span>预览效果</span>
            </div>
            <div class="debug-info" id="bg-debug"></div>
        </div>
        <div class="btn-row">
            <button class="btn btn-primary" id="bg-save">保存</button>
            <button class="btn btn-secondary" id="bg-reset">重置</button>
            <button class="btn btn-secondary" id="bg-refresh-theme">重新拉取主题</button>
            <button class="btn btn-secondary" id="bg-url-clear">清空手动 URL</button>
            <button class="btn btn-secondary" id="bg-auto-clear">清空自动缓存</button>
            <span class="save-status" id="bg-status">已保存</span>
        </div>
    `;

    panel.querySelectorAll('input, textarea').forEach(el => {
        el.classList.add(INPUT_SKIP_CLASS);
    });

    const toggle     = panel.querySelector('#bg-toggle');
    const inputArea  = panel.querySelector('#bg-input-area');
    const colorInput = panel.querySelector('#bg-color');
    const colorText  = panel.querySelector('#bg-color-text');
    const alphaInput = panel.querySelector('#bg-alpha');
    const alphaText  = panel.querySelector('#bg-alpha-text');
    const urlInput   = panel.querySelector('#bg-url');
    const previewColor = panel.querySelector('#bg-preview-color');
    const debugInfo  = panel.querySelector('#bg-debug');
    const status     = panel.querySelector('#bg-status');

    const showStatus = msg => {
        status.textContent = msg;
        status.classList.add('show');
        clearTimeout(status._t);
        status._t = setTimeout(() => status.classList.remove('show'), 1800);
    };

    function refreshDebug() {
        const manual = GM_getValue(KEY_THEME_BG_URL, '') || '(空)';
        const auto = GM_getValue(KEY_AUTO_BG_URL, '') || '(空)';
        const source = lastThemeInfo.source || 'none';
        const divider = buildTicketDividerColor(currentColor);
        debugInfo.innerHTML =
            `手动 URL: ${manual}<br>` +
            `自动缓存: ${auto}<br>` +
            `当前生效来源: <b>${source}</b><br>` +
            `工单分割线色: <b>${divider}</b>`;
    }

    function liveUpdate() {
        currentColor = colorInput.value;
        currentAlpha = parseInt(alphaInput.value, 10) / 100;
        colorText.textContent = currentColor;
        alphaText.textContent = `${Math.round(currentAlpha * 100)}%`;
        previewColor.style.backgroundColor = buildBgValue(currentColor, currentAlpha);
        bumpPaintVersion();
        if (currentEnabled) applyCustomBg();
        refreshDebug();
    }

    colorInput.addEventListener('input', liveUpdate);
    alphaInput.addEventListener('input', liveUpdate);
    colorInput.addEventListener('change', liveUpdate);
    alphaInput.addEventListener('change', liveUpdate);

    previewColor.style.backgroundColor = buildBgValue(currentColor, currentAlpha);
    refreshDebug();

    panel.querySelector('#bg-url-apply').addEventListener('click', () => {
        const url = urlInput.value.trim();
        GM_setValue(KEY_THEME_BG_URL, url);
        themeHostEl = null;
        lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
        applyCustomBg();
        refreshDebug();
        showStatus(url ? '已应用' : '已切回跟随主题');
    });

    panel.querySelector('#bg-refresh-theme').addEventListener('click', () => {
        preferenceFetched = false;
        serverThemeFetched = false;
        serverThemeAttempted = false;
        themeHostEl = null;
        lastLuoguThemeImage = '';
        lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
        applyCustomBg();
        fetchThemeFromApi(true).then(url => {
            if (url) {
                GM_setValue(KEY_AUTO_BG_URL, url);
                applyCustomBg();
                showStatus('已重新拉取:' + url.slice(0, 40) + '...');
            } else {
                showStatus('拉取失败');
            }
            refreshDebug();
        });
    });

    panel.querySelector('#bg-url-clear').addEventListener('click', () => {
        urlInput.value = '';
        GM_setValue(KEY_THEME_BG_URL, '');
        themeHostEl = null;
        lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
        applyCustomBg();
        refreshDebug();
        showStatus('已清空手动 URL');
    });

    panel.querySelector('#bg-auto-clear').addEventListener('click', () => {
        GM_setValue(KEY_AUTO_BG_URL, '');
        GM_setValue(KEY_AUTO_BG_BACK, '');
        GM_setValue(KEY_AUTO_BG_GRAD, '');
        lastLuoguThemeImage = '';
        refreshDebug();
        showStatus('已清空自动缓存');
    });

    urlInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            panel.querySelector('#bg-url-apply').click();
        }
    });

    /* ★ 修复 3:开关切换立即持久化,关得下去、刷新不回弹 */
    toggle.addEventListener('change', () => {
        currentEnabled = toggle.checked;
        GM_setValue(KEY_ENABLED, currentEnabled);
        inputArea.classList.toggle('disabled', !toggle.checked);
        bumpPaintVersion();
        applyCustomBg();
        refreshDebug();
    });

    panel.querySelector('#bg-save').addEventListener('click', () => {
        GM_setValue(KEY_ENABLED, currentEnabled);
        GM_setValue(KEY_COLOR,   currentColor);
        GM_setValue(KEY_ALPHA,   currentAlpha);
        GM_setValue(KEY_THEME_BG_URL, urlInput.value.trim());
        bumpPaintVersion();
        applyCustomBg();
        refreshDebug();
        showStatus('已保存');
    });

    panel.querySelector('#bg-reset').addEventListener('click', () => {
        colorInput.value = '#232329';
        alphaInput.value = 78;
        liveUpdate();
        GM_setValue(KEY_COLOR, '#232329');
        GM_setValue(KEY_ALPHA, 0.78);
        showStatus('已重置');
    });

    return panel;
}

function tryInsertPanel() {
    if (document.getElementById(PANEL_ID)) return true;
    if (!isSettingPage()) return false;
    const main = document.querySelector('main');
    if (!main) return false;
    injectPanelStyle();
    const panel = createPanel();
    const hitoPanel = document.getElementById(HITOKOTO_PANEL_ID);
    if (hitoPanel && hitoPanel.parentElement === main) {
        hitoPanel.insertAdjacentElement('afterend', panel);
    } else {
        main.appendChild(panel);
    }
    return true;
}

function tryInsertPanelWithWait() {
    if (tryInsertPanel()) return;
    let waited = 0;
    const t = setInterval(() => {
        waited += 200;
        if (tryInsertPanel()) { clearInterval(t); return; }
        if (waited >= 3000) clearInterval(t);
    }, 200);
}

/* ============================================================
 * 调试 & 手动设置接口
 * ============================================================ */
PAGE_WIN.__luoguBgDebug = function () {
    console.group('==== 铍洛谷调试 v5.4.1 ====');
    console.log('enabled:', currentEnabled);
    console.log('手动 URL:', GM_getValue(KEY_THEME_BG_URL, '') || '(空)');
    console.log('自动缓存 URL:', GM_getValue(KEY_AUTO_BG_URL, '') || '(空)');
    console.log('自动缓存 backColor:', GM_getValue(KEY_AUTO_BG_BACK, '') || '(空)');
    console.log('自动缓存 gradient:', GM_getValue(KEY_AUTO_BG_GRAD, '') || '(空)');
    console.log('lastThemeInfo:', lastThemeInfo);
    console.log('isHomePage:', isHomePage());
    console.log('lastLuoguThemeImage:', lastLuoguThemeImage);

    const themeEl = document.getElementById('luogu-theme');
    if (themeEl) {
        try {
            const t = JSON.parse(themeEl.textContent);
            console.log('#luogu-theme lBody:', t.lBody);
        } catch (e) {
            console.log('#luogu-theme 解析失败:', e);
        }
    } else {
        console.log('#luogu-theme 不存在');
    }
    console.groupEnd();
    return {
        lastThemeInfo,
        manual: GM_getValue(KEY_THEME_BG_URL, ''),
        auto: GM_getValue(KEY_AUTO_BG_URL, ''),
    };
};

PAGE_WIN.__luoguBgInspectUserCard = function () {
    console.log('[铍洛谷] 请在 3 秒内把鼠标悬停到一个用户名上,并保持不动...');
    setTimeout(() => {
        const el = document.querySelector('.l-card.float-card');
        if (!el) {
            console.warn('[铍洛谷] 未找到 .l-card.float-card,请确认鼠标正悬停在用户名上');
            return null;
        }
        const cs = getComputedStyle(el);
        const info = {
            bg: cs.backgroundColor,
            backdropFilter: cs.backdropFilter || cs.webkitBackdropFilter,
            border: cs.borderTopWidth + ' ' + cs.borderTopStyle + ' ' + cs.borderTopColor,
            boxShadow: cs.boxShadow.slice(0, 80),
            borderRadius: cs.borderTopLeftRadius,
            inlineStyle: el.getAttribute('style'),
        };
        console.log('l-card.float-card:', info);
        console.log(el);
        return info;
    }, 3000);
    return '等待中... 3 秒后看控制台';
};

PAGE_WIN.__luoguBgForceRefresh = function () {
    themeHostEl = null;
    preferenceFetched = false;
    serverThemeFetched = false;
    serverThemeAttempted = false;
    lastLuoguThemeImage = '';
    lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
    bumpPaintVersion();
    applyCustomBg();
    console.log('[铍洛谷] 已强制刷新');
    return lastThemeInfo;
};

PAGE_WIN.__luoguBgFetchTheme = function () {
    preferenceFetched = false;
    serverThemeFetched = false;
    serverThemeAttempted = false;
    lastLuoguThemeImage = '';
    fetchThemeFromPreference().then(() => {
        if (!lastThemeInfo.imageUrl) {
            return fetchThemeFromApi(true).then(url => {
                if (url) {
                    GM_setValue(KEY_AUTO_BG_URL, url);
                    applyCustomBg();
                }
                return url;
            });
        }
    });
    console.log('[铍洛谷] 已触发主题拉取');
};

PAGE_WIN.__luoguBgFetchFromServer = function () {
    serverThemeFetched = false;
    serverThemeAttempted = false;
    lastLuoguThemeImage = '';
    return fetchThemeFromApi(true).then(url => {
        console.log('[铍洛谷] fetch 结果:', url);
        if (url) {
            GM_setValue(KEY_AUTO_BG_URL, url);
            applyCustomBg();
        }
        return url;
    });
};

PAGE_WIN.__luoguBgFetchViaIframe = PAGE_WIN.__luoguBgFetchFromServer;

PAGE_WIN.__luoguBgSetThemeBg = function (url) {
    url = (url || '').trim();
    GM_setValue(KEY_THEME_BG_URL, url);
    themeHostEl = null;
    lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
    applyCustomBg();
    console.log('[铍洛谷] 手动 URL =', url || '(已清空)');
};

PAGE_WIN.__luoguBgSetAutoBg = function (url) {
    url = (url || '').trim();
    GM_setValue(KEY_AUTO_BG_URL, url);
    themeHostEl = null;
    lastLuoguThemeImage = '';
    lastThemeInfo = { imageUrl: null, backColor: null, colorGradient: null, source: 'none' };
    applyCustomBg();
    console.log('[铍洛谷] 自动缓存 URL =', url || '(已清空)');
};

/* ★ 新增:一键彻底关闭并清干净(万一 UI 出问题可在控制台调用) */
PAGE_WIN.__luoguBgForceDisable = function () {
    GM_setValue(KEY_ENABLED, false);
    currentEnabled = false;
    bumpPaintVersion();
    applyCustomBg();
    console.log('[铍洛谷] 已强制关闭');
};

PAGE_WIN.__luoguBgVerbose = function (on) {
    PAGE_WIN.__LUOGU_BG_VERBOSE = !!on;
    console.log('[铍洛谷] verbose =', PAGE_WIN.__LUOGU_BG_VERBOSE);
};

/* ============================================================
 * 启动
 * ============================================================ */
function boot() {
    try {
        const themeData = extractLuoguThemeFromDoc(document);
        const parsed = themeData ? parseLBody(themeData.lBody) : null;
        if (parsed) lastLuoguThemeImage = parsed.imageUrl;

        applyCustomBg();
        startWatching();
        addValueListeners();
        if (isSettingPage()) tryInsertPanelWithWait();

        if (IS_MAIN_SITE && !getManualBgUrl()) {
            fetchThemeFromApi().then(url => {
                if (url && currentEnabled) {
                    const old = GM_getValue(KEY_AUTO_BG_URL, '');
                    if (old !== url) {
                        GM_setValue(KEY_AUTO_BG_URL, url);
                        applyCustomBg();
                    }
                }
            });
        }

        console.log(
            '[铍洛谷] v5.4.1 已启动。\n' +
            '  调试: __luoguBgDebug()\n' +
            '  悬停卡片调试: __luoguBgInspectUserCard()\n' +
            '  强制刷新: __luoguBgForceRefresh()\n' +
            '  重新拉取主题: __luoguBgFetchTheme()\n' +
            '  fetch 拉取: __luoguBgFetchFromServer()\n' +
            '  强制关闭: __luoguBgForceDisable()'
        );
    } catch (err) {
        console.error('[铍洛谷] boot 出错:', err);
    }
}

boot();

let lastUrl = location.href;
setInterval(() => {
    if (location.href !== lastUrl) {
        lastUrl = location.href;
        serverThemeAttempted = false;
        setTimeout(() => {
            try {
                applyCustomBg();
                startWatching();
                if (isSettingPage()) tryInsertPanelWithWait();
                if (IS_MAIN_SITE && !getManualBgUrl()) {
                    fetchThemeFromApi().then(url => {
                        if (url && currentEnabled) {
                            const old = GM_getValue(KEY_AUTO_BG_URL, '');
                            if (old !== url) {
                                GM_setValue(KEY_AUTO_BG_URL, url);
                                applyCustomBg();
                            }
                        }
                    });
                }
            } catch (err) {
                console.error('[铍洛谷] URL 变化后重绘出错:', err);
            }
        }, 300);
    }
}, 800);

})();

代码

三、打开设置面板

入口只有一个:/user/setting/preference 页面

步骤:

  1. 右上角头像 → 用户设置 → 偏好设置
  2. 页面往下滚,会看到一个”铍洛谷 设置”的玻璃卡片

或者直接访问:https://www.luogu.com.cn/user/setting/preference


四、设置面板各控件说明

顶部开关

  • 启用自定义背景板:总开关。关掉后整个脚本效果消失,洛谷回到原生外观
  • 只有打开这个开关,下面的选项才生效

背景图 URL

  • 留空:跟随你在洛谷主题商店选的主题(推荐)
  • 填一张图:强制使用这张图作为背景,忽略主题商店
  • 点「应用」立即生效,「清空手动 URL」回到跟随主题

颜色

  • 决定所有玻璃卡片的基础色(默认 #232329 深灰黑)
  • 配合下面的透明度,决定卡片视觉

透明度

  • 5%:几乎看不见玻璃,卡片完全透明
  • 40%~60%:轻度玻璃,背景图清晰可见
  • 78%(默认):标准玻璃,文字可读性好
  • 100%:卡片完全不透明

预览效果

  • 实时显示当前「颜色 + 透明度」组合的样子

按钮

按钮作用
保存把当前设置写入存储,其他标签页也会同步
重置颜色回到 #232329,透明度回到 78%
重新拉取主题强制从洛谷重新读取当前主题的背景图/色
清空手动 URL清掉手动填的背景图,回到跟随主题
清空自动缓存清掉自动缓存的背景图,下次刷新重新拉

五、常用场景

场景 1:想让背景完全跟随洛谷主题

  1. 打开设置面板
  2. 背景图 URL 留空
  3. 点「保存」

场景 2:想用自己找的图

  1. 打开设置面板
  2. 在「背景图 URL」里粘贴图片直链(必须是 http(s):// 开头)
  3. 点「应用」
  4. 点「保存」持久化

场景 3:卡片太透明,文字看不清

  1. 把「透明度」滑到 85% 或 90%
  2. 或者把「颜色」调成更深的色,比如 #1a1a1a
  3. 点「保存」

场景 4:刚在主题商店换了主题,页面没变

  • 通常 1~2 秒内会自动更新(脚本每 1.5s 轮询一次)
  • 如果还没变:点「重新拉取主题」
  • 再不行:F5 刷新页面

场景 5:某页面看着很乱,想临时关掉

  • 设置面板 → 关掉「启用自定义背景板」开关
  • 或 F12 控制台执行 __luoguBgDebug() 查看当前状态

六、调试接口(F12 控制台用)

打开 F12 → Console,可以执行:

查看当前状态

JavaScript
__luoguBgDebug()

输出当前启用状态、手动URL、自动缓存、#luogu-theme 实时数据等,排查问题第一站。

强制刷新

JavaScript
__luoguBgForceRefresh()

清掉所有缓存标记,重新读取主题并重绘。

强制重新拉取主题

JavaScript
__luoguBgFetchTheme()

从洛谷重新拉一次主题背景。

手动设置背景图

JavaScript
__luoguBgSetThemeBg('https://cdn.luogu.com.cn/upload/image_hosting/xxx.png')

相当于在面板里填 URL 并应用。

手动清空自动缓存

JavaScript
__luoguBgSetAutoBg('')

打开 verbose 日志

JavaScript
__luoguBgVerbose(true)

之后主题变化、拉取过程都会打印详细日志,排查问题很有用。


七、常见问题

Q1:控制台报 Framing ... violates CSP

A:这是 v4.7 及之前用 iframe 方案的错误。v5.0 之后已改用 fetch + <script id="luogu-theme"> 解析,不会再有这个报错。

Q2:换了主题,背景图不变

A:先 F5 一次。如果还是不变,执行 __luoguBgForceRefresh()。如果仍不变,执行 __luoguBgDebug() 看 #luogu-theme lBody 是不是你换的主题,如果不是,说明洛谷没更新那个 script 标签,需要在洛谷那边切回主题商店页面再切回来。

Q3:设置面板不见了

A:确认你在 /user/setting/preference 页面。如果脚本启动正常但面板没出现,可能是洛谷改了页面结构,F12 执行 __luoguBgDebug() 看下有没有报错。

Q4:多个标签同时开着,一个改了设置其他不变

A:正常情况下跨标签会同步。如果不同步,检查 Tampermonkey 是否给了「跨域存储」权限(在扩展设置里搜 GM_setValue)。

Q5:跟洛谷官方的”毛玻璃”冲突吗

A:冲突。脚本需要关闭洛谷默认毛玻璃效果才能用


八、已知限制

限制说明
主页没有 #luogu-theme会走 fetch /theme 兜底,可能慢 100~300ms
iOS Safari 背景抖动background-attachment: fixed 在移动端不稳,可考虑关闭脚本或换桌面端
主题商店刚换主题需要等 1.5s 轮询或手动刷新
部分浮层popper、tooltip、dropdown 等浮层刻意不做玻璃化,避免叠层视觉混乱

九、卸载

  1. Tampermonkey 面板 → 找到「铍洛谷」→ 删除
  2. F5 刷新页面即可恢复洛谷原生外观
  3. 如果想清理残留存储,F12 执行 GM_setValue('bg_custom_enabled', false) 再删脚本

十、更新脚本

当有新版本时:

  1. Tampermonkey 面板 → 找到「铍洛谷」
  2. 打开编辑器,全选 → 粘贴新版全部代码 → 保存
  3. F5 刷新任意洛谷页面

建议整份替换,不要只替换部分函数,避免版本错配。

问题反馈

请联系 @Breakon


注:本文包括插件由DeepSeek协助完成


叠甲

由于这是作者第一次探索类似的插件,以及这个项目目前还处于测试阶段,所以可能有各种各样的BUG。

免责声明

铍洛谷是一个美化洛谷的插件,不含任何爬取/滥用数据或API或修改了洛谷的核心功能或数据或影响其他用户或服务器稳定性等损害洛谷或其他用户利益的功能。如果用户因为铍洛谷(包括从第三方下载、私自修改等)被封禁,铍洛谷概不负责。

如果洛谷官方明令禁止,请立即停止使用此脚本。

更新日志

V5.4 修复了一些已知问题

V5.5.1 修复了很多已知问题