天下苦ChatGPT代码渲染久矣

网页端每次搞个写代码的聊天,聊得一长了,网页就卡成狗。经过我的反复研究,它每次进入聊天都把code blocks全渲染了,这不卡才怪。所以让ChatGPT写了这个油猴脚本,隐藏之前的代码,卡顿会减少很多。ChatGPT网页端写得真是一坨。

// ==UserScript==
// @name         ChatGPT网页端代码显示优化
// @namespace    http://tampermonkey.net/
// @version      2.0
// @description  自动隐藏旧代码块,并提供展开按钮,减少负担,提高流畅度。
// @author       ChatGPT
// @match        https://chatgpt.com/*
// @icon         https://chatgpt.com//favicon.ico
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const MAX_VISIBLE_CODE_BLOCKS = 10; // 只显示最近 N 个代码块
    const CHECK_INTERVAL = 3000; // 每 3 秒检测一次新代码块

    function optimizeCodeBlocks() {
        let codeBlocks = document.querySelectorAll("pre"); // 获取所有代码块
        if (codeBlocks.length <= MAX_VISIBLE_CODE_BLOCKS) return;

        codeBlocks.forEach((codeBlock, index) => {
            if (index < codeBlocks.length - MAX_VISIBLE_CODE_BLOCKS) {
                if (!codeBlock.dataset.optimized) {
                    // 隐藏代码块
                    codeBlock.style.display = "none";

                    // 创建展开按钮
                    let toggleButton = document.createElement("button");
                    toggleButton.textContent = "展开";
                    toggleButton.style.display = "block";
                    toggleButton.style.margin = "5px 0";
                    toggleButton.style.padding = "5px 10px";
                    toggleButton.style.fontSize = "14px";
                    toggleButton.style.cursor = "pointer";
                    toggleButton.style.borderRadius = "4px";
                    toggleButton.style.background = "#707dbc";
                    toggleButton.style.color = "white";
                    toggleButton.style.border = "none";

                    // 展开/折叠代码块
                    toggleButton.addEventListener("click", () => {
                        if (codeBlock.style.display === "none") {
                            codeBlock.style.display = "block";
                            toggleButton.textContent = "折叠代码";
                        } else {
                            codeBlock.style.display = "none";
                            toggleButton.textContent = "展开代码";
                        }
                    });

                    // 插入展开按钮
                    codeBlock.parentNode.insertBefore(toggleButton, codeBlock);

                    codeBlock.dataset.optimized = "true"; // 标记已优化
                }
            }
        });
    }

    // 监听 React 组件变化,确保代码块始终被优化
    const observer = new MutationObserver(optimizeCodeBlocks);
    observer.observe(document.body, { childList: true, subtree: true });

    // 定期检查,防止 React 重新渲染导致优化失效
    setInterval(optimizeCodeBlocks, CHECK_INTERVAL);
})();