跳到正文

科技·工程

插件 - Concise Luogu!

wendywan约 165 分钟
原文
文章信息与版本

文章信息

发布
2026年11月7日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 165 分钟
获赞
1

版本

  1. v1当前

继强力学术之后的简约版本,因为强力学术更多是面向番茄种学习方式,而这个版本直接一刀切更加决绝,而且很方便。

From @SMHBD_’s 简洁的洛谷。

增加一点小功能。

原有功能:

  • 拦截讨论区、文章等页面以及入口;
  • 去除最顶上的广告以及主页侧边智能推荐、公告、友链。

增设功能:

  • 广告位、屏蔽页增设自定义头图;
  • 改变对文章的盲目屏蔽(待完善);
  • 增加玩玩小草功能,比来源体验感稍微差一点,但是起到了多动症释放的作用,减少了我想要关闭插件的次数。
Code.\textup{Code.}
JavaScript
// ==UserScript==
// @name         简洁的洛谷
// @namespace    https://www.luogu.com.cn/
// @version      14.7
// @description  精简洛谷页面并修复设置页布局;新增可拖动的“玩玩小草”互动浮窗
// @author       -
// @match        *://*.luogu.com.cn/*
// @match        *://*.luogu/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const BLOCKED_TEXT = '🚫 该页面已被屏蔽';
    const REMOVED_FEATURE_NAMES = ['陶片放逐', '小黑屋'];

    /* ============================================================
       路径处理:统一 decodeURIComponent
       ============================================================ */
    const decodePath = (raw) => {
        try { return decodeURIComponent(raw); } catch (e) { return raw; }
    };

    // 所有 /article/_ 开头的路径都是编辑器页面(_new、_draft 等)
    const isEditorPath = (path) => /^\/article\/_/i.test(path);

    const ARTICLE_RESERVED = /^(mine|new|list|edit|draft)$/i;

    const isArticleDetailPage = (rawPath) => {
        const path = decodePath(rawPath);
        if (isEditorPath(path)) return false;
        if (/\/edit(\/|$)/.test(path)) return false;
        const m = path.match(/^\/article\/([a-z0-9_]+)(?:\/|$)/i);
        if (!m) return false;
        const id = m[1];
        if (ARTICLE_RESERVED.test(id)) return false;
        if (id.charCodeAt(0) === 95) return false;
        return true;
    };

    const isBlockedPath = (rawPath, search) => {
        const path = decodePath(rawPath);
        search = search || '';

        if (path.startsWith('/discuss')) return true;
        if (path.startsWith('/ticket')) return true;
        if (path === '/judgement' || path.startsWith('/judgement/')) return true;

        if (path.startsWith('/article')) {
            // 编辑器路径,无条件放行
            if (isEditorPath(path)) return false;
            if (/\/edit(\/|$)/.test(path)) return false;
            if (path === '/article/mine' || path.startsWith('/article/mine/')) return false;
            if (path === '/article/new' || path.startsWith('/article/new/')) return false;
            if (isArticleDetailPage(path)) return false;
            if (/[?&](type|tab|filter|category)=(mine|own|my|personal)(&|=|$)/.test(search)) return false;
            return true;
        }
        return false;
    };

    const OVERLAY_ID = 'lp-block-overlay';
    const BLOCK_STYLE_ID = 'lp-block-style';

    let blocked = false;
    let savedTitle = '';
    let blockObserver = null;
    let articleJudging = false;

    /* ============================================================
       封禁页遮罩:全部 inline style
       ============================================================ */
    const OVERLAY_STYLE = [
        'position:fixed',
        'top:0', 'left:0', 'right:0', 'bottom:0',
        'width:100vw', 'height:100vh',
        'z-index:2147483647',
        'display:flex', 'flex-direction:column',
        'align-items:center', 'justify-content:center',
        'background:#f5f5f5', 'color:#333',
        'font-family:system-ui,-apple-system,"Segoe UI",sans-serif',
        'margin:0', 'padding:0',
        'visibility:visible', 'opacity:1',
        'pointer-events:all'
    ].join(';') + ';';

    const OVERLAY_INNER = '<div style="font-size:56px;line-height:1;margin-bottom:16px;">🚫</div><div style="font-size:20px;">该页面已被屏蔽</div>';

    const ensureOverlayNow = () => {
        if (!blocked) return;

        // 洛谷可能在 SPA 渲染后再次修改 title,因此每次 DOM 变化都校正标签页标题。
        if (document.title !== BLOCKED_TEXT) document.title = BLOCKED_TEXT;

        const body = document.body;
        if (!body) return;

        let overlay = document.getElementById(OVERLAY_ID);
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = OVERLAY_ID;
        }
        if (overlay.style.cssText !== OVERLAY_STYLE) overlay.style.cssText = OVERLAY_STYLE;
        if (overlay.innerHTML !== OVERLAY_INNER) overlay.innerHTML = OVERLAY_INNER;

        if (overlay.parentNode !== body) body.appendChild(overlay);
    };

    const blockPage = () => {
        if (blocked) return;
        blocked = true;
        savedTitle = document.title;

        ensureOverlayNow();
        document.addEventListener('DOMContentLoaded', ensureOverlayNow, { once: true });

        if (blockObserver) blockObserver.disconnect();
        blockObserver = new MutationObserver(ensureOverlayNow);

        // 监听 title 节点文本、head/body 子树和 SPA 重建,持续保持屏蔽标题。
        blockObserver.observe(document.documentElement, {
            childList: true,
            subtree: true,
            characterData: true
        });
    };

    const unblockPage = () => {
        if (!blocked) return;
        blocked = false;

        if (blockObserver) {
            blockObserver.disconnect();
            blockObserver = null;
        }

        const overlay = document.getElementById(OVERLAY_ID);
        if (overlay) overlay.remove();

        if (savedTitle && document.title === BLOCKED_TEXT) {
            document.title = savedTitle;
        }
    };

    /* ============================================================
       文章详情页判断
       ============================================================ */
    const pendingArticleJudge = () => {
        if (articleJudging) return;
        articleJudging = true;

        let resolved = false;
        let mo = null;
        let timer = null;

        const cleanup = () => {
            if (mo) {
                mo.disconnect();
                mo = null;
            }
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            articleJudging = false;
        };

        const finish = (isMine) => {
            if (resolved) return;
            resolved = true;
            cleanup();
            if (!isMine) blockPage();
        };

        const tryJudge = () => {
            if (resolved) return true;

            const actionBars = document.querySelectorAll('.article-content > .actions');
            if (!actionBars.length) return false;

            for (const bar of actionBars) {
                if (bar.querySelector('svg.fa-pen-to-square, svg[data-icon="pen-to-square"]')) {
                    finish(true);
                    return true;
                }

                for (const a of bar.querySelectorAll('a')) {
                    if ((a.textContent || '').trim() === '编辑') {
                        finish(true);
                        return true;
                    }
                }
            }

            finish(false);
            return true;
        };

        if (tryJudge()) return;

        // 先创建超时器,确保 tryJudge() 同步结束判断时 cleanup 能正确清理它。
        timer = setTimeout(() => {
            if (!resolved) finish(false);
        }, 2000);

        mo = new MutationObserver(() => {
            if (!resolved) tryJudge();
        });

        const startObserve = () => {
            if (resolved) return;
            if (document.body) {
                mo.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
            tryJudge();
        };

        if (document.body) {
            startObserve();
        } else {
            document.addEventListener('DOMContentLoaded', startObserve, { once: true });
        }
    };

    /* ============================================================
       侧边栏处理
       ============================================================ */
    const ENTRY_DEFS = [
        { prefix: '/discuss', text: '讨论' },
        { prefix: '/ticket', text: '工单' },
        { prefix: '/article', text: '文章广场' },
        // 排名入口及其子页面(例如 /ranking/elo)统一按讨论区的方式移除并拦截。
        { prefix: '/ranking', text: '咕值排名' }
    ];
    const REMOVED_SIDEBAR_LABELS = ['咕值排名', '等级分排名', '洛谷有题'];

    const SCOPES = 'nav, aside';
    const isScope = (el) => el.matches && el.matches(SCOPES);

    // 删除指定功能入口,并清理相邻分隔符,让这一项看起来从未存在。
    const cleanFeatureSeparator = (target) => {
        const isSeparatorText = (value) =>
            /^[\s·•⋅・||,,、;;::]+$/.test(value || '');

        const trimTrailingSeparator = (node) => {
            if (!node || node.nodeType !== Node.TEXT_NODE) return false;

            const value = node.nodeValue || '';
            const next = value.replace(/[\s]*[·•⋅・||,,、;;::]+[\s]*$/, '');

            if (next === value) return false;

            if (next.trim()) {
                node.nodeValue = next;
            } else {
                node.remove();
            }

            return true;
        };

        const trimLeadingSeparator = (node) => {
            if (!node || node.nodeType !== Node.TEXT_NODE) return false;

            const value = node.nodeValue || '';
            const next = value.replace(/^[\s]*[·•⋅・||,,、;;::]+[\s]*/, '');

            if (next === value) return false;

            if (next.trim()) {
                node.nodeValue = next;
            } else {
                node.remove();
            }

            return true;
        };

        if (!target || !target.parentNode) return;

        const prev = target.previousSibling;
        const next = target.nextSibling;

        let cleaned = trimTrailingSeparator(prev);

        if (!cleaned && prev &&
            prev.nodeType === Node.ELEMENT_NODE &&
            isSeparatorText(prev.textContent)) {
            prev.remove();
            cleaned = true;
        }

        // 优先清理左侧分隔符;左侧没有时才清理右侧,避免留下两个相邻分隔点。
        if (!cleaned) {
            if (trimLeadingSeparator(next)) {
                cleaned = true;
            } else if (next &&
                next.nodeType === Node.ELEMENT_NODE &&
                isSeparatorText(next.textContent)) {
                next.remove();
            }
        }
    };

    const banNamedFeature = () => {
        document.querySelectorAll('a').forEach((a) => {
            const label = (a.textContent || '').replace(/\s+/g, ' ').trim();

            if (!label || !REMOVED_FEATURE_NAMES.some((name) => label.includes(name))) {
                return;
            }

            const target = pickTarget(a);
            cleanFeatureSeparator(target);
            target.remove();
        });
    };

    // 删除指定页脚链接及版权/备案文字;这里是直接移除,不做跳转拦截。
    // 只处理真正的页脚,避免误删用户设置等正文中的普通帮助链接或布局容器。
    const removeFooterInfo = () => {
        document.querySelectorAll('footer, #footer, .footer, .lg-footer, .lfe-footer')
            .forEach((footer) => {
                const text = (footer.textContent || '').replace(/\s+/g, ' ');
                const hasTargetContent =
                    /关于洛谷|用户协议|帮助中心|联系我们|社区规则|在洛谷,享受\s*Coding\s*的欢乐|©\s*2013\s*[-–—]\s*2026\s*洛谷|增值电信业务经营许可证|沪ICP备\s*18008322/i.test(text);
                if (hasTargetContent) footer.remove();
            });
    };
    const pickTarget = (a) => {
        const li = a.closest('li');
        if (li && li.querySelectorAll('a').length === 1) return li;
        return a;
    };

    const findSidebarEntries = () => {
        const result = new Set();

        document.querySelectorAll(SCOPES).forEach((scope) => {
            scope.querySelectorAll('a[href]').forEach((a) => {
                const href = a.getAttribute('href') || '';
                const label = (a.textContent || '').replace(/\s+/g, ' ').trim();
                const matchedByPath = ENTRY_DEFS.some(({ prefix, text }) =>
                    href.startsWith(prefix) && (label === text || label.startsWith(text))
                );
                const matchedByLabel = REMOVED_SIDEBAR_LABELS.some((name) =>
                    label === name || label.startsWith(name)
                );
                if (matchedByPath || matchedByLabel) result.add(a);
            });
        });

        return Array.from(result);
    };

    const isDivider = (el) => {
        if (!el || el.nodeType !== 1) return false;
        if (el.tagName === 'HR') return true;

        const cls = (
            String(el.className || '') + ' ' +
            String(el.id || '')
        ).toLowerCase();

        if (/divider|separator|split|horizontal[-_]?line/.test(cls)) {
            return true;
        }

        if (el.textContent.trim()) return false;
        if (el.querySelector('a, img, button, input, svg')) return false;
        if (el.getBoundingClientRect().height <= 3) return true;

        if (el.children.length === 1) {
            const child = el.children[0];

            if (!child.textContent.trim() &&
                child.getBoundingClientRect().height <= 3 &&
                !child.querySelector('a, img, button, input, svg')) {
                return true;
            }
        }

        return false;
    };

    const markBlocked = () => {
        const links = findSidebarEntries();
        if (!links.length) return;

        let needsWork = false;

        for (const a of links) {
            if (!pickTarget(a).classList.contains('lp-blocked')) {
                needsWork = true;
                break;
            }
        }

        if (!needsWork) return;

        document.querySelectorAll(
            '.lp-prev-of-blocked, .lp-next-of-blocked, .lp-divider-hidden'
        ).forEach((el) => {
            el.classList.remove(
                'lp-prev-of-blocked',
                'lp-next-of-blocked',
                'lp-divider-hidden'
            );
        });

        document.querySelectorAll('.lp-blocked-ancestor').forEach((el) => {
            el.classList.remove('lp-blocked-ancestor');
        });

        const targets = new Set(links.map(pickTarget));
        targets.forEach((el) => el.classList.add('lp-blocked'));

        targets.forEach((el) => {
            let node = el.parentElement;

            while (node &&
                !isScope(node) &&
                node !== document.body &&
                node !== document.documentElement) {

                const hasContent = Array.from(node.children).some((c) => {
                    if (c === el) return false;
                    if (c.classList.contains('lp-blocked')) return false;
                    if (c.classList.contains('lp-blocked-ancestor')) return false;
                    if ((c.textContent || '').trim().length > 0) return true;
                    if (c.querySelector('a, img, button, input, svg')) return true;
                    if (c.getBoundingClientRect().height > 4) return true;
                    return false;
                });

                if (hasContent) break;

                node.classList.add('lp-blocked-ancestor');
                node = node.parentElement;
            }
        });

        const pairs = [];

        targets.forEach((el) => {
            const prevDivs = [];
            let p = el.previousElementSibling;

            while (p && isDivider(p) && !targets.has(p)) {
                prevDivs.push(p);
                p = p.previousElementSibling;
            }

            const nextDivs = [];
            let n = el.nextElementSibling;

            while (n && isDivider(n) && !targets.has(n)) {
                nextDivs.push(n);
                n = n.nextElementSibling;
            }

            pairs.push({ prev: prevDivs, next: nextDivs });
        });

        pairs.forEach(({ prev, next }) => {
            if (prev.length && next.length) {
                next.forEach((d) => d.classList.add('lp-divider-hidden'));
            }
        });

        const prevBoundary = new Set();
        const nextBoundary = new Set();

        targets.forEach((el) => {
            let p = el.previousElementSibling;

            while (p &&
                (targets.has(p) ||
                p.classList.contains('lp-blocked-ancestor') ||
                isDivider(p))) {
                p = p.previousElementSibling;
            }

            if (p) prevBoundary.add(p);

            let n = el.nextElementSibling;

            while (n &&
                (targets.has(n) ||
                n.classList.contains('lp-blocked-ancestor') ||
                isDivider(n))) {
                n = n.nextElementSibling;
            }

            if (n) nextBoundary.add(n);
        });

        prevBoundary.forEach((el) => el.classList.add('lp-prev-of-blocked'));
        nextBoundary.forEach((el) => el.classList.add('lp-next-of-blocked'));
    };

    /* ============================================================
       样式注入(等待 head)
       ============================================================ */
    const injectBlockStyleOnce = () => {
        if (document.getElementById(BLOCK_STYLE_ID)) return;

        const s = document.createElement('style');
        s.id = BLOCK_STYLE_ID;

        s.textContent = `
            nav a[href="/discuss"], nav a[href="/ticket"], nav a[href="/article"],
            aside a[href="/discuss"], aside a[href="/ticket"], aside a[href="/article"] {
                display: none !important;
            }

            .lp-blocked, .lp-blocked-ancestor, .lp-divider-hidden {
                display: none !important;
            }

            .lp-prev-of-blocked {
                border-top: none !important;
                box-shadow: none !important;
            }

            .lp-prev-of-blocked::after {
                display: none !important;
            }

            .lp-next-of-blocked {
                border-top: none !important;
                box-shadow: none !important;
            }

            .lp-next-of-blocked::before {
                display: none !important;
            }

            div.lg-index-benben.lg-right > div:first-child + div,
            .lg-index-content.am-center > div:first-child + div + div > div:first-child + div > div:first-child + div {
                display: none !important;
            }

            div.lg-article.am-hide-sm {
                display: none !important;
            }

            .lp-ads-replaced {
                position: relative !important;
                padding: 0 !important;
                margin: 0 !important;
                background: transparent !important;
                border: none !important;
                overflow: hidden !important;
            }

            .lp-gears-wrap {
                position: relative;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }

            .lp-gears {
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%) scale(1);
                transform-origin: center center;
            }

            .lp-gear {
                position: absolute;
                transform-origin: center center;
            }

            .lp-gear svg {
                display: block;
                overflow: visible;
            }

            @keyframes lp-spin {
                from { transform: rotate(0deg); }
                to { transform: rotate(360deg); }
            }

            .lp-gear-text {
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                font-size: 28px;
                font-weight: 600;
                color: #555;
                letter-spacing: 2px;
                white-space: nowrap;
                pointer-events: none;
                user-select: none;
                z-index: 2;
                text-shadow: 0 0 10px #fff, 0 0 10px #fff, 0 0 10px #fff;
            }

            /* 玩玩小草:侧边栏入口与可拖动浮窗 */
            .lp-grass-menu svg, .lp-grass-menu i,
            .lp-grass-menu .icon, .lp-grass-menu .nav-icon {
                display: none !important;
            }
            #lp-grass-panel {
                position: fixed;
                left: 16px;
                bottom: 16px;
                width: min(400px, calc(100vw - 32px));
                height: 280px;
                z-index: 2147483000;
                display: flex;
                flex-direction: column;
                overflow: hidden;
                border: 1px solid rgba(255,255,255,.2);
                border-radius: 10px;
                background: #111;
                box-shadow: 0 8px 30px rgba(0,0,0,.35);
            }
            #lp-grass-panel[hidden] { display: none !important; }
            #lp-grass-panel .lp-grass-head {
                height: 34px;
                min-height: 34px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10px;
                color: #eee;
                background: #292929;
                font: 13px/1.2 system-ui, sans-serif;
                cursor: move;
                user-select: none;
                touch-action: none;
            }
            #lp-grass-panel .lp-grass-close {
                width: 24px;
                height: 24px;
                padding: 0;
                border: 0;
                border-radius: 5px;
                color: #ddd;
                background: transparent;
                font: 20px/24px sans-serif;
                cursor: pointer;
            }
            #lp-grass-panel .lp-grass-close:hover { background: #555; }
            #lp-grass-panel iframe {
                display: block;
                width: 100%;
                height: calc(100% - 34px);
                flex: 1;
                border: 0;
                background: #000;
            }
            @media (max-width: 520px) {
                #lp-grass-panel {
                    width: calc(100vw - 20px);
                    height: min(270px, 40vh);
                    left: 10px;
                    bottom: 10px;
                }
            }

        `;

        const append = () => {
            if (document.getElementById(BLOCK_STYLE_ID)) return;

            if (document.head) {
                document.head.appendChild(s);
            } else {
                document.documentElement.appendChild(s);
            }
        };

        if (document.head) {
            append();
        } else {
            document.addEventListener('DOMContentLoaded', append, { once: true });
        }
    };

    injectBlockStyleOnce();

    /* ============================================================
       路由监听:编辑器路径优先放行
       ============================================================ */
    const checkAndBlock = () => {
        const path = decodePath(location.pathname);

        // 编辑器路径无条件放行,不走任何判断
        if (isEditorPath(path)) {
            if (blocked) unblockPage();
            markBlocked();
            return;
        }

        if (isBlockedPath(path, location.search)) {
            blockPage();
            return;
        }

        if (blocked) unblockPage();

        if (isArticleDetailPage(path)) {
            pendingArticleJudge();
        }

        markBlocked();
    };

    ['pushState', 'replaceState'].forEach((m) => {
        const orig = history[m];

        history[m] = function (...args) {
            const r = orig.apply(this, args);
            checkAndBlock();
            return r;
        };
    });

    window.addEventListener('popstate', checkAndBlock);

    window.addEventListener('pageshow', (e) => {
        if (e.persisted) checkAndBlock();
    });

    /* ============================================================
       初始判断:编辑器路径优先放行
       ============================================================ */
    const initPath = decodePath(location.pathname);
    const initSearch = location.search;

    if (isEditorPath(initPath)) {
        // 编辑器页面,不屏蔽、不判断
    } else if (isBlockedPath(initPath, initSearch)) {
        blockPage();
        return;
    } else if (isArticleDetailPage(initPath)) {
        pendingArticleJudge();
    }

    /* ============================================================
       首页板块隐藏
       ============================================================ */
    const TOP_LEVEL = ['BODY', 'HTML', 'MAIN'];
    const TOP_LEVEL_IDS = ['app', 'main', 'root'];

    const isUnsafeContainer = (el) => {
        if (!el || TOP_LEVEL.includes(el.tagName)) return true;
        if (el.id && TOP_LEVEL_IDS.includes(el.id)) return true;
        if (el.querySelectorAll('a').length > 40) return true;
        if ((el.textContent || '').length > 4000) return true;
        return false;
    };

    const TITLE_KEYWORDS = ['工单', '文章广场'];

    const hideBlockedSections = () => {
        document.querySelectorAll(
            'h1, h2, h3, h4, h5, h6, [class*="title"], [class*="header"]'
        ).forEach((title) => {
            const t = (title.textContent || '').trim();

            if (!TITLE_KEYWORDS.some(k => t === k || t === `${k}区`)) {
                return;
            }

            let smallest = title.parentElement;

            while (smallest && !isUnsafeContainer(smallest)) {
                if (smallest.dataset.lpHiddenSection === '1') return;

                if (smallest.querySelector('a[href^="/ticket"], a[href^="/article"]')) {
                    smallest.style.display = 'none';
                    smallest.dataset.lpHiddenSection = '1';
                    return;
                }

                smallest = smallest.parentElement;
            }
        });
    };

    const SIDE_FALLBACK_SELECTORS = [
        'div.lg-article.am-hide-sm',
        'div.am-u-lg-3.am-u-md-4.lg-right > div:first-child'
    ];

    // 按标题移除独立板块:只删除标题所在的小容器,不向上误删包含其他板块的布局。
    const removeSectionByExactHeading = (headingText) => {
        document.querySelectorAll('h1, h2, h3, h4, h5, h6, [class*="title"], [class*="header"], [class*="Title"], [class*="Header"]').forEach((title) => {
            if ((title.textContent || '').replace(/\s+/g, ' ').trim() !== headingText) return;
            let node = title;
            for (let depth = 0; depth < 7 && node && node.parentElement && node !== document.body; depth++) {
                const parent = node.parentElement;
                const text = (parent.textContent || '').replace(/\s+/g, ' ').trim();
                if (text.includes('训练计划')) break;
                const hasContent = parent.querySelector('a, p, ul, ol') || text.length > headingText.length + 8;
                if (hasContent && parent !== document.body && parent.tagName !== 'MAIN' &&
                    parent.id !== 'app' && parent.id !== 'root' && text.length < 2500) {
                    parent.style.setProperty('display', 'none', 'important');
                    parent.dataset.lpHiddenSection = '1';
                    return;
                }
                node = parent;
            }
            // 找不到独立容器时至少隐藏标题及其紧邻内容,不影响训练计划。
            if (title.isConnected) title.style.setProperty('display', 'none', 'important');
        });
    };

    // “相关链接”是侧边栏中的一个完整 nav-group。
    // 只移除这个分组,不再全局删除同名链接(设置页正文中有正常的帮助中心说明链接)。
    const removeRelatedLinks = () => {
        document.querySelectorAll('nav.sidebar.lside .nav-group').forEach((group) => {
            const title = group.querySelector('.group-title .title, .group-title');
            const label = (title?.textContent || '').replace(/\s+/g, ' ').trim();
            if (label === '相关链接') group.remove();
        });
    };

    const removeSmartRecommendation = () => {
        if (location.pathname !== '/') return;

        const selectors = [
            'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
            '.title', '.header', '[class*="title"]', '[class*="header"]'
        ];
        const seen = new Set();

        document.querySelectorAll(selectors.join(',')).forEach((title) => {
            const label = (title.textContent || '').replace(/\s+/g, ' ').trim();
            if (label !== '智能推荐') return;

            // 只接受明确的卡片/推荐模块容器;遇到训练计划或大布局容器立即停止。
            let node = title;
            for (let depth = 0; depth < 7 && node && node.parentElement; depth++) {
                node = node.parentElement;
                if (node === document.body || node.tagName === 'MAIN' ||
                    node.id === 'app' || node.id === 'root') break;

                const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
                if (!text || text.includes('训练计划') || text.length > 1800) break;

                const cls = typeof node.className === 'string' ? node.className : '';
                const semanticCard = /card|recommend|recommendation|section|panel|block/i.test(cls) ||
                    ['SECTION', 'ARTICLE'].includes(node.tagName);
                const hasBody = node.querySelector('a, p, ul, ol, button');
                const hasOtherSectionTitle = Array.from(
                    node.querySelectorAll('h1,h2,h3,h4,h5,h6,.title,[class*="title"]')
                ).some((other) => other !== title &&
                    (other.textContent || '').replace(/\s+/g, ' ').trim() === '训练计划');

                if (hasOtherSectionTitle) break;
                if (semanticCard && hasBody && !seen.has(node)) {
                    seen.add(node);
                    node.remove();
                    return;
                }
            }

            // 结构无法可靠识别时只隐藏标题,不冒险删除包含其他栏目(尤其训练计划)的父容器。
            if (title.isConnected) title.style.setProperty('display', 'none', 'important');
        });
    };

    const hideHomeSideSections = () => {
        SIDE_FALLBACK_SELECTORS.forEach((sel) => {
            document.querySelectorAll(sel).forEach((el) => {
                if (el.dataset.lpHiddenSection === '1') return;

                el.style.display = 'none';
                el.dataset.lpHiddenSection = '1';
            });
        });

        const SIDE_KEYWORDS = ['本站公告', '友情链接'];

        document.querySelectorAll(
            'h1, h2, h3, h4, h5, h6, [class*="title"], [class*="header"], [class*="Title"], [class*="Header"]'
        ).forEach((title) => {
            const t = (title.textContent || '').trim();

            if (!SIDE_KEYWORDS.includes(t)) return;

            let node = title;
            let container = null;

            while (node && node.parentElement && node !== document.body) {
                if (node.parentElement.matches('.lg-right, .lg-index-benben.lg-right, aside, .lfe-body')) {
                    container = node;
                    break;
                }

                node = node.parentElement;
            }

            if (!container) {
                let p = title.parentElement;

                while (p && p !== document.body) {
                    if (p.tagName === 'DIV' && !isUnsafeContainer(p)) {
                        container = p;
                        break;
                    }

                    p = p.parentElement;
                }
            }

            if (container &&
                !isUnsafeContainer(container) &&
                container.dataset.lpHiddenSection !== '1') {
                container.style.display = 'none';
                container.dataset.lpHiddenSection = '1';
            }
        });
    };

    /* ============================================================
       齿轮
       ============================================================ */
    const GEAR_OVERLAP_RATIO = 0.22;

    const GEAR_CONFIG = {
        w: 640,
        h: 240,
        basePeriod: 12,

        left: {
            start: { x: 80, y: 40 },
            specs: [
                { R: 28, teeth: 8, color: '#6b6b6b' },
                { R: 35, teeth: 10, color: '#4a4a4a' },
                { R: 28, teeth: 8, color: '#6b6b6b' },
                { R: 42, teeth: 12, color: '#4a4a4a' }
            ],
            angles: [50, 140, 50]
        },

        right: {
            start: { x: 560, y: 40 },
            specs: [
                { R: 28, teeth: 8, color: '#6b6b6b' },
                { R: 35, teeth: 10, color: '#4a4a4a' },
                { R: 28, teeth: 8, color: '#6b6b6b' },
                { R: 42, teeth: 12, color: '#4a4a4a' }
            ],
            angles: [130, 40, 130]
        }
    };

    const gearPathD = (teeth) => {
        const R = 100;
        const r = 78;
        const hole = 22;
        const step = 2 * Math.PI / teeth;
        const pts = [];

        for (let i = 0; i < teeth; i++) {
            const a = i * step;
            pts.push([a - 0.09 * step, R]);
            pts.push([a + 0.09 * step, R]);
            pts.push([a + 0.28 * step, r]);
            pts.push([a + 0.72 * step, r]);
        }

        const xy = ([ang, rad]) =>
            `${(Math.cos(ang) * rad).toFixed(2)} ${(Math.sin(ang) * rad).toFixed(2)}`;

        let d = 'M ' + xy(pts[0]);

        for (let i = 1; i < pts.length; i++) {
            d += ' L ' + xy(pts[i]);
        }

        d += ' Z';
        d += ` M ${-hole} 0 A ${hole} ${hole} 0 1 0 ${hole} 0 A ${hole} ${hole} 0 1 0 ${-hole} 0 Z`;

        return d;
    };

    const gearPathCache = new Map();

    const getGearPath = (teeth) => {
        if (!gearPathCache.has(teeth)) {
            gearPathCache.set(teeth, gearPathD(teeth));
        }

        return gearPathCache.get(teeth);
    };

    const buildChain = (config) => {
        const gears = [];
        const first = config.specs[0];

        gears.push({
            x: config.start.x,
            y: config.start.y,
            ...first
        });

        for (let i = 1; i < config.specs.length; i++) {
            const prev = gears[i - 1];
            const cur = config.specs[i];
            const overlap = GEAR_OVERLAP_RATIO * Math.min(prev.R, cur.R);
            const d = prev.R + cur.R - overlap;
            const a = config.angles[i - 1] * Math.PI / 180;

            gears.push({
                x: prev.x + d * Math.cos(a),
                y: prev.y + d * Math.sin(a),
                ...cur
            });
        }

        return gears;
    };

    const computePhase = (gears, basePeriod) => {
        if (gears.length >= 2) {
            const phi01 = Math.atan2(
                gears[1].y - gears[0].y,
                gears[1].x - gears[0].x
            );

            const step0 = 2 * Math.PI / gears[0].teeth;
            gears[0].initAngle = ((phi01 % step0) + step0) % step0;
        } else {
            gears[0].initAngle = 0;
        }

        gears[0].omega = 2 * Math.PI / basePeriod;

        for (let i = 1; i < gears.length; i++) {
            const prev = gears[i - 1];
            const cur = gears[i];

            const phi = Math.atan2(cur.y - prev.y, cur.x - prev.x);
            cur.omega = -prev.omega * prev.teeth / cur.teeth;

            const prevStep = 2 * Math.PI / prev.teeth;
            const prevRel = ((phi - prev.initAngle) % prevStep + prevStep) % prevStep;
            const prevCycle = prevRel / prevStep;
            const curStep = 2 * Math.PI / cur.teeth;

            if (prevCycle > 0.35 && prevCycle < 0.65) {
                cur.initAngle = ((phi + Math.PI) % curStep + curStep) % curStep;
            } else {
                cur.initAngle = ((phi + Math.PI - 0.5 * curStep) % curStep + curStep) % curStep;
            }
        }

        return gears;
    };

    const gearSVG = (teeth, color, R) => {
        const size = R * 2;

        return `<svg viewBox="-100 -100 200 200" width="${size}" height="${size}" style="display:block;overflow:visible">
            <path d="${getGearPath(teeth)}" fill="${color}" fill-rule="evenodd"/>
        </svg>`;
    };

    let gearData = null;

    const initGears = () => {
        if (gearData) return;

        const left = computePhase(
            buildChain(GEAR_CONFIG.left),
            GEAR_CONFIG.basePeriod
        );

        const right = computePhase(
            buildChain(GEAR_CONFIG.right),
            GEAR_CONFIG.basePeriod
        );

        gearData = [...left, ...right];
    };

    const buildGearsHTML = () => {
        initGears();

        return gearData.map((g) => {
            const size = g.R * 2;
            const left = g.x - g.R;
            const top = g.y - g.R;
            const period = 2 * Math.PI / Math.abs(g.omega);

            let initDeg = (g.initAngle * 180 / Math.PI) % 360;
            if (initDeg < 0) initDeg += 360;

            let dir;
            let delay;

            if (g.omega >= 0) {
                dir = 'normal';
                delay = -(initDeg / 360) * period;
            } else {
                dir = 'reverse';
                delay = -((360 - initDeg) / 360) * period;
            }

            return `<div class="lp-gear" style="left:${left}px;top:${top}px;width:${size}px;height:${size}px;animation:lp-spin ${period.toFixed(4)}s linear infinite;animation-direction:${dir};animation-delay:${delay.toFixed(4)}s;">
                ${gearSVG(g.teeth, g.color, g.R)}
            </div>`;
        }).join('');
    };

    const ADS_HTML = `
        <div class="lp-gears-wrap">
            <div class="lp-gears" style="width:${GEAR_CONFIG.w}px;height:${GEAR_CONFIG.h}px;">${buildGearsHTML()}</div>
            <div class="lp-gear-text">专注学习ing...</div>
        </div>`;

    const collectSliders = () => {
        const set = new Set();

        document.querySelectorAll('.am-slider').forEach((s) => set.add(s));

        document.querySelectorAll('.am-slides').forEach((s) => {
            const p = s.closest('.am-slider');
            if (p) set.add(p);
        });

        return set;
    };

    const applyGearScale = (slider) => {
        const gears = slider.querySelector('.lp-gears');
        if (!gears) return;

        const w = slider.clientWidth;
        const h = slider.clientHeight;

        if (w <= 0 || h <= 0) return;

        const s = Math.min(
            w / GEAR_CONFIG.w,
            h / GEAR_CONFIG.h
        ) * 0.94;

        gears.style.transform = `translate(-50%, -50%) scale(${s})`;
    };

    const replaceAds = () => {
        if (location.pathname !== '/') return;

        collectSliders().forEach((slider) => {
            if (slider.dataset.lpAdsReplaced === '1') return;

            const h = slider.offsetHeight;
            if (h <= 0) return;

            slider.innerHTML = ADS_HTML;
            slider.style.setProperty('height', h + 'px', 'important');
            slider.classList.add('lp-ads-replaced');
            slider.dataset.lpAdsReplaced = '1';

            applyGearScale(slider);
        });

        document.querySelectorAll(
            '.lg-ads, #lg-ads, [class*="lg-ads"], ins.adsbygoogle, .adsbygoogle'
        ).forEach((el) => {
            if (el.dataset.lpAdsReplaced === '1') return;

            el.innerHTML = ADS_HTML;
            el.classList.add('lp-ads-replaced');
            el.dataset.lpAdsReplaced = '1';

            applyGearScale(el);
        });
    };

    const onResize = () => {
        document.querySelectorAll('.lp-ads-replaced').forEach((el) => {
            applyGearScale(el);
        });
    };


    /* ============================================================
       玩玩小草:复用“云剪切板”侧边栏项目的原生样式
       ============================================================ */
    const GRASS_MENU_ATTR = 'data-lp-grass-menu';
    const GRASS_PANEL_ID = 'lp-grass-panel';
    const GRASS_GAME_HTML = "<!DOCTYPE html>\n<!-- saved from url=(0043)https://zhangxinagrui.github.io/relaxation/ -->\n<html lang=\"zh-CN\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n  \n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, viewport-fit=cover\">\n  <title>Relaxation</title>\n  <style>\n    * { box-sizing: border-box; margin: 0; padding: 0; }\n    html, body { height: 100%; }\n    body {\n      background: #000000;\n      overflow: hidden;\n      cursor: crosshair;\n      touch-action: none;\n      -webkit-tap-highlight-color: transparent;\n    }\n    canvas { display: block; width: 100%; height: 100%; }\n  </style>\n</head>\n<body>\n<canvas id=\"grass-canvas\" width=\"1667\" height=\"964\" style=\"width: 1667px; height: 964px;\"></canvas>\n\n<script>\n(function () {\n  'use strict';\n\n  const canvas = document.getElementById('grass-canvas');\n  const ctx = canvas.getContext('2d', { alpha: false });\n\n  const CFG = {\n    density: 0.22,\n    minBlades: 150,\n    maxBlades: 420,\n    minHeight: 0.22,\n    maxHeight: 0.78,\n    widthMin: 0.75,\n    widthMax: 1.8,\n    tuftChance: 0.18,\n\n    dt: 1 / 60,\n    gravity: 260,\n    airDrag: 0.996,\n    dragQuad: 0.16,\n    iterations: 4,\n    angleBase: 0.025,\n    bendBase: 0.92,\n    bendTip: 0.07,\n    maxSpeed: 1600,\n\n    windAcc: 5500,\n\n    mouseRadius: 210,\n    mouseWind: 13500,\n    mouseStep: 0.45,\n\n    smokeLifeMin: 1300,\n    smokeLifeMax: 2300,\n    smokeStep: 1.5,\n    maxStepsPerMove: 240,\n    maxSmoke: 1500,\n\n    fireflyCount: 26,\n    fireflyAttractRadius: 240,\n    fireflyAttractProb: 0.06,\n    fireflyUpDamp: 0.45,\n    fireflyTurnEase: 0.035,      // 实际朝向追目标角度的速度(稍提,减少滞后)\n    fireflyDrift: 0.03,\n    fireflyGrassRatio: 0.45,\n\n    shockwaveRadius: 180,\n    shockwaveStrength: 9,\n    shockwaveJitterMin: 0.7,\n    shockwaveJitterMax: 1.3,\n\n    holdThreshold: 2.0,\n    holdSpeedBoost: 4,\n\n    // 新增:全局吸引时目标角度靠向鼠标的速度\n    holdTurnRate: 0.09,\n    // 新增:facing 的低通平滑速度\n    holdFacingEase: 0.05,\n    // 速度过渡平滑\n    speedSmoothUp: 0.06,\n    speedSmoothDown: 0.05,\n\n    meteorIntervalMin: 2500,\n    meteorIntervalMax: 6500,\n    meteorBurstMin: 1,\n    meteorBurstMax: 2\n  };\n\n  const AUTO = /[?&]auto\\b/.test(location.search);\n  let W = 0, H = 0, dpr = 1;\n\n  const pointer = { x: -9999, y: -9999, vx: 0, vy: 0, active: false };\n  let lastMoveTime = 0;\n  let pointerPower = 0;\n  let smoothSpeed = 0;\n  let windLevel = 0;\n\n  let pointerDown = false;\n  let holdTime = 0;\n  let globalAttract = 0;\n\n  function setPointer(x, y) {\n    const now = performance.now();\n    const dtm = Math.max(8, Math.min(90, now - lastMoveTime));\n    lastMoveTime = now;\n    if (pointer.x > -9000) {\n      let vx = ((x - pointer.x) / dtm) * 1000;\n      let vy = ((y - pointer.y) / dtm) * 1000;\n      const sp = Math.sqrt(vx * vx + vy * vy);\n      if (sp > 2600) { vx *= 2600 / sp; vy *= 2600 / sp; }\n      pointer.vx = vx;\n      pointer.vy = vy;\n    }\n    pointer.x = x;\n    pointer.y = y;\n    pointer.active = true;\n  }\n\n  function releasePointer() {\n    pointer.active = false;\n    pointer.vx = 0;\n    pointer.vy = 0;\n    pointer.x = -9999;\n    pointer.y = -9999;\n    trailHistory.length = 0;\n    pointerDown = false;\n  }\n\n  // ---------------- 烟雾 ----------------\n  const smoke = [];\n  const trailHistory = [];\n  const MAX_TRAIL_HISTORY = 4;\n  let overflowPressure = 0;\n\n  const SPRITE_SIZE = 128;\n  const smokeSprite = document.createElement('canvas');\n  smokeSprite.width = SPRITE_SIZE;\n  smokeSprite.height = SPRITE_SIZE;\n  (function makeSmokeSprite() {\n    const c = smokeSprite.getContext('2d');\n    const g = c.createRadialGradient(\n      SPRITE_SIZE / 2, SPRITE_SIZE / 2, 0,\n      SPRITE_SIZE / 2, SPRITE_SIZE / 2, SPRITE_SIZE / 2\n    );\n    g.addColorStop(0, 'rgba(255,255,255,1)');\n    g.addColorStop(0.35, 'rgba(255,255,255,0.55)');\n    g.addColorStop(0.7, 'rgba(255,255,255,0.16)');\n    g.addColorStop(1, 'rgba(255,255,255,0)');\n    c.fillStyle = g;\n    c.fillRect(0, 0, SPRITE_SIZE, SPRITE_SIZE);\n  })();\n\n  function spawnSmoke(x, y) {\n    if (smoke.length >= CFG.maxSmoke * 3) return;\n    const now = performance.now();\n    const spread = 7;\n    smoke.push({\n      x: x + (Math.random() - 0.5) * spread,\n      y: y + (Math.random() - 0.5) * spread,\n      r0: 6 + Math.random() * 9,\n      r1: 24 + Math.random() * 26,\n      life: CFG.smokeLifeMin + Math.random() * (CFG.smokeLifeMax - CFG.smokeLifeMin),\n      birth: now,\n      alpha: 0.09 + Math.random() * 0.08\n    });\n  }\n\n  function trailTo(x, y) {\n    if (trailHistory.length > 0) {\n      const last = trailHistory[trailHistory.length - 1];\n      const ddx = last.x - x;\n      const ddy = last.y - y;\n      if (ddx * ddx + ddy * ddy < 0.25) return;\n    }\n    trailHistory.push({ x, y });\n    if (trailHistory.length > MAX_TRAIL_HISTORY) trailHistory.shift();\n\n    const n = trailHistory.length;\n    if (n < 2) return;\n\n    const pCur = trailHistory[n - 1];\n    const pPrev = trailHistory[n - 2];\n    const pPrevPrev = n >= 3\n      ? trailHistory[n - 3]\n      : { x: 2 * pPrev.x - pCur.x, y: 2 * pPrev.y - pCur.y };\n    const pNext = { x: 2 * pCur.x - pPrev.x, y: 2 * pCur.y - pPrev.y };\n\n    const dx = pCur.x - pPrev.x;\n    const dy = pCur.y - pPrev.y;\n    const dist = Math.sqrt(dx * dx + dy * dy);\n    if (dist < 0.5 || dist > 1500) return;\n\n    const bx0 = pPrev.x, by0 = pPrev.y;\n    const bx1 = pPrev.x + (pCur.x - pPrevPrev.x) / 6;\n    const by1 = pPrev.y + (pCur.y - pPrevPrev.y) / 6;\n    const bx2 = pCur.x - (pNext.x - pPrev.x) / 6;\n    const by2 = pCur.y - (pNext.y - pPrev.y) / 6;\n    const bx3 = pCur.x, by3 = pCur.y;\n\n    const steps = Math.min(CFG.maxStepsPerMove, Math.max(1, Math.ceil(dist / CFG.smokeStep)));\n    for (let i = 1; i <= steps; i++) {\n      const t = i / steps;\n      const mt = 1 - t;\n      const px = mt * mt * mt * bx0 + 3 * mt * mt * t * bx1 + 3 * mt * t * t * bx2 + t * t * t * bx3;\n      const py = mt * mt * mt * by0 + 3 * mt * mt * t * by1 + 3 * mt * t * t * by2 + t * t * t * by3;\n      spawnSmoke(px, py);\n    }\n  }\n\n  // ---------------- 流星 ----------------\n  const meteors = [];\n  let meteorTimer = 0;\n  let meteorInterval = CFG.meteorIntervalMin +\n    Math.random() * (CFG.meteorIntervalMax - CFG.meteorIntervalMin);\n\n  function spawnMeteorBurst() {\n    const count = CFG.meteorBurstMin +\n      Math.floor(Math.random() * (CFG.meteorBurstMax - CFG.meteorBurstMin + 1));\n    const baseAngle = Math.PI * (0.18 + Math.random() * 0.09);\n    const baseX = -80 + Math.random() * (W * 0.55 + 80);\n    const baseY = -80 - Math.random() * 80;\n    const spreadTime = count > 1 ? 140 : 0;\n\n    for (let i = 0; i < count; i++) {\n      const offX = (Math.random() - 0.5) * 360;\n      const offY = (Math.random() - 0.5) * 200;\n      const angle = baseAngle + (Math.random() - 0.5) * (Math.PI * 10 / 180);\n      const speed = 500 + Math.random() * 450;\n      const delay = count > 1 ? i * spreadTime + Math.random() * 80 : 0;\n      meteors.push({\n        x: baseX + offX, y: baseY + offY,\n        vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed,\n        tailLen: 110 + Math.random() * 130,\n        width: 1.1 + Math.random() * 0.9,\n        life: 1.05 + Math.random() * 0.55,\n        age: 0, delay: delay / 1000\n      });\n    }\n  }\n\n  function updateMeteors(dt) {\n    meteorTimer += dt * 1000;\n    if (meteorTimer >= meteorInterval) {\n      meteorTimer = 0;\n      meteorInterval = CFG.meteorIntervalMin +\n        Math.random() * (CFG.meteorIntervalMax - CFG.meteorIntervalMin);\n      spawnMeteorBurst();\n    }\n    for (let i = meteors.length - 1; i >= 0; i--) {\n      const m = meteors[i];\n      if (m.delay > 0) {\n        m.delay -= dt;\n        if (m.delay > 0) continue;\n        m.delay = 0;\n      }\n      m.age += dt;\n      m.x += m.vx * dt;\n      m.y += m.vy * dt;\n      if (m.age >= m.life || m.y > H + 60 || m.x < -150 || m.x > W + 150) {\n        meteors.splice(i, 1);\n      }\n    }\n  }\n\n  function drawMeteors() {\n    const yFadeStart = H * 0.60;\n    const yFadeEnd = H * 0.78;\n    for (let i = 0; i < meteors.length; i++) {\n      const m = meteors[i];\n      if (m.delay > 0) continue;\n      const t = m.age / m.life;\n      let alpha = 1;\n      if (t < 0.08) alpha = t / 0.08;\n      else if (t > 0.70) alpha = Math.pow((1 - t) / 0.30, 1.3);\n      if (alpha <= 0) continue;\n      if (m.y > yFadeStart) {\n        const k = Math.min(1, (m.y - yFadeStart) / (yFadeEnd - yFadeStart));\n        alpha *= Math.pow(1 - k, 1.4);\n        if (alpha <= 0.002) continue;\n      }\n      const sp = Math.sqrt(m.vx * m.vx + m.vy * m.vy) || 1;\n      const ux = m.vx / sp, uy = m.vy / sp;\n      const tailX = m.x - ux * m.tailLen;\n      const tailY = m.y - uy * m.tailLen;\n\n      {\n        const g = ctx.createLinearGradient(m.x, m.y, tailX, tailY);\n        g.addColorStop(0, 'rgba(255,255,255,' + (alpha * 0.10) + ')');\n        g.addColorStop(0.35, 'rgba(255,255,255,' + (alpha * 0.05) + ')');\n        g.addColorStop(0.7, 'rgba(255,255,255,' + (alpha * 0.015) + ')');\n        g.addColorStop(1, 'rgba(255,255,255,0)');\n        ctx.strokeStyle = g; ctx.lineWidth = m.width * 4.0;\n        ctx.lineCap = 'round';\n        ctx.beginPath(); ctx.moveTo(m.x, m.y); ctx.lineTo(tailX, tailY); ctx.stroke();\n      }\n      {\n        const g = ctx.createLinearGradient(m.x, m.y, tailX, tailY);\n        g.addColorStop(0, 'rgba(255,255,255,' + (alpha * 0.38) + ')');\n        g.addColorStop(0.35, 'rgba(255,255,255,' + (alpha * 0.18) + ')');\n        g.addColorStop(0.75, 'rgba(255,255,255,' + (alpha * 0.05) + ')');\n        g.addColorStop(1, 'rgba(255,255,255,0)');\n        ctx.strokeStyle = g; ctx.lineWidth = m.width * 1.9;\n        ctx.beginPath(); ctx.moveTo(m.x, m.y); ctx.lineTo(tailX, tailY); ctx.stroke();\n      }\n      {\n        const g = ctx.createLinearGradient(m.x, m.y, tailX, tailY);\n        g.addColorStop(0, 'rgba(255,255,255,' + (alpha * 1.0) + ')');\n        g.addColorStop(0.25, 'rgba(255,255,255,' + (alpha * 0.85) + ')');\n        g.addColorStop(0.6, 'rgba(255,255,255,' + (alpha * 0.35) + ')');\n        g.addColorStop(1, 'rgba(255,255,255,0)');\n        ctx.strokeStyle = g; ctx.lineWidth = m.width * 0.85;\n        ctx.beginPath(); ctx.moveTo(m.x, m.y); ctx.lineTo(tailX, tailY); ctx.stroke();\n      }\n      {\n        const r = m.width * 9;\n        const g = ctx.createRadialGradient(m.x, m.y, 0, m.x, m.y, r);\n        g.addColorStop(0, 'rgba(255,255,255,' + (alpha * 0.22) + ')');\n        g.addColorStop(0.35, 'rgba(255,255,255,' + (alpha * 0.10) + ')');\n        g.addColorStop(0.7, 'rgba(255,255,255,' + (alpha * 0.03) + ')');\n        g.addColorStop(1, 'rgba(255,255,255,0)');\n        ctx.fillStyle = g; ctx.beginPath(); ctx.arc(m.x, m.y, r, 0, Math.PI * 2); ctx.fill();\n      }\n      {\n        const r = m.width * 4.5;\n        const g = ctx.createRadialGradient(m.x, m.y, 0, m.x, m.y, r);\n        g.addColorStop(0, 'rgba(255,255,255,' + (alpha * 0.55) + ')');\n        g.addColorStop(0.4, 'rgba(255,255,255,' + (alpha * 0.22) + ')');\n        g.addColorStop(0.8, 'rgba(255,255,255,' + (alpha * 0.04) + ')');\n        g.addColorStop(1, 'rgba(255,255,255,0)');\n        ctx.fillStyle = g; ctx.beginPath(); ctx.arc(m.x, m.y, r, 0, Math.PI * 2); ctx.fill();\n      }\n      {\n        const r = m.width * 1.8;\n        const g = ctx.createRadialGradient(m.x, m.y, 0, m.x, m.y, r);\n        g.addColorStop(0, 'rgba(255,255,255,' + (alpha * 1.0) + ')');\n        g.addColorStop(0.5, 'rgba(255,255,255,' + (alpha * 0.55) + ')');\n        g.addColorStop(1, 'rgba(255,255,255,0)');\n        ctx.fillStyle = g; ctx.beginPath(); ctx.arc(m.x, m.y, r, 0, Math.PI * 2); ctx.fill();\n      }\n    }\n    ctx.lineCap = 'butt';\n  }\n\n  // ---------------- 萤火虫 ----------------\n  const fireflies = [];\n  const FF_SPRITE_SIZE = 64;\n  const fireflySprite = document.createElement('canvas');\n  fireflySprite.width = FF_SPRITE_SIZE;\n  fireflySprite.height = FF_SPRITE_SIZE;\n  (function makeFireflySprite() {\n    const c = fireflySprite.getContext('2d');\n    const g = c.createRadialGradient(32, 32, 0, 32, 32, 32);\n    g.addColorStop(0, 'rgba(255,255,255,1)');\n    g.addColorStop(0.12, 'rgba(255,255,255,0.9)');\n    g.addColorStop(0.35, 'rgba(255,255,255,0.3)');\n    g.addColorStop(1, 'rgba(255,255,255,0)');\n    c.fillStyle = g;\n    c.fillRect(0, 0, 64, 64);\n  })();\n\n  function buildFireflies() {\n    fireflies.length = 0;\n    for (let i = 0; i < CFG.fireflyCount; i++) {\n      const angle = Math.random() * Math.PI * 2;\n      let y;\n      if (Math.random() < CFG.fireflyGrassRatio) {\n        y = H * (0.78 + Math.random() * 0.19);\n      } else {\n        y = H * (0.05 + Math.random() * 0.73);\n      }\n      fireflies.push({\n        x: Math.random() * W, y,\n        speed: 0.25 + Math.random() * 0.35,\n        size: 1.2 + Math.random() * 1.5,\n        wanderAngle: angle,\n        targetAngle: angle,\n        blinkSpeed: 0.0008 + Math.random() * 0.0015,\n        phase: Math.random() * Math.PI * 2,\n        kx: 0, ky: 0,\n        shockDecay: 0.92 + Math.random() * 0.04,\n        // 新增:平滑状态\n        smoothFacing: 0,\n        speedSmooth: 1\n      });\n    }\n  }\n\n  function angleLerp(current, target, t) {\n    let diff = target - current;\n    while (diff > Math.PI) diff -= Math.PI * 2;\n    while (diff < -Math.PI) diff += Math.PI * 2;\n    return current + diff * t;\n  }\n\n  function stepFireflies(dt) {\n    const dtf = Math.min(dt * 60, 2);\n    const gA = globalAttract;\n\n    for (let i = 0; i < fireflies.length; i++) {\n      const f = fireflies[i];\n      const heightRatio = Math.min(1, Math.max(0, (H - f.y) / H));\n      const upFactor = 1 - heightRatio * CFG.fireflyUpDamp;\n\n      // 随机漂移\n      const driftMul = 1 - gA * 0.75;\n      let drift = (Math.random() - 0.5) * CFG.fireflyDrift * dtf * driftMul;\n      const nextTarget = f.targetAngle + drift;\n      const wouldGoUp = Math.sin(nextTarget) < 0;\n      if (wouldGoUp && Math.random() > upFactor) drift = 0;\n      f.targetAngle += drift;\n\n      let hasPointerTarget = false;\n\n      if (pointer.active) {\n        const dx = pointer.x - f.x;\n        const dy = pointer.y - f.y;\n        const d2 = dx * dx + dy * dy;\n        const R = CFG.fireflyAttractRadius;\n\n        if (gA > 0.01 && d2 > 16) {\n          // 全局吸引:两级平滑转向\n          const angleToMouse = Math.atan2(dy, dx);\n          // 一级:目标角度连续地靠向鼠标方向(不再按概率跳变)\n          f.targetAngle = angleLerp(\n            f.targetAngle,\n            angleToMouse,\n            CFG.holdTurnRate * gA * dtf\n          );\n          // facing 也做低通平滑,避免 cos 抖动直接传导到速度\n          let angDiff = angleToMouse - f.wanderAngle;\n          while (angDiff > Math.PI) angDiff -= Math.PI * 2;\n          while (angDiff < -Math.PI) angDiff += Math.PI * 2;\n          const rawFacing = (Math.cos(angDiff) + 1) * 0.5; // 0~1\n          f.smoothFacing += (rawFacing - f.smoothFacing) * CFG.holdFacingEase * dtf;\n          hasPointerTarget = true;\n        } else if (d2 < R * R && d2 > 4) {\n          // 局部随机吸引(保留原版手感)\n          const d = Math.sqrt(d2);\n          const prob = (1 - d / R) * CFG.fireflyAttractProb * dtf;\n          if (Math.random() < prob) {\n            f.targetAngle = Math.atan2(dy, dx) + (Math.random() - 0.5) * 1.0;\n          }\n        }\n      }\n\n      if (!hasPointerTarget) {\n        // 没有目标时 facing 平滑回到 0\n        f.smoothFacing += (0 - f.smoothFacing) * 0.04 * dtf;\n      }\n\n      const margin = 12;\n      if (f.x < margin || f.x > W - margin || f.y < margin || f.y > H - margin) {\n        f.targetAngle = Math.atan2(H / 2 - f.y, W / 2 - f.x);\n        f.x = Math.max(margin, Math.min(W - margin, f.x));\n        f.y = Math.max(margin, Math.min(H - margin, f.y));\n      }\n\n      // 二级:实际朝向追目标角度\n      f.wanderAngle = angleLerp(f.wanderAngle, f.targetAngle, CFG.fireflyTurnEase * dtf);\n\n      // 基于平滑 facing 的目标速度,再过一次 speedSmooth\n      let targetSpeedMul = 1;\n      if (hasPointerTarget) {\n        targetSpeedMul = 1 + gA * CFG.holdSpeedBoost * f.smoothFacing;\n      }\n      const ease = targetSpeedMul > f.speedSmooth\n        ? CFG.speedSmoothUp\n        : CFG.speedSmoothDown;\n      f.speedSmooth += (targetSpeedMul - f.speedSmooth) * ease * dtf;\n      if (Math.abs(f.speedSmooth - 1) < 0.005) f.speedSmooth = 1;\n\n      f.x += Math.cos(f.wanderAngle) * f.speed * dtf * f.speedSmooth;\n      f.y += Math.sin(f.wanderAngle) * f.speed * dtf * f.speedSmooth;\n\n      if (f.kx !== 0 || f.ky !== 0) {\n        f.x += f.kx * dtf;\n        f.y += f.ky * dtf;\n        const decay = Math.pow(f.shockDecay, dtf);\n        f.kx *= decay;\n        f.ky *= decay;\n        if (Math.abs(f.kx) < 0.01 && Math.abs(f.ky) < 0.01) {\n          f.kx = 0;\n          f.ky = 0;\n        }\n      }\n    }\n  }\n\n  function drawFireflies(now) {\n    for (let i = 0; i < fireflies.length; i++) {\n      const f = fireflies[i];\n      const blink = 0.25 + 0.75 * (Math.sin(now * f.blinkSpeed + f.phase) * 0.5 + 0.5);\n      const glowSize = f.size * 9;\n      ctx.globalAlpha = blink * 0.75;\n      ctx.drawImage(fireflySprite, f.x - glowSize / 2, f.y - glowSize / 2, glowSize, glowSize);\n    }\n    ctx.globalAlpha = 1;\n  }\n\n  function triggerShockwave(cx, cy) {\n    const R = CFG.shockwaveRadius;\n    const R2 = R * R;\n    const jMin = CFG.shockwaveJitterMin;\n    const jMax = CFG.shockwaveJitterMax;\n    for (let i = 0; i < fireflies.length; i++) {\n      const f = fireflies[i];\n      const dx = f.x - cx, dy = f.y - cy;\n      const d2 = dx * dx + dy * dy;\n      if (d2 < R2 && d2 > 1) {\n        const d = Math.sqrt(d2);\n        const fall = 1 - d / R;\n        const jitter = jMin + Math.random() * (jMax - jMin);\n        const force = CFG.shockwaveStrength * fall * jitter;\n        f.kx += (dx / d) * force;\n        f.ky += (dy / d) * force;\n      }\n    }\n  }\n\n  // ---------------- 草场 ----------------\n  const field = { blades: [], time: 0 };\n  let fogGrad = null;\n  let baseGrad = null;\n\n  function gauss() {\n    return (Math.random() + Math.random() + Math.random() - 1.5) * 0.9;\n  }\n\n  function buildField() {\n    const blades = [];\n    const target = Math.round(Math.min(CFG.maxBlades, Math.max(CFG.minBlades, W * CFG.density)));\n    const tuftCount = Math.max(6, Math.round(W / 150));\n    const tufts = [];\n    for (let i = 0; i < tuftCount; i++) {\n      tufts.push({\n        x: Math.random() * W,\n        spread: 40 + Math.random() * 70,\n        hs: 0.72 + Math.random() * 0.5\n      });\n    }\n    const groundY = H + 10;\n    const span = W + 80;\n\n    for (let k = 0; k < target; k++) {\n      const inTuft = Math.random() < CFG.tuftChance;\n      let bx, hs = 1, tuftX = 0;\n      if (inTuft) {\n        const tf = tufts[(Math.random() * tufts.length) | 0];\n        bx = tf.x + gauss() * tf.spread;\n        hs = tf.hs; tuftX = tf.x;\n      } else {\n        bx = Math.random() * span - 40;\n      }\n      if (bx < -40 || bx > W + 40) continue;\n\n      let hr = (CFG.minHeight + (CFG.maxHeight - CFG.minHeight) * Math.pow(Math.random(), 1.7)) * hs;\n      hr = Math.max(0.06, Math.min(0.62, hr));\n      const h = H * hr;\n      const seg = Math.max(3, Math.min(8, Math.round(h / 16)));\n      const L = h / seg;\n\n      let lean = (Math.random() - 0.5) * 0.34;\n      if (inTuft) lean += Math.max(-1, Math.min(1, (bx - tuftX) / 40)) * 0.22;\n      const droop = Math.random() < 0.3\n        ? (0.45 + Math.random() * 0.5) * (Math.random() < 0.5 ? -1 : 1) : 0;\n      const curl = (Math.random() - 0.5) * 0.75 + droop;\n\n      const nodes = new Array(seg + 1);\n      const relCos = new Float32Array(seg + 1);\n      const relSin = new Float32Array(seg + 1);\n      const bendK = new Float32Array(seg + 1);\n      const wf = new Float32Array(seg + 1);\n      const exposure = new Float32Array(seg + 1);\n      const stiff = 0.8 + Math.random() * 0.45;\n\n      let x = bx, y = groundY;\n      let a = -Math.PI / 2 + lean;\n      let prevA = a;\n\n      for (let i = 0; i <= seg; i++) {\n        const t = i / seg;\n        if (i < seg) {\n          a = -Math.PI / 2 + lean + curl * t * t;\n          if (i > 0) {\n            const rel = a - prevA;\n            relCos[i] = Math.cos(rel);\n            relSin[i] = Math.sin(rel);\n          }\n          prevA = a;\n          wf[i] = Math.pow(1 - t, 0.3);\n          exposure[i] = 0.22 + 0.78 * t * t;\n          const softT = t < 0.55 ? 0 : (t - 0.55) / 0.45;\n          const soft = softT * softT * (3 - 2 * softT);\n          bendK[i] = (CFG.bendBase * (1 - soft) + CFG.bendTip * soft) * stiff;\n        } else {\n          wf[i] = 0; exposure[i] = 1; bendK[i] = 0;\n        }\n        nodes[i] = { x, y, px: x, py: y };\n        if (i < seg) {\n          x += Math.cos(a) * L;\n          y += Math.sin(a) * L;\n        }\n      }\n\n      const depth = h / (H * CFG.maxHeight);\n      const alpha = 0.07 + depth * 0.25 + Math.random() * 0.04;\n\n      const blade = {\n        nodes, seg, L,\n        baseCos: Math.cos(-Math.PI / 2 + lean),\n        baseSin: Math.sin(-Math.PI / 2 + lean),\n        baseK: CFG.angleBase * stiff,\n        relCos, relSin, bendK, wf, exposure,\n        baseW: (CFG.widthMin + Math.random() * (CFG.widthMax - CFG.widthMin)) * (0.72 + depth * 0.45),\n        fill: 'rgba(255,255,255,' + alpha.toFixed(3) + ')',\n        seed: Math.random(),\n        baseX: bx,\n        left: new Array(seg + 1),\n        right: new Array(seg + 1),\n        windX: 0, windY: 0, pwX: 0, pwY: 0\n      };\n      for (let i = 0; i <= seg; i++) {\n        blade.left[i] = { x: 0, y: 0 };\n        blade.right[i] = { x: 0, y: 0 };\n      }\n      blades.push(blade);\n    }\n\n    blades.sort((p, q) => (p.seg * p.L) - (q.seg * q.L));\n    field.blades = blades;\n    field.time = 0;\n  }\n\n  function buildFog() {\n    fogGrad = ctx.createLinearGradient(0, H * 0.55, 0, H);\n    fogGrad.addColorStop(0, 'rgba(255,255,255,0)');\n    fogGrad.addColorStop(0.7, 'rgba(255,255,255,0.012)');\n    fogGrad.addColorStop(1, 'rgba(255,255,255,0.045)');\n\n    baseGrad = ctx.createLinearGradient(0, H - 60, 0, H);\n    baseGrad.addColorStop(0, 'rgba(0,0,0,0)');\n    baseGrad.addColorStop(0.6, 'rgba(0,0,0,0.16)');\n    baseGrad.addColorStop(1, 'rgba(0,0,0,0.55)');\n  }\n\n  function windAt(b, t) {\n    const x = b.baseX;\n    const wave1 = Math.sin(t * 0.55 - x * 0.0022);\n    const wave2 = Math.sin(t * 1.45 - x * 0.0037 + 1.3);\n    const w = 0.62 + 0.34 * wave1 + 0.12 * wave2;\n    const wx = w * CFG.windAcc * (0.94 + b.seed * 0.12) * windLevel;\n    b.windX = wx;\n    b.windY = wx * 0.06;\n  }\n\n  function stepBlades(dt) {\n    const dt2 = dt * dt;\n    const blades = field.blades;\n    const t = field.time;\n    const mr = CFG.mouseRadius;\n    const mr2 = mr * mr;\n    const pActive = pointer.active;\n    const px = pointer.x, py = pointer.y;\n    const pvx = pointer.vx, pvy = pointer.vy;\n    smoothSpeed += (Math.sqrt(pvx * pvx + pvy * pvy) - smoothSpeed) * 0.08;\n    const pSpeed = smoothSpeed;\n    const maxSp = CFG.maxSpeed / 60;\n\n    for (let bi = 0; bi < blades.length; bi++) {\n      const b = blades[bi];\n      const nodes = b.nodes;\n      const seg = b.seg;\n\n      windAt(b, t);\n\n      let pfx = 0, pfy = 0;\n      if (pActive) {\n        const mid = nodes[seg > 1 ? (seg >> 1) : 1];\n        const srcY = py < H ? py : H;\n        const dx = mid.x - px;\n        const dyReal = mid.y - srcY;\n        const d2 = dx * dx + dyReal * dyReal;\n        if (d2 < mr2 && d2 > 1) {\n          const d = Math.sqrt(d2);\n          const fall = 1 - d / mr;\n          const gust = fall * fall * (0.55 + 0.45 * fall);\n          const drive = 1 + Math.min(0.8, pSpeed / 1800);\n          const w = CFG.mouseWind * gust * drive * pointerPower;\n          const dirY = dyReal * 0.4;\n          const dl = Math.sqrt(dx * dx + dirY * dirY) || 1;\n          pfx = (dx / dl) * w;\n          pfy = (dirY / dl) * w;\n          const stepLen = Math.sqrt(pfx * pfx + pfy * pfy) * dt2;\n          const maxStep = b.L * CFG.mouseStep;\n          if (stepLen > 0.0001) {\n            const s = (maxStep * Math.tanh(stepLen / maxStep)) / stepLen;\n            pfx *= s; pfy *= s;\n          }\n        }\n      }\n\n      const curMag = Math.abs(b.pwX) + Math.abs(b.pwY);\n      const newMag = Math.abs(pfx) + Math.abs(pfy);\n      const k = newMag > curMag ? 0.14 : 0.016;\n      b.pwX += (pfx - b.pwX) * k;\n      b.pwY += (pfy - b.pwY) * k;\n      pfx = b.pwX; pfy = b.pwY;\n\n      for (let i = 1; i <= seg; i++) {\n        const n = nodes[i];\n        let ax = b.windX * b.exposure[i] + pfx;\n        let ay = b.windY * b.exposure[i] + CFG.gravity + pfy;\n\n        let vx = (n.x - n.px) * CFG.airDrag;\n        let vy = (n.y - n.py) * CFG.airDrag;\n        const sp = Math.sqrt(vx * vx + vy * vy);\n        if (sp > 0) {\n          const damp = 1 / (1 + CFG.dragQuad * sp);\n          vx *= damp; vy *= damp;\n        }\n        if (sp > maxSp) {\n          const k2 = maxSp / sp;\n          vx *= k2; vy *= k2;\n        }\n        n.px = n.x; n.py = n.y;\n        n.x += vx + ax * dt2;\n        n.y += vy + ay * dt2;\n      }\n\n      for (let it = 0; it < CFG.iterations; it++) {\n        for (let i = 1; i <= seg; i++) {\n          const a = nodes[i - 1], c = nodes[i];\n          const dx = c.x - a.x, dy = c.y - a.y;\n          const d = Math.sqrt(dx * dx + dy * dy) || 0.0001;\n          const diff = (d - b.L) / d;\n          if (i === 1) {\n            const mx = -dx * diff, my = -dy * diff;\n            c.x += mx; c.y += my; c.px += mx; c.py += my;\n          } else {\n            const hx = dx * diff * 0.5, hy = dy * diff * 0.5;\n            a.x += hx; a.y += hy; a.px += hx; a.py += hy;\n            c.x -= hx; c.y -= hy; c.px -= hx; c.py -= hy;\n          }\n        }\n        for (let i = 1; i <= seg; i++) {\n          const a = nodes[i - 1], c = nodes[i];\n          const dx = c.x - a.x, dy = c.y - a.y;\n          const len = Math.sqrt(dx * dx + dy * dy) || 0.0001;\n          const ux = dx / len, uy = dy / len;\n          let rx, ry, kk;\n          if (i === 1) {\n            rx = b.baseCos; ry = b.baseSin; kk = b.baseK;\n          } else {\n            const p = nodes[i - 2];\n            let px2 = a.x - p.x, py2 = a.y - p.y;\n            const pl = Math.sqrt(px2 * px2 + py2 * py2) || 0.0001;\n            px2 /= pl; py2 /= pl;\n            const cr = b.relCos[i - 1], sr = b.relSin[i - 1];\n            rx = px2 * cr - py2 * sr;\n            ry = px2 * sr + py2 * cr;\n            kk = b.bendK[i - 1];\n          }\n          const vx = ux + (rx - ux) * kk;\n          const vy = uy + (ry - uy) * kk;\n          const vl = Math.sqrt(vx * vx + vy * vy) || 1;\n          c.x = a.x + (vx / vl) * len;\n          c.y = a.y + (vy / vl) * len;\n        }\n      }\n\n      for (let i = 1; i <= seg; i++) {\n        const a = nodes[i - 1], c = nodes[i];\n        const dx = c.x - a.x, dy = c.y - a.y;\n        const d = Math.sqrt(dx * dx + dy * dy) || 0.0001;\n        const kk = b.L / d;\n        const nx2 = a.x + dx * kk;\n        const ny2 = a.y + dy * kk;\n        c.px += nx2 - c.x; c.py += ny2 - c.y;\n        c.x = nx2; c.y = ny2;\n      }\n    }\n  }\n\n  function simulate(dt) {\n    field.time += dt;\n    if (windLevel < 1) windLevel += (1 - windLevel) * 0.02;\n\n    if (pointerDown && pointer.active) {\n      holdTime += dt;\n      if (holdTime >= CFG.holdThreshold) {\n        globalAttract += (1 - globalAttract) * 0.06;\n      }\n    } else {\n      holdTime = 0;\n      globalAttract += (0 - globalAttract) * 0.05;\n      if (globalAttract < 0.001) globalAttract = 0;\n    }\n\n    if (AUTO) {\n      const t = field.time;\n      const tx = W * 0.5 + Math.sin(t * 0.5) * W * 0.34;\n      const ty = H * 0.86 + Math.sin(t * 1.13 + 0.6) * H * 0.05;\n      pointer.vx = (tx - pointer.x) * 60;\n      pointer.vy = (ty - pointer.y) * 60;\n      pointer.x = tx; pointer.y = ty;\n      pointer.active = true;\n      if (Math.random() < 0.85) spawnSmoke(tx, ty);\n    }\n\n    stepBlades(dt);\n    stepFireflies(dt);\n    updateMeteors(dt);\n\n    const targetPower = pointer.active ? 1 : 0;\n    const ease = targetPower > pointerPower ? 0.045 : 0.015;\n    pointerPower += (targetPower - pointerPower) * ease;\n    pointer.vx *= 0.9;\n    pointer.vy *= 0.9;\n  }\n\n  // ---------------- 渲染 ----------------\n  const SMOKE_SCALE = 0.4;\n  const smokeLayer = document.createElement('canvas');\n  const sctx = smokeLayer.getContext('2d');\n  let smokeDrawn = false;\n  let smokeTick = 0;\n  let smokeBX0 = 0, smokeBY0 = 0, smokeBX1 = 0, smokeBY1 = 0;\n\n  function resizeSmokeLayer() {\n    smokeLayer.width = Math.max(1, Math.ceil(W * SMOKE_SCALE));\n    smokeLayer.height = Math.max(1, Math.ceil(H * SMOKE_SCALE));\n    smokeDrawn = false;\n  }\n\n  function drawSmoke(now) {\n    smokeTick++;\n    const load = smoke.length / CFG.maxSmoke;\n    const targetPressure = Math.max(0, Math.min(1, (load - 0.5) / 0.5));\n    const pEase = targetPressure > overflowPressure ? 0.15 : 0.05;\n    overflowPressure += (targetPressure - overflowPressure) * pEase;\n\n    if (smokeTick % 2 === 1 || !smokeDrawn) {\n      const lw = smokeLayer.width, lh = smokeLayer.height;\n      sctx.clearRect(0, 0, lw, lh);\n      let any = false;\n      let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;\n      const total = smoke.length;\n\n      for (let i = total - 1; i >= 0; i--) {\n        const p = smoke[i];\n        const ageRank = total > 1 ? i / (total - 1) : 0;\n        const boost = 1 + overflowPressure * 3 * (1 - ageRank);\n        const age = ((now - p.birth) / p.life) * boost;\n        if (age >= 1) { smoke.splice(i, 1); continue; }\n        const r = p.r0 + (p.r1 - p.r0) * age;\n        const fadeIn = Math.min(1, age / 0.15);\n        const alpha = p.alpha * fadeIn * Math.pow(1 - age, 1.7);\n        if (alpha < 0.003) continue;\n        any = true;\n        const x = p.x * SMOKE_SCALE, y = p.y * SMOKE_SCALE, rr = r * SMOKE_SCALE;\n        if (x - rr < x0) x0 = x - rr;\n        if (y - rr < y0) y0 = y - rr;\n        if (x + rr > x1) x1 = x + rr;\n        if (y + rr > y1) y1 = y + rr;\n        sctx.globalAlpha = alpha;\n        sctx.drawImage(smokeSprite, x - rr, y - rr, rr * 2, rr * 2);\n      }\n      sctx.globalAlpha = 1;\n      smokeDrawn = any;\n      if (any) {\n        smokeBX0 = Math.max(0, Math.floor(x0));\n        smokeBY0 = Math.max(0, Math.floor(y0));\n        smokeBX1 = Math.min(lw, Math.ceil(x1));\n        smokeBY1 = Math.min(lh, Math.ceil(y1));\n      }\n    }\n\n    if (smokeDrawn && smokeBX1 > smokeBX0 && smokeBY1 > smokeBY0) {\n      const sw = smokeBX1 - smokeBX0;\n      const sh = smokeBY1 - smokeBY0;\n      ctx.drawImage(\n        smokeLayer,\n        smokeBX0, smokeBY0, sw, sh,\n        smokeBX0 / SMOKE_SCALE, smokeBY0 / SMOKE_SCALE,\n        sw / SMOKE_SCALE, sh / SMOKE_SCALE\n      );\n    }\n  }\n\n  function drawBlades() {\n    const blades = field.blades;\n    const al = renderAlpha;\n    for (let bi = 0; bi < blades.length; bi++) {\n      const b = blades[bi];\n      const nodes = b.nodes;\n      const seg = b.seg;\n      const left = b.left, right = b.right;\n\n      for (let i = 0; i <= seg; i++) {\n        const p = nodes[i];\n        p.ix = p.px + (p.x - p.px) * al;\n        p.iy = p.py + (p.y - p.py) * al;\n      }\n      for (let i = 0; i <= seg; i++) {\n        const p = nodes[i];\n        const a = nodes[i > 0 ? i - 1 : 0];\n        const c = nodes[i < seg ? i + 1 : seg];\n        const dx = c.ix - a.ix, dy = c.iy - a.iy;\n        const len = Math.sqrt(dx * dx + dy * dy) || 1;\n        const nx = -dy / len, ny = dx / len;\n        const halfW = b.baseW * b.wf[i] * 0.5 + 0.35;\n        const l = left[i], r = right[i];\n        l.x = p.ix + nx * halfW; l.y = p.iy + ny * halfW;\n        r.x = p.ix - nx * halfW; r.y = p.iy - ny * halfW;\n      }\n\n      ctx.beginPath();\n      ctx.moveTo(left[0].x, left[0].y);\n      for (let i = 1; i < seg; i++) {\n        const mx = (left[i].x + left[i + 1].x) * 0.5;\n        const my = (left[i].y + left[i + 1].y) * 0.5;\n        ctx.quadraticCurveTo(left[i].x, left[i].y, mx, my);\n      }\n      ctx.lineTo(left[seg].x, left[seg].y);\n      for (let i = seg - 1; i >= 1; i--) {\n        const mx = (right[i].x + right[i - 1].x) * 0.5;\n        const my = (right[i].y + right[i - 1].y) * 0.5;\n        ctx.quadraticCurveTo(right[i].x, right[i].y, mx, my);\n      }\n      ctx.lineTo(right[0].x, right[0].y);\n      ctx.closePath();\n      ctx.fillStyle = b.fill;\n      ctx.fill();\n    }\n  }\n\n  function render(now) {\n    ctx.fillStyle = '#000000';\n    ctx.fillRect(0, 0, W, H);\n    if (fogGrad) {\n      ctx.fillStyle = fogGrad;\n      ctx.fillRect(0, H * 0.55, W, H * 0.45);\n    }\n    drawSmoke(now);\n    drawMeteors();\n    drawFireflies(now);\n    drawBlades();\n    if (baseGrad) {\n      ctx.fillStyle = baseGrad;\n      ctx.fillRect(0, H - 60, W, 60);\n    }\n  }\n\n  function resize() {\n    dpr = Math.min(window.devicePixelRatio || 1, 2);\n    W = window.innerWidth;\n    H = window.innerHeight;\n    canvas.width = Math.floor(W * dpr);\n    canvas.height = Math.floor(H * dpr);\n    canvas.style.width = W + 'px';\n    canvas.style.height = H + 'px';\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    buildField();\n    buildFog();\n    resizeSmokeLayer();\n    buildFireflies();\n    windLevel = 0;\n    for (let i = 0; i < 100; i++) simulate(CFG.dt);\n  }\n  resize();\n\n  let resizeTimer = 0;\n  window.addEventListener('resize', function () {\n    clearTimeout(resizeTimer);\n    resizeTimer = setTimeout(resize, 120);\n  });\n\n  function handlePointerMove(e) {\n    if (typeof e.getCoalescedEvents === 'function') {\n      const events = e.getCoalescedEvents();\n      if (events.length > 0) {\n        for (let i = 0; i < events.length; i++) {\n          trailTo(events[i].clientX, events[i].clientY);\n        }\n        const last = events[events.length - 1];\n        setPointer(last.clientX, last.clientY);\n        return;\n      }\n    }\n    setPointer(e.clientX, e.clientY);\n    trailTo(e.clientX, e.clientY);\n  }\n\n  window.addEventListener('mousemove', handlePointerMove, { passive: true });\n\n  window.addEventListener('mousedown', function (e) {\n    if (e.button !== 0) return;\n    setPointer(e.clientX, e.clientY);\n    triggerShockwave(e.clientX, e.clientY);\n    pointerDown = true;\n    holdTime = 0;\n  });\n\n  window.addEventListener('mouseup', function (e) {\n    if (e.button !== 0) return;\n    pointerDown = false;\n  });\n\n  window.addEventListener('mouseleave', releasePointer);\n\n  window.addEventListener('touchstart', function (e) {\n    const t = e.touches[0];\n    if (t) {\n      setPointer(t.clientX, t.clientY);\n      trailHistory.length = 0;\n      trailHistory.push({ x: t.clientX, y: t.clientY });\n      triggerShockwave(t.clientX, t.clientY);\n      pointerDown = true;\n      holdTime = 0;\n    }\n  }, { passive: true });\n\n  window.addEventListener('touchmove', function (e) {\n    const t = e.touches[0];\n    if (t) {\n      setPointer(t.clientX, t.clientY);\n      trailTo(t.clientX, t.clientY);\n    }\n  }, { passive: true });\n\n  window.addEventListener('touchend', function () {\n    pointerDown = false;\n    releasePointer();\n  });\n  window.addEventListener('touchcancel', function () {\n    pointerDown = false;\n    releasePointer();\n  });\n  window.addEventListener('blur', function () {\n    pointerDown = false;\n    releasePointer();\n  });\n\n  const DT = CFG.dt;\n  let lastTime = 0;\n  let acc = 0;\n  let renderAlpha = 1;\n\n  function frame(now) {\n    if (!lastTime) {\n      lastTime = now;\n      requestAnimationFrame(frame);\n      return;\n    }\n    const delta = Math.min(64, now - lastTime);\n    lastTime = now;\n    acc += delta / 1000;\n    let steps = 0;\n    while (acc >= DT && steps < 3) {\n      simulate(DT);\n      acc -= DT;\n      steps++;\n    }\n    if (steps === 3) acc = 0;\n    renderAlpha = Math.max(0, Math.min(1, acc / DT));\n    render(now);\n    requestAnimationFrame(frame);\n  }\n\n  requestAnimationFrame(frame);\n})();\n</script>\n\n\n</body></html>";

    const openGrassPanel = () => {
        let panel = document.getElementById(GRASS_PANEL_ID);
        if (panel) {
            panel.hidden = false;
            return;
        }

        panel = document.createElement('section');
        panel.id = GRASS_PANEL_ID;
        panel.innerHTML = `
            <div class="lp-grass-head">
                <span>玩玩小草</span>
                <button class="lp-grass-close" type="button" aria-label="关闭">×</button>
            </div>
            <iframe title="玩玩小草" sandbox="allow-scripts"></iframe>
        `;
        document.body.appendChild(panel);

        const frame = panel.querySelector('iframe');
        frame.srcdoc = GRASS_GAME_HTML;
        panel.querySelector('.lp-grass-close').addEventListener('click', () => {
            panel.hidden = true;
        });

        // 只允许从标题栏拖动,避免影响 iframe 内部的草地交互。
        const head = panel.querySelector('.lp-grass-head');
        let dragging = false;
        let startX = 0, startY = 0, startLeft = 0, startTop = 0;

        head.addEventListener('pointerdown', (e) => {
            if (e.target.closest('button')) return;
            dragging = true;
            const rect = panel.getBoundingClientRect();
            startX = e.clientX;
            startY = e.clientY;
            startLeft = rect.left;
            startTop = rect.top;
            panel.style.left = startLeft + 'px';
            panel.style.top = startTop + 'px';
            panel.style.right = 'auto';
            panel.style.bottom = 'auto';
            head.setPointerCapture(e.pointerId);
            e.preventDefault();
        });

        head.addEventListener('pointermove', (e) => {
            if (!dragging) return;
            const maxLeft = Math.max(0, window.innerWidth - panel.offsetWidth);
            const maxTop = Math.max(0, window.innerHeight - panel.offsetHeight);
            panel.style.left = Math.max(0, Math.min(maxLeft, startLeft + e.clientX - startX)) + 'px';
            panel.style.top = Math.max(0, Math.min(maxTop, startTop + e.clientY - startY)) + 'px';
        });

        const stopDragging = () => { dragging = false; };
        head.addEventListener('pointerup', stopDragging);
        head.addEventListener('pointercancel', stopDragging);
    };

    const installGrassMenu = () => {
        if (document.querySelector(`[${GRASS_MENU_ATTR}]`)) return;

        // 优先定位云剪切板项目,并克隆其 li,确保与洛谷原生侧边栏完全同款。
        const candidates = document.querySelectorAll('nav.sidebar.lside .nav-group ul > li, aside nav .nav-group ul > li, nav.sidebar.lside li');
        let reference = null;
        for (const li of candidates) {
            const label = (li.textContent || '').replace(/\s+/g, '').trim();
            if (label.includes('云剪切板') || label.includes('云剪贴板')) {
                reference = li;
                break;
            }
        }
        if (!reference || !reference.parentNode) return;

        const item = reference.cloneNode(true);
        item.setAttribute(GRASS_MENU_ATTR, '1');
        item.classList.add('lp-grass-menu');

        const title = item.querySelector('.title.minor, .title');
        if (title) {
            title.textContent = '玩玩小草';
        } else {
            const aText = item.querySelector('a');
            if (aText) {
                const textNode = [...aText.childNodes].find(n => n.nodeType === Node.TEXT_NODE && n.nodeValue.trim());
                if (textNode) textNode.nodeValue = '玩玩小草';
                else aText.appendChild(document.createTextNode('玩玩小草'));
            }
        }

        // 不显示原项目的图标,只保留原生文字入口样式。
        item.querySelectorAll('svg, i, img, .icon, .nav-icon').forEach(el => el.remove());
        const link = item.querySelector('a');
        if (link) {
            link.removeAttribute('href');
            link.removeAttribute('target');
            link.setAttribute('role', 'button');
            link.style.cursor = 'pointer';
            link.addEventListener('click', (e) => {
                e.preventDefault();
                openGrassPanel();
            });
        } else {
            item.style.cursor = 'pointer';
            item.addEventListener('click', openGrassPanel);
        }

        reference.parentNode.insertBefore(item, reference);
    };

    /* ============================================================
       页面任务
       ============================================================ */
    const runPageTasks = () => {
        if (blocked) return;

        installGrassMenu();
        markBlocked();
        banNamedFeature();
        removeFooterInfo();
        removeRelatedLinks();

        if (location.pathname === '/') {
            removeSmartRecommendation();
            hideBlockedSections();
            hideHomeSideSections();
            replaceAds();
        }
    };

    // 动态页面可能在短时间内连续改动 DOM。采用轻量节流,避免每帧都执行全页扫描。
    let pageTaskTimer = 0;

    const schedulePageTasks = () => {
        if (pageTaskTimer) return;

        pageTaskTimer = setTimeout(() => {
            pageTaskTimer = 0;
            runPageTasks();
        }, 80);
    };

    let resizeFrame = 0;

    const scheduleResize = () => {
        if (resizeFrame) return;

        resizeFrame = requestAnimationFrame(() => {
            resizeFrame = 0;
            onResize();
        });
    };

    const isScriptOwnedNode = (node) => {
        if (!node || node.nodeType !== 1) return false;

        return node.id === OVERLAY_ID ||
            node.id === GRASS_PANEL_ID ||
            node.hasAttribute(GRASS_MENU_ATTR) ||
            node.classList.contains('lp-ads-replaced') ||
            !!node.closest('.lp-ads-replaced, #' + OVERLAY_ID + ', #' + GRASS_PANEL_ID + ', [' + GRASS_MENU_ATTR + ']');
    };

    const hasRelevantMutation = (records) => records.some((record) => {
        if (record.target.nodeType === 1 && isScriptOwnedNode(record.target)) {
            return false;
        }

        // 遮罩层被移除通常意味着 SPA 已离开屏蔽页,需要重新执行页面清理任务。
        for (const node of record.removedNodes) {
            if (node.nodeType === 1 && node.id === OVERLAY_ID) return true;
            if (!isScriptOwnedNode(node)) return true;
        }

        for (const node of record.addedNodes) {
            if (!isScriptOwnedNode(node)) return true;
        }

        return false;
    });

    const startPageEnhancements = () => {
        runPageTasks();

        const ob = new MutationObserver((records) => {
            if (hasRelevantMutation(records)) {
                schedulePageTasks();
            }
        });

        ob.observe(document.body, {
            childList: true,
            subtree: true
        });

        window.addEventListener('resize', scheduleResize, { passive: true });
    };

    if (document.body) {
        startPageEnhancements();
    } else {
        document.addEventListener('DOMContentLoaded', startPageEnhancements, { once: true });
    }
})();

体验 bug 请多多反馈谢谢。

原文