跳到正文

个人记录

luogu帖记录工具

Damon77约 98 分钟
原文
文章信息与版本

文章信息

发布
2026年5月3日
收录
2026年5月3日
更新
2026年11月10日
篇幅
约 98 分钟

版本

  1. v2当前
  2. v1
code
代码
// ==UserScript==
// @name         洛谷讨论区回复监控 (可拖拽+主题切换+启停控制)
// @namespace    http://tampermonkey.net/
// @version      4.0
// @description  自动检测洛谷讨论区的新回复,界面可拖拽移动,支持深浅色切换和启停控制
// @author       Assistant
// @match        https://www.luogu.com.cn/*
// @match        https://www.luogu.com/*
// @grant        GM_notification
// @grant        GM_setClipboard
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @grant        unsafeWindow
// @license      MIT
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // ==================== 配置项 ====================
    const CONFIG = {
        CHECK_INTERVAL: 10000,        // 检测间隔(毫秒)
        ENABLE_SOUND: true,           // 是否播放提示音
        ENABLE_NOTIFICATION: true,    // 是否显示浏览器通知
        ENABLE_CLIPBOARD: true,       // 是否自动复制到剪贴板
        DEBUG_MODE: false,            // 调试模式
        MAX_STORED_ITEMS: 500,        // 最大存储条目数
        AUTO_START: true              // 启动时自动开始记录
    };

    // ==================== 主题系统 ====================
    const THEMES = {
        dark: {
            name: '深色',
            icon: '🌙',
            nextIcon: '☀️',
            css: `
                #luogu-monitor-bar {
                    background: #1e1e2e;
                    color: #cdd6f4;
                    box-shadow: 0 -4px 25px rgba(0, 0, 0, 0.5);
                }
                .monitor-header {
                    background: #313244;
                    border-bottom: 1px solid #45475a;
                }
                .monitor-status-indicator {
                    background: #a6e3a1;
                    box-shadow: 0 0 8px rgba(166, 227, 161, 0.5);
                }
                .monitor-status-indicator.stopped {
                    background: #f38ba8;
                    box-shadow: 0 0 8px rgba(243, 139, 168, 0.5);
                }
                .monitor-title { color: #cdd6f4; }
                .monitor-count {
                    background: #cba6f7;
                    color: #1e1e2e;
                }
                .monitor-btn {
                    background: #45475a;
                    color: #cdd6f4;
                }
                .monitor-btn:hover { background: #585b70; }
                .monitor-btn.recording {
                    background: #a6e3a1;
                    color: #1e1e2e;
                    animation: pulse-dark 2s infinite;
                }
                .monitor-btn.stopped {
                    background: #f38ba8;
                    color: #1e1e2e;
                }
                .monitor-content { background: #1e1e2e; }
                .monitor-item {
                    background: #313244;
                    border: 1px solid #45475a;
                }
                .monitor-item.clipboard-failed {
                    border-left: 3px solid #f38ba8;
                }
                .monitor-item-time { color: #a6adc8; }
                .monitor-item-text { color: #cdd6f4; }
                .monitor-item-copy {
                    background: #585b70;
                    color: #cdd6f4;
                }
                .monitor-item-copy:hover { background: #6c7086; }
                .monitor-retry {
                    background: #f38ba8;
                    color: #1e1e2e;
                }
                .monitor-retry button {
                    background: #1e1e2e;
                    color: #f38ba8;
                }
                .monitor-drag-handle { color: #6c7086; }
                .monitor-drag-handle:hover { color: #cdd6f4; }
                .monitor-content::-webkit-scrollbar-thumb { background: #585b70; }
                .monitor-content::-webkit-scrollbar-track { background: #313244; }
                .theme-switch-btn { background: #45475a; color: #f9e2af; }
                .theme-switch-btn:hover { background: #585b70; }
            `
        },
        light: {
            name: '浅色',
            icon: '☀️',
            nextIcon: '🌙',
            css: `
                #luogu-monitor-bar {
                    background: #ffffff;
                    color: #2c3e50;
                    box-shadow: 0 -4px 25px rgba(0, 0, 0, 0.15);
                }
                .monitor-header {
                    background: #f8f9fa;
                    border-bottom: 1px solid #dee2e6;
                }
                .monitor-status-indicator {
                    background: #27ae60;
                    box-shadow: 0 0 8px rgba(39, 174, 96, 0.3);
                }
                .monitor-status-indicator.stopped {
                    background: #e74c3c;
                    box-shadow: 0 0 8px rgba(231, 76, 60, 0.3);
                }
                .monitor-title { color: #2c3e50; }
                .monitor-count {
                    background: #3498db;
                    color: #ffffff;
                }
                .monitor-btn {
                    background: #e9ecef;
                    color: #495057;
                }
                .monitor-btn:hover { background: #dee2e6; }
                .monitor-btn.recording {
                    background: #27ae60;
                    color: #ffffff;
                    animation: pulse-light 2s infinite;
                }
                .monitor-btn.stopped {
                    background: #e74c3c;
                    color: #ffffff;
                }
                .monitor-content { background: #ffffff; }
                .monitor-item {
                    background: #f8f9fa;
                    border: 1px solid #e9ecef;
                }
                .monitor-item.clipboard-failed {
                    border-left: 3px solid #e74c3c;
                }
                .monitor-item-time { color: #6c757d; }
                .monitor-item-text { color: #2c3e50; }
                .monitor-item-copy {
                    background: #3498db;
                    color: #ffffff;
                }
                .monitor-item-copy:hover { background: #2980b9; }
                .monitor-retry {
                    background: #e74c3c;
                    color: #ffffff;
                }
                .monitor-retry button {
                    background: #ffffff;
                    color: #e74c3c;
                }
                .monitor-drag-handle { color: #adb5bd; }
                .monitor-drag-handle:hover { color: #495057; }
                .monitor-content::-webkit-scrollbar-thumb { background: #ced4da; }
                .monitor-content::-webkit-scrollbar-track { background: #f8f9fa; }
                .theme-switch-btn { background: #e9ecef; color: #f39c12; }
                .theme-switch-btn:hover { background: #dee2e6; }
            `
        }
    };

    let currentTheme = 'dark';

    // ==================== 记录状态管理 ====================
    const STORAGE_KEY = 'luogu_comment_monitor_v4';
    const FAILED_KEY = 'luogu_failed_clipboards_v4';
    const POSITION_KEY = 'luogu_monitor_position';
    const STATE_KEY = 'luogu_monitor_state';  // 新增:保存启停状态

    let processedComments = new Set();
    let failedClipboards = [];
    let isRecording = true;  // 是否正在记录
    let checkIntervalId = null;  // 定时器ID

    function loadState() {
        try {
            const saved = GM_getValue(STORAGE_KEY, '[]');
            processedComments = new Set(JSON.parse(saved));

            const failed = GM_getValue(FAILED_KEY, '[]');
            failedClipboards = JSON.parse(failed);

            currentTheme = getTheme();

            // 加载记录状态
            const savedState = GM_getValue(STATE_KEY, null);
            if (savedState !== null) {
                isRecording = savedState;
            } else {
                isRecording = CONFIG.AUTO_START;
            }
        } catch (e) {
            console.warn('[洛谷监控] 加载状态失败:', e);
            processedComments = new Set();
            failedClipboards = [];
            currentTheme = 'dark';
            isRecording = CONFIG.AUTO_START;
        }
    }

    function saveState() {
        GM_setValue(STORAGE_KEY, JSON.stringify([...processedComments]));
        GM_setValue(FAILED_KEY, JSON.stringify(failedClipboards.slice(-20)));
        GM_setValue(STATE_KEY, isRecording);
        saveTheme(currentTheme);
    }

    // ==================== 主题管理 ====================
    function getTheme() {
        try {
            const saved = GM_getValue('luogu_monitor_theme', 'dark');
            return THEMES[saved] ? saved : 'dark';
        } catch (e) {
            return 'dark';
        }
    }

    function saveTheme(theme) {
        GM_setValue('luogu_monitor_theme', theme);
    }

    function switchTheme() {
        currentTheme = currentTheme === 'dark' ? 'light' : 'dark';
        applyTheme();
        saveTheme(currentTheme);
        updateThemeButton();
    }

    function applyTheme() {
        const existingStyle = document.getElementById('luogu-monitor-theme');
        if (existingStyle) {
            existingStyle.remove();
        }

        const themeStyle = document.createElement('style');
        themeStyle.id = 'luogu-monitor-theme';
        themeStyle.textContent = THEMES[currentTheme].css;
        document.head.appendChild(themeStyle);
    }

    function updateThemeButton() {
        const btn = document.getElementById('monitor-theme-btn');
        if (btn) {
            const theme = THEMES[currentTheme];
            btn.textContent = theme.icon;
            btn.title = `切换到${currentTheme === 'dark' ? '浅色' : '深色'}模式`;
        }
    }

    // ==================== 拖拽系统 ====================
    let dragState = {
        isDragging: false,
        startX: 0,
        startY: 0,
        startLeft: 0,
        startTop: 0,
        currentLeft: null,
        currentTop: null
    };

    function loadPosition() {
        try {
            const saved = GM_getValue(POSITION_KEY, null);
            if (saved) {
                const pos = JSON.parse(saved);
                dragState.currentLeft = pos.left;
                dragState.currentTop = pos.top;
            }
        } catch (e) {
            dragState.currentLeft = null;
            dragState.currentTop = null;
        }
    }

    function savePosition(left, top) {
        GM_setValue(POSITION_KEY, JSON.stringify({ left, top }));
    }

    function initDragSystem() {
        const bar = document.getElementById('luogu-monitor-bar');
        if (!bar) return;

        const header = bar.querySelector('.monitor-header');
        if (!header) return;

        if (dragState.currentLeft !== null && dragState.currentTop !== null) {
            bar.style.right = 'auto';
            bar.style.bottom = 'auto';
            bar.style.left = dragState.currentLeft + 'px';
            bar.style.top = dragState.currentTop + 'px';
        } else {
            bar.style.right = '0';
            bar.style.bottom = '0';
            bar.style.left = 'auto';
            bar.style.top = 'auto';
        }

        header.addEventListener('mousedown', startDrag);
        document.addEventListener('mousemove', onDrag);
        document.addEventListener('mouseup', stopDrag);
        header.addEventListener('touchstart', startDragTouch, { passive: false });
        document.addEventListener('touchmove', onDragTouch, { passive: false });
        document.addEventListener('touchend', stopDragTouch);
    }

    function startDrag(e) {
        if (e.target.closest('button, .monitor-btn, .theme-switch-btn, .monitor-control-btn')) return;
        if (e.target.closest('.monitor-status-indicator')) return;

        const bar = document.getElementById('luogu-monitor-bar');
        const rect = bar.getBoundingClientRect();

        dragState.isDragging = true;
        dragState.startX = e.clientX;
        dragState.startY = e.clientY;
        dragState.startLeft = rect.left;
        dragState.startTop = rect.top;

        bar.style.transition = 'none';
        bar.style.right = 'auto';
        bar.style.bottom = 'auto';
        bar.style.left = rect.left + 'px';
        bar.style.top = rect.top + 'px';
        bar.style.cursor = 'grabbing';

        e.preventDefault();
    }

    function onDrag(e) {
        if (!dragState.isDragging) return;

        const deltaX = e.clientX - dragState.startX;
        const deltaY = e.clientY - dragState.startY;

        let newLeft = dragState.startLeft + deltaX;
        let newTop = dragState.startTop + deltaY;

        const bar = document.getElementById('luogu-monitor-bar');
        const barWidth = bar.offsetWidth;
        const barHeight = bar.offsetHeight;
        const maxLeft = window.innerWidth - barWidth;
        const maxTop = window.innerHeight - barHeight;

        newLeft = Math.max(0, Math.min(newLeft, maxLeft));
        newTop = Math.max(0, Math.min(newTop, maxTop));

        bar.style.left = newLeft + 'px';
        bar.style.top = newTop + 'px';

        dragState.currentLeft = newLeft;
        dragState.currentTop = newTop;
    }

    function stopDrag() {
        if (!dragState.isDragging) return;

        const bar = document.getElementById('luogu-monitor-bar');
        bar.style.transition = '';
        bar.style.cursor = '';

        dragState.isDragging = false;

        if (dragState.currentLeft !== null && dragState.currentTop !== null) {
            savePosition(dragState.currentLeft, dragState.currentTop);
        }
    }

    function startDragTouch(e) {
        if (e.target.closest('button, .monitor-btn, .theme-switch-btn, .monitor-control-btn')) return;
        if (e.target.closest('.monitor-status-indicator')) return;
        if (e.touches.length !== 1) return;

        const touch = e.touches[0];
        const bar = document.getElementById('luogu-monitor-bar');
        const rect = bar.getBoundingClientRect();

        dragState.isDragging = true;
        dragState.startX = touch.clientX;
        dragState.startY = touch.clientY;
        dragState.startLeft = rect.left;
        dragState.startTop = rect.top;

        bar.style.transition = 'none';
        bar.style.right = 'auto';
        bar.style.bottom = 'auto';
        bar.style.left = rect.left + 'px';
        bar.style.top = rect.top + 'px';

        e.preventDefault();
    }

    function onDragTouch(e) {
        if (!dragState.isDragging) return;
        if (e.touches.length !== 1) return;

        const touch = e.touches[0];
        const deltaX = touch.clientX - dragState.startX;
        const deltaY = touch.clientY - dragState.startY;

        let newLeft = dragState.startLeft + deltaX;
        let newTop = dragState.startTop + deltaY;

        const bar = document.getElementById('luogu-monitor-bar');
        const maxLeft = window.innerWidth - bar.offsetWidth;
        const maxTop = window.innerHeight - bar.offsetHeight;

        newLeft = Math.max(0, Math.min(newLeft, maxLeft));
        newTop = Math.max(0, Math.min(newTop, maxTop));

        bar.style.left = newLeft + 'px';
        bar.style.top = newTop + 'px';

        dragState.currentLeft = newLeft;
        dragState.currentTop = newTop;

        e.preventDefault();
    }

    function stopDragTouch() {
        if (!dragState.isDragging) return;

        const bar = document.getElementById('luogu-monitor-bar');
        bar.style.transition = '';
        bar.style.cursor = '';

        dragState.isDragging = false;

        if (dragState.currentLeft !== null && dragState.currentTop !== null) {
            savePosition(dragState.currentLeft, dragState.currentTop);
        }
    }

    function handleResize() {
        const bar = document.getElementById('luogu-monitor-bar');
        if (!bar || dragState.currentLeft === null) return;

        const maxLeft = window.innerWidth - bar.offsetWidth;
        const maxTop = window.innerHeight - bar.offsetHeight;

        if (dragState.currentLeft > maxLeft) {
            dragState.currentLeft = maxLeft;
            bar.style.left = maxLeft + 'px';
        }
        if (dragState.currentTop > maxTop) {
            dragState.currentTop = maxTop;
            bar.style.top = maxTop + 'px';
        }
    }

    // ==================== 剪贴板操作 (四重降级) ====================
    async function safeClipboardWrite(text) {
        if (!CONFIG.ENABLE_CLIPBOARD) return 'disabled';

        let success = false;
        let method = '';

        try {
            await GM_setClipboard(text, { type: 'text', mimetype: 'text/plain' });
            success = true;
            method = 'GM_setClipboard';
        } catch (e) {
            debugLog('GM_setClipboard 失败:', e.message);
        }

        if (!success) {
            try {
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    await navigator.clipboard.writeText(text);
                    success = true;
                    method = 'navigator.clipboard';
                }
            } catch (e) {
                debugLog('navigator.clipboard 失败:', e.message);
            }
        }

        if (!success) {
            try {
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.cssText = `
                    position: fixed; top: 0; left: 0; width: 2em; height: 2em;
                    padding: 0; border: none; outline: none; box-shadow: none;
                    background: transparent; opacity: 0; pointer-events: none;
                `;
                document.body.appendChild(textarea);
                textarea.focus();
                textarea.select();
                const copySuccess = document.execCommand('copy');
                document.body.removeChild(textarea);
                if (copySuccess) {
                    success = true;
                    method = 'execCommand';
                }
            } catch (e) {
                debugLog('execCommand 失败:', e.message);
            }
        }

        if (!success) {
            try {
                if (navigator.clipboard && navigator.clipboard.write) {
                    const blob = new Blob([text], { type: 'text/plain' });
                    const item = new ClipboardItem({ 'text/plain': blob });
                    await navigator.clipboard.write([item]);
                    success = true;
                    method = 'ClipboardItem';
                }
            } catch (e) {
                debugLog('ClipboardItem 失败:', e.message);
            }
        }

        if (!success) {
            debugLog('所有剪贴板方法均失败,保存到本地存储');
            failedClipboards.push({
                text: text,
                timestamp: new Date().toISOString(),
                url: window.location.href
            });
            saveState();
            return 'failed';
        }

        debugLog(`剪贴板写入成功,使用方法: ${method}`);
        return method;
    }

    // ==================== 状态栏 ====================
    let statusBar = null;
    let statusBarContent = [];
    let isStatusBarCollapsed = false;

    function ensureStatusBar() {
        if (statusBar) return;

        statusBar = document.createElement('div');
        statusBar.id = 'luogu-monitor-bar';
        statusBar.innerHTML = `
            <div class="monitor-header">
                <div class="monitor-drag-handle" title="拖拽移动">⋮⋮</div>
                <div class="monitor-status-indicator ${isRecording ? '' : 'stopped'}"
                     id="monitor-status-indicator"
                     title="${isRecording ? '正在记录' : '已停止记录'}"></div>
                <span class="monitor-title">📋 洛谷回复监控</span>
                <div class="monitor-controls">
                    <span class="monitor-count" id="monitor-count">0</span>
                    <button class="monitor-btn monitor-control-btn" id="monitor-view" title="查看所有记录">📄</button>
                    <button class="monitor-btn monitor-control-btn" id="monitor-copy-last" title="复制最新记录">📋</button>
                    <button class="monitor-btn monitor-control-btn" id="monitor-clear" title="清除记录">🗑️</button>
                    <button class="monitor-btn theme-switch-btn" id="monitor-theme-btn" title="切换主题">🌙</button>
                    <button class="monitor-btn monitor-control-btn" id="monitor-toggle" title="折叠/展开">▼</button>
                </div>
            </div>
            <div class="monitor-content" id="monitor-content"></div>
            <div class="monitor-footer">
                <div class="monitor-retry" id="monitor-retry" style="display:none;">
                    ⚠️ 剪贴板写入失败,<button id="monitor-retry-btn">点击此处重试</button>
                </div>
                <div class="monitor-record-controls">
                    <button class="monitor-btn record-btn" id="monitor-record-btn">
                        ${isRecording ? '⏹️ 停止记录' : '▶️ 开始记录'}
                    </button>
                    <span class="monitor-record-status" id="monitor-record-status">
                        ${isRecording ? '🟢 监控中...' : '🔴 已暂停'}
                    </span>
                </div>
            </div>
        `;
        document.body.appendChild(statusBar);

        // 绑定事件
        document.getElementById('monitor-toggle').addEventListener('click', toggleStatusBar);
        document.getElementById('monitor-clear').addEventListener('click', clearStatusBar);
        document.getElementById('monitor-copy-last').addEventListener('click', copyLastItem);
        document.getElementById('monitor-view').addEventListener('click', viewAllItems);
        document.getElementById('monitor-theme-btn').addEventListener('click', switchTheme);
        document.getElementById('monitor-record-btn').addEventListener('click', toggleRecording);

        const retryBtn = document.getElementById('monitor-retry-btn');
        if (retryBtn) retryBtn.addEventListener('click', retryFailedClipboard);

        updateStatusBarCount();
        updateThemeButton();
        updateRecordButton();
        updateStatusIndicator();
    }

    function toggleRecording() {
        isRecording = !isRecording;
        updateRecordButton();
        updateStatusIndicator();
        saveState();

        if (isRecording) {
            showToast('▶️ 开始记录新回复', 'success');
            // 重新建立基准,避免触发旧回复
            const currentComments = parseComments();
            currentComments.forEach(c => processedComments.add(c.id));
            saveState();
        } else {
            showToast('⏹️ 已停止记录', 'warning');
        }
    }

    function updateRecordButton() {
        const btn = document.getElementById('monitor-record-btn');
        if (btn) {
            btn.innerHTML = isRecording ? '⏹️ 停止记录' : '▶️ 开始记录';
            btn.className = `monitor-btn record-btn ${isRecording ? 'recording' : 'stopped'}`;
            btn.title = isRecording ? '停止监控新回复' : '开始监控新回复';
        }

        const status = document.getElementById('monitor-record-status');
        if (status) {
            status.innerHTML = isRecording ? '🟢 监控中...' : '🔴 已暂停';
        }
    }

    function updateStatusIndicator() {
        const indicator = document.getElementById('monitor-status-indicator');
        if (indicator) {
            if (isRecording) {
                indicator.classList.remove('stopped');
                indicator.title = '正在记录';
            } else {
                indicator.classList.add('stopped');
                indicator.title = '已停止记录';
            }
        }
    }

    function addToStatusBar(text, isClipboardFailed = false) {
        ensureStatusBar();

        statusBarContent.push({
            text: text,
            time: new Date().toLocaleString('zh-CN'),
            clipboardFailed: isClipboardFailed,
            isRecording: isRecording  // 记录当时的状态
        });

        if (statusBarContent.length > CONFIG.MAX_STORED_ITEMS) {
            statusBarContent.shift();
        }

        updateStatusBarDisplay();

        if (isClipboardFailed) {
            const retryDiv = document.getElementById('monitor-retry');
            if (retryDiv) retryDiv.style.display = 'block';
        }
    }

    function updateStatusBarDisplay() {
        const contentDiv = document.getElementById('monitor-content');
        if (!contentDiv) return;

        const latest = statusBarContent.slice(-5).reverse();
        contentDiv.innerHTML = latest.map((item, index) => `
            <div class="monitor-item ${item.clipboardFailed ? 'clipboard-failed' : ''}">
                <div class="monitor-item-time">
                    ${item.time}
                    ${!item.isRecording ? '<span class="paused-badge">已暂停</span>' : ''}
                </div>
                <div class="monitor-item-text">${escapeHtml(item.text.substring(0, 200))}${item.text.length > 200 ? '...' : ''}</div>
                <button class="monitor-item-copy" data-index="${statusBarContent.length - 1 - index}">复制</button>
            </div>
        `).join('');

        contentDiv.querySelectorAll('.monitor-item-copy').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const index = parseInt(e.target.dataset.index);
                if (statusBarContent[index]) {
                    safeClipboardWrite(statusBarContent[index].text);
                    showToast('✅ 已复制到剪贴板', 'success');
                }
            });
        });

        updateStatusBarCount();
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function updateStatusBarCount() {
        const countElement = document.getElementById('monitor-count');
        if (countElement) {
            countElement.textContent = statusBarContent.length;
        }
    }

    function toggleStatusBar() {
        const content = document.getElementById('monitor-content');
        const footer = document.querySelector('.monitor-footer');
        const toggle = document.getElementById('monitor-toggle');
        isStatusBarCollapsed = !isStatusBarCollapsed;

        if (isStatusBarCollapsed) {
            content.style.display = 'none';
            if (footer) footer.style.display = 'none';
            toggle.textContent = '▶';
        } else {
            content.style.display = 'block';
            if (footer) footer.style.display = 'block';
            toggle.textContent = '▼';
        }
    }

    function clearStatusBar() {
        if (statusBarContent.length > 0) {
            if (confirm(`确定要清除所有 ${statusBarContent.length} 条记录吗?\n清除后可以继续记录新回复。`)) {
                statusBarContent = [];
                processedComments.clear();  // 清除已处理记录,允许重新记录
                updateStatusBarDisplay();
                const retryDiv = document.getElementById('monitor-retry');
                if (retryDiv) retryDiv.style.display = 'none';
                saveState();
                showToast('✅ 记录已清除,可以重新记录', 'success');
            }
        } else {
            showToast('📭 没有可清除的记录', 'info');
        }
    }

    function copyLastItem() {
        if (statusBarContent.length > 0) {
            safeClipboardWrite(statusBarContent[statusBarContent.length - 1].text);
            showToast('✅ 已复制最新记录', 'success');
        } else {
            showToast('⚠️ 暂无记录', 'warning');
        }
    }

    function viewAllItems() {
        const isDark = currentTheme === 'dark';

        const win = window.open('', '', 'width=800,height=600');
        win.document.write(`
            <html>
            <head>
                <title>洛谷回复监控 - 历史记录</title>
                <style>
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    body {
                        font-family: 'Segoe UI', system-ui, sans-serif;
                        padding: 20px;
                        background: ${isDark ? '#1e1e2e' : '#f5f5f5'};
                        color: ${isDark ? '#cdd6f4' : '#2c3e50'};
                    }
                    h1 { margin-bottom: 10px; }
                    .subtitle { color: ${isDark ? '#a6adc8' : '#6c757d'}; margin-bottom: 20px; }
                    .item {
                        background: ${isDark ? '#313244' : '#ffffff'};
                        margin: 10px 0;
                        padding: 15px;
                        border-radius: 8px;
                        border: 1px solid ${isDark ? '#45475a' : '#dee2e6'};
                    }
                    .time {
                        color: ${isDark ? '#a6adc8' : '#6c757d'};
                        font-size: 12px;
                        display: flex;
                        align-items: center;
                        gap: 8px;
                    }
                    .text { margin-top: 8px; white-space: pre-wrap; font-size: 13px; }
                    .failed { border-left: 3px solid ${isDark ? '#f38ba8' : '#e74c3c'}; }
                    .paused {
                        background: ${isDark ? '#f38ba8' : '#e74c3c'};
                        color: white;
                        padding: 1px 6px;
                        border-radius: 3px;
                        font-size: 10px;
                    }
                    .export-btn {
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        padding: 10px 20px;
                        background: ${isDark ? '#cba6f7' : '#3498db'};
                        color: ${isDark ? '#1e1e2e' : '#ffffff'};
                        border: none;
                        border-radius: 6px;
                        cursor: pointer;
                        font-size: 14px;
                    }
                </style>
            </head>
            <body>
                <h1>📋 洛谷回复监控记录</h1>
                <p class="subtitle">共 ${statusBarContent.length} 条记录 | 当前状态: ${isRecording ? '🟢 记录中' : '🔴 已暂停'}</p>
                <button class="export-btn" onclick="exportToClipboard()">📋 导出全部到剪贴板</button>
                ${statusBarContent.map(item => `
                    <div class="item ${item.clipboardFailed ? 'failed' : ''}">
                        <div class="time">
                            ${item.time}
                            ${!item. isRecording ? '<span class="paused">已暂停</span>' : ''}
                            ${item.clipboardFailed ? ' ⚠ 剪贴板失败' : ''}
                        </div>
                        <div class="text">${escapeHtml(item.text)}</div>
                    </div>
                `).join('')}
                <script>
                    function exportToClipboard() {
                        const allText = ${JSON.stringify(statusBarContent.map(item => item.text).join('\n\n---\n\n'))};
                        navigator.clipboard.writeText(allText).then(() => {
                            alert('✅ 已导出全部记录到剪贴板');
                        }).catch(() => {
                            alert('❌ 导出失败,请手动复制');
                        });
                    }
                <\/script>
            </body>
            </html>
        `);
    }

    async function retryFailedClipboard() {
        if (failedClipboards.length === 0) {
            document.getElementById('monitor-retry').style.display = 'none';
            return;
        }

        const latest = failedClipboards[failedClipboards.length - 1];
        const result = await safeClipboardWrite(latest.text);

        if (result !== 'failed') {
            failedClipboards = [];
            saveState();
            const retryDiv = document.getElementById('monitor-retry');
            if (retryDiv) retryDiv.style.display = 'none';
            showToast('✅ 剪贴板重试成功!', 'success');
        } else {
            showToast('❌ 重试失败,请手动复制状态栏内容', 'error');
        }
    }

    // ==================== Toast 提示 ====================
    let toastTimer = null;

    function showToast(message, type = 'info') {
        const oldToast = document.querySelector('.luogu-monitor-toast');
        if (oldToast) oldToast.remove();
        if (toastTimer) clearTimeout(toastTimer);

        const toast = document.createElement('div');
        toast.className = 'luogu-monitor-toast';

        const isDark = currentTheme === 'dark';
        const colors = {
            success: isDark
                ? 'linear-gradient(135deg, #40a02b 0%, #a6e3a1 100%)'
                : 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)',
            error: isDark
                ? 'linear-gradient(135deg, #d20f39 0%, #f38ba8 100%)'
                : 'linear-gradient(135deg, #eb3349 0%, #f45c43 100%)',
            warning: isDark
                ? 'linear-gradient(135deg, #df8e1d 0%, #f9e2af 100%)'
                : 'linear-gradient(135deg, #f2994a 0%, #f2c94c 100%)',
            info: isDark
                ? 'linear-gradient(135deg, #1e66f5 0%, #89b4fa 100%)'
                : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
        };

        toast.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: ${colors[type] || colors.info};
            color: white;
            padding: 12px 24px;
            border-radius: 12px;
            font-size: 14px;
            font-family: 'Segoe UI', system-ui, sans-serif;
            z-index: 100000;
            animation: monitorToastIn 0.3s ease;
            box-shadow: 0 8px 32px rgba(0,0,0,0.2);
            white-space: nowrap;
        `;
        toast.textContent = message;
        document.body.appendChild(toast);

        toastTimer = setTimeout(() => {
            toast.style.animation = 'monitorToastOut 0.3s ease forwards';
            setTimeout(() => toast.remove(), 300);
        }, 2500);
    }

    // ==================== 核心检测逻辑 ====================
    function debugLog(...args) {
        if (CONFIG.DEBUG_MODE) console.log('[洛谷监控]', ...args);
    }

    function generateCommentHash(commentData) {
        const str = `${commentData.username}|${commentData.time}|${commentData.content.substring(0, 100)}`;
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash |= 0;
        }
        return 'comment_' + Math.abs(hash);
    }

    function cleanContent(content) {
        return content
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&#39;/g, "'")
            .replace(/\s+/g, ' ')
            .trim();
    }

    function extractCommentData(card) {
        const usernameElement = card.querySelector('.luogu-username');
        if (!usernameElement) return null;

        const userLink = usernameElement.querySelector('a[href^="/user/"]');
        if (!userLink) return null;

        const username = userLink.textContent.trim();
        const userHref = userLink.getAttribute('href');
        const userId = userHref.replace('/user/', '');

        const avatarImg = card.querySelector('.avatar');
        const avatarSrc = avatarImg ? avatarImg.getAttribute('src') : '';
        const isBanned = avatarSrc.includes('banned.png');

        const timeElement = card.querySelector('.time time');
        if (!timeElement) return null;

        const timeTitle = timeElement.getAttribute('title') || '';
        const timeText = timeElement.textContent.trim();

        const contentElement = card.querySelector('.content .lfe-marked');
        if (!contentElement) return null;

        const content = contentElement.textContent.trim();
        if (!content) return null;

        return {
            id: generateCommentHash({ username, time: timeTitle, content }),
            username,
            userId,
            isBanned,
            timeTitle,
            timeText,
            content: cleanContent(content)
        };
    }

    function formatCommentInfo(commentData) {
        const bannedTag = commentData.isBanned ? ' ⛔[封禁]' : '';
        return [
            `👤 用户: ${commentData.username}${bannedTag}`,
            `🔗 主页: https://www.luogu.com.cn/user/${commentData.userId}`,
            `🕐 时间: ${commentData.timeTitle} (${commentData.timeText})`,
            `💬 内容: ${commentData.content}`,
            `━━━━━━━━━━━━━━━━━━━━━━`
        ].join('\n');
    }

    function formatBatchInfo(newComments) {
        const now = new Date().toLocaleString('zh-CN', { hour12: false });
        let report = `📋 洛谷讨论区新回复报告\n`;
        report += `⏰ 检测时间: ${now}\n`;
        report += `🔍 新增回复: ${newComments.length} 条\n`;
        report += `🔄 页面URL: ${window.location.href}\n`;
        report += `📊 记录状态: ${isRecording ? '🟢 记录中' : '🔴 已暂停'}\n`;
        report += `\n${'='.repeat(40)}\n\n`;

        newComments.forEach((comment, index) => {
            if (index > 0) report += '\n';
            report += `【#${index + 1}】\n`;
            report += formatCommentInfo(comment);
            report += '\n';
        });

        report += `\n${'='.repeat(40)}\n`;
        report += `📌 总共 ${newComments.length} 条新回复 | ${now}`;
        return report;
    }

    function playAlertSound() {
        if (!CONFIG.ENABLE_SOUND) return;
        try {
            const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            const frequencies = isRecording ? [880, 1100] : [440, 550];  // 记录停止时用不同音调
            const duration = 0.12;
            frequencies.forEach((freq, index) => {
                const oscillator = audioCtx.createOscillator();
                const gainNode = audioCtx.createGain();
                oscillator.connect(gainNode);
                gainNode.connect(audioCtx.destination);
                oscillator.frequency.value = freq;
                oscillator.type = 'sine';
                gainNode.gain.setValueAtTime(0.3, audioCtx.currentTime + index * duration);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + index * duration + duration);
                oscillator.start(audioCtx.currentTime + index * duration);
                oscillator.stop(audioCtx.currentTime + index * duration + duration);
            });
        } catch (e) {
            debugLog('声音播放失败:', e);
        }
    }

    function showNotification(title, body) {
        if (!CONFIG.ENABLE_NOTIFICATION) return;
        try {
            GM_notification({
                title: title,
                text: body.substring(0, 200),
                timeout: 8000
            });
        } catch (e) {
            if ('Notification' in window && Notification.permission === 'granted') {
                new Notification(title, { body: body.substring(0, 200) });
            }
        }
    }

    function parseComments() {
        const comments = [];
        const cards = document.querySelectorAll('.l-card.comment');
        cards.forEach(card => {
            if (card.closest('.modal, .dialog, .popup')) return;
            const data = extractCommentData(card);
            if (data) comments.push(data);
        });
        return comments;
    }

    async function checkAndProcess() {
        // 检查是否正在记录
        if (!isRecording) {
            debugLog('记录已停止,跳过检测');
            return;
        }

        debugLog('开始扫描评论...');
        const currentComments = parseComments();
        const newComments = [];
        const knownIds = new Set([...processedComments]);

        currentComments.forEach(comment => {
            if (!knownIds.has(comment.id)) {
                newComments.push(comment);
                processedComments.add(comment.id);
            }
        });

        if (newComments.length > 0) {
            debugLog(`发现 ${newComments.length} 条新回复`);
            const batchReport = formatBatchInfo(newComments);

            const clipboardResult = await safeClipboardWrite(batchReport);
            addToStatusBar(batchReport, clipboardResult === 'failed');

            console.log('%c📋 洛谷讨论区新回复',
                'font-size:16px; font-weight:bold; color:#e74c3c;');
            console.log(batchReport);
            if (clipboardResult === 'failed') {
                console.warn('⚠️ 剪贴板写入失败,内容已保存到页面状态栏');
            }

            const firstComment = newComments[0];
            showNotification(
                `洛谷 - ${newComments.length} 条新回复`,
                `${firstComment.username}: ${firstComment.content.substring(0, 80)}`
            );

            playAlertSound();

            if (clipboardResult === 'failed') {
                showToast('⚠️ 剪贴板失败,已保存到状态栏', 'warning');
            } else {
                showToast(`✅ 已复制 ${newComments.length} 条新回复`, 'success');
            }

            saveState();
        } else {
            debugLog('无新回复');
        }
    }

    // ==================== 样式注入 ====================
    function injectStyles() {
        if (document.getElementById('luogu-monitor-styles')) return;

        const styles = document.createElement('style');
        styles.id = 'luogu-monitor-styles';
        styles.textContent = `
            #luogu-monitor-bar {
                position: fixed;
                width: 440px;
                max-width: 92vw;
                font-family: 'Segoe UI', system-ui, sans-serif;
                font-size: 13px;
                z-index: 99998;
                border-radius: 12px;
                transition: box-shadow 0.3s ease;
                user-select: none;
            }
            #luogu-monitor-bar:hover {
                box-shadow: 0 -4px 30px rgba(0, 0, 0, 0.3) !important;
            }
            .monitor-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 12px 16px;
                border-radius: 12px 12px 0 0;
                cursor: grab;
                user-select: none;
                transition: background 0.3s ease;
                gap: 10px;
            }
            .monitor-header:active {
                cursor: grabbing;
            }
            .monitor-drag-handle {
                font-size: 18px;
                letter-spacing: 2px;
                cursor: grab;
                padding: 0 4px;
            }
            .monitor-drag-handle:active {
                cursor: grabbing;
            }
            .monitor-status-indicator {
                width: 10px;
                height: 10px;
                border-radius: 50%;
                flex-shrink: 0;
                animation: statusPulse 2s infinite;
            }
            .monitor-status-indicator.stopped {
                animation: none;
                opacity: 0.6;
            }
            .monitor-title {
                font-weight: 600;
                font-size: 14px;
                flex: 1;
                margin: 0;
                white-space: nowrap;
            }
            .monitor-controls {
                display: flex;
                gap: 6px;
                align-items: center;
            }
            .monitor-count {
                padding: 2px 8px;
                border-radius: 12px;
                font-weight: bold;
                font-size: 12px;
                min-width: 24px;
                text-align: center;
                transition: all 0.3s ease;
            }
            .monitor-btn {
                border: none;
                padding: 6px 10px;
                border-radius: 6px;
                cursor: pointer;
                font-size: 14px;
                transition: all 0.3s ease;
                line-height: 1;
                white-space: nowrap;
            }
            .monitor-control-btn {
                font-size: 16px;
                padding: 6px 8px;
            }
            .theme-switch-btn {
                font-size: 16px;
            }
            .monitor-content {
                max-height: 200px;
                overflow-y: auto;
                padding: 8px;
                transition: background 0.3s ease;
            }
            .monitor-footer {
                border-radius: 0 0 12px 12px;
                overflow: hidden;
            }
            .monitor-item {
                padding: 8px 12px;
                margin: 6px 0;
                border-radius: 6px;
                position: relative;
                transition: all 0.3s ease;
            }
            .monitor-item-time {
                font-size: 11px;
                margin-bottom: 4px;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .monitor-item-text {
                font-size: 12px;
                white-space: pre-wrap;
                word-break: break-all;
                max-height: 60px;
                overflow-y: auto;
                padding-right: 50px;
            }
            .monitor-item-copy {
                position: absolute;
                top: 8px;
                right: 12px;
                border: none;
                padding: 2px 8px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 11px;
                transition: all 0.3s ease;
            }
            .monitor-retry {
                padding: 10px 16px;
                text-align: center;
            }
            .monitor-retry button {
                border: none;
                padding: 4px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-weight: bold;
                margin-left: 8px;
            }
            .monitor-record-controls {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 10px 16px;
                border-top: 1px solid;
            }
            .record-btn {
                font-size: 13px !important;
                padding: 8px 16px !important;
                font-weight: 600;
            }
            .monitor-record-status {
                font-size: 12px;
                font-weight: 500;
            }
            .paused-badge {
                background: #f38ba8;
                color: white;
                padding: 1px 6px;
                border-radius: 3px;
                font-size: 10px;
            }
            .monitor-content::-webkit-scrollbar {
                width: 6px;
            }
            .monitor-content::-webkit-scrollbar-thumb {
                border-radius: 3px;
            }
            @keyframes monitorToastIn {
                from { opacity: 0; transform: translateX(-50%) translateY(-20px); }
                to { opacity: 1; transform: translateX(-50%) translateY(0); }
            }
            @keyframes monitorToastOut {
                from { opacity: 1; transform: translateX(-50%) translateY(0); }
                to { opacity: 0; transform: translateX(-50%) translateY(-20px); }
            }
            @keyframes statusPulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.5; }
            }
            @keyframes pulse-dark {
                0%, 100% { box-shadow: 0 0 0 0 rgba(166, 227, 161, 0.4); }
                50% { box-shadow: 0 0 0 6px rgba(166, 227, 161, 0); }
            }
            @keyframes pulse-light {
                0%, 100% { box-shadow: 0 0 0 0 rgba(39, 174, 96, 0.4); }
                50% { box-shadow: 0 0 0 6px rgba(39, 174, 96, 0); }
            }
        `;
        document.head.appendChild(styles);
    }

    // ==================== 初始化 ====================
    async function init() {
        injectStyles();

        loadState();
        loadPosition();

        applyTheme();

        console.log('%c🔍 洛谷讨论区回复监控 v4.0',
            'font-size:14px; color:#cba6f7; font-weight:bold;');
        console.log('✨ 新功能: 启停控制 | 清除后重复保存');
        console.log('⚙️ 配置:', CONFIG);
        console.log('📊 初始状态:', isRecording ? '🟢 记录中' : '🔴 已暂停');

        if (CONFIG.ENABLE_NOTIFICATION && 'Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }

        // 首次扫描建立基准
        const initialComments = parseComments();
        initialComments.forEach(c => processedComments.add(c.id));
        saveState();

        ensureStatusBar();
        initDragSystem();

        window.addEventListener('resize', handleResize);

        // 启动定时检测
        checkIntervalId = setInterval(checkAndProcess, CONFIG.CHECK_INTERVAL);

        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                setTimeout(checkAndProcess, 500);
            }
        });

        console.log('✅ 监控已启动 - 启停控制 | 拖拽移动 | 主题切换 | 四重剪贴板降级');
    }

    // ==================== 启动 ====================
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
原文