跳到正文

剪贴板

剪贴板 itjrxibh

原文
剪贴板信息

剪贴板信息

收录
更新

洛谷喵化助手 v1.8.1

功能:会当你在犇犇、私信或讨论区中输入标点符号(“。”、“?”、“!”)以及波浪号(~)时在前面打一个“喵”字。

这份代码保证不会调用任何洛谷的api(并没有声明网络请求权限)。

代码由AI生成。

需要先下载“篡改猴”扩展才可使用,具体见这里。

更新日志:

  • 1.0:初稿。
  • 1.1:修复了按标点符号会显示两个喵的bug。
  • 1.2:设置只在首页加载。
  • 1.3:新增找到犇犇框后不再搜索的功能。
  • 1.4:移除目标字符串中的三个英文标点,减少网址、图床等识别错的问题。
  • 1.5:设置只匹配第一个 || 前的内容,修复了会修改他人犇犇的bug。
  • 1.6.1:新增私信喵化功能。
  • 1.6.2:新增控制面板,可启用或禁用喵化;如果设置关闭控制面板,可在浏览器右上角扩展界面找到。
  • 1.6.3:修复了私信界面发送时会清除插件打出的“喵”字的bug。
  • 1.7.1:新增匹配波浪号“~”;连续多个标点(可不同,如“?!”)只在第一个标点前加“喵”。
  • 1.7.2:修复并美化控制面板,支持任意拖动;修复私信输入框查找。
  • 1.8.1:通过查找 CodeMirror 编辑器并设置特定规则,支持讨论区发帖与回复的喵化;针对讨论区的 URL 变化,新增 SPA 路由监控功能。
C++
// ==UserScript==
// @name         洛谷喵化助手 v1.8.1
// @namespace    http://tampermonkey.net/
// @version      1.8.1
// @description  在洛谷犇犇、私信和讨论区自动在句末标点前加"喵"字,使用1.7.2风格控制面板
// @author       qwq
// @match        https://www.luogu.com.cn/
// @match        https://luogu.com.cn/
// @match        https://www.luogu.com.cn/chat*
// @match        https://luogu.com.cn/chat*
// @match        https://www.luogu.com.cn/discuss*
// @match        https://luogu.com.cn/discuss*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function() {
    'use strict';

    // ==================== 配置管理 ====================
    const CONFIG = {
        feedEnabled: GM_getValue('feedEnabled', true),
        chatEnabled: GM_getValue('chatEnabled', true),
        discussEnabled: GM_getValue('discussEnabled', true),
        showPanel: GM_getValue('showPanel', true)
    };

    // 保存配置
    function saveConfig() {
        GM_setValue('feedEnabled', CONFIG.feedEnabled);
        GM_setValue('chatEnabled', CONFIG.chatEnabled);
        GM_setValue('discussEnabled', CONFIG.discussEnabled);
        GM_setValue('showPanel', CONFIG.showPanel);
    }

    // 注册菜单命令
    GM_registerMenuCommand('打开控制面板', showControlPanel);
    GM_registerMenuCommand('重置所有设置', resetAllSettings);

    // ==================== 页面判断 ====================
    let isChatPage = window.location.pathname.startsWith('/chat');
    let isDiscussPage = window.location.pathname.startsWith('/discuss');
    let currentFeature = isChatPage ? 'chat' : (isDiscussPage ? 'discuss' : 'feed');
    let isFeatureEnabled = CONFIG[currentFeature + 'Enabled'];

    console.log(`🐱 洛谷喵化助手 v1.8.1 加载 (${isChatPage ? '私信页面' : (isDiscussPage ? '讨论区页面' : '犇犇页面')})...`);
    console.log(`⚙️  当前功能状态: ${isFeatureEnabled ? '已启用' : '已禁用'}`);

    // ==================== SPA路由监控 ====================
    let lastPathname = window.location.pathname;
    let routeObserver = null;
    let currentPanel = null;

    // 设置SPA路由监控
    function setupRouteMonitoring() {
        console.log('🔄 设置SPA路由监控...');

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

        routeObserver = new MutationObserver(() => {
            const currentPathname = window.location.pathname;
            if (currentPathname !== lastPathname) {
                console.log(`🔄 URL变化: ${lastPathname} -> ${currentPathname}`);
                handleRouteChange(lastPathname, currentPathname);
                lastPathname = currentPathname;
            }
        });

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

        console.log('✅ SPA路由监控已启用');
    }

    // 处理路由变化
    function handleRouteChange(oldPath, newPath) {
        isChatPage = newPath.startsWith('/chat');
        isDiscussPage = newPath.startsWith('/discuss');
        currentFeature = isChatPage ? 'chat' : (isDiscussPage ? 'discuss' : 'feed');
        isFeatureEnabled = CONFIG[currentFeature + 'Enabled'];

        const wasTargetPage = isTargetPage(oldPath);
        const isTargetPageNow = isTargetPage(newPath);

        if (wasTargetPage && !isTargetPageNow) {
            console.log('🚫 离开目标页面到非目标页面,移除面板');
            if (currentPanel && currentPanel.parentNode) {
                currentPanel.remove();
                currentPanel = null;
            }
        } else if (isTargetPageNow) {
            console.log('✅ 进入目标页面,重新初始化');

            setTimeout(() => {
                if (CONFIG.showPanel) {
                    if (currentPanel && document.body.contains(currentPanel)) {
                        currentPanel.style.display = 'block';
                    } else {
                        currentPanel = createControlPanel();
                    }
                }

                if (isFeatureEnabled) {
                    const inputBox = findInputBox();
                    if (inputBox) {
                        setupSmartListener(inputBox);
                    }
                }
            }, 500);
        }
    }

    // 判断是否为目标页面
    function isTargetPage(path) {
        return path === '/' ||
               path.startsWith('/feed') ||
               path.startsWith('/chat') ||
               path.startsWith('/discuss');
    }

    // ==================== 核心功能配置 ====================
    const TARGET_PUNCTUATION = '。?!~';

    // ==================== 核心函数 ====================

    // 智能加"喵"函数
    function addMiao(text, pageType = 'feed') {
        if (!text || typeof text !== 'string') return text;

        // 按行处理
        const lines = text.split('\n');
        const processedLines = lines.map(line => {
            if (line === '') return '';

            // 犇犇页面:处理 || 分隔符
            if (pageType === 'feed') {
                const separatorIndex = line.indexOf('||');
                if (separatorIndex !== -1) {
                    const beforeSeparator = line.substring(0, separatorIndex);
                    const afterSeparator = line.substring(separatorIndex);
                    const processedBefore = processLineText(beforeSeparator);
                    return processedBefore + afterSeparator;
                }
            }

            return processLineText(line);
        });

        // 返回处理后的文本,保留所有换行
        return processedLines.join('\n');
    }

    // 处理单行文本内容
    function processLineText(line) {
        let result = '';
        let i = 0;

        while (i < line.length) {
            const char = line[i];

            if (TARGET_PUNCTUATION.includes(char)) {
                // 检查前面是否已经是"喵"
                if (i === 0 || line[i-1] !== '喵') {
                    result += '喵';
                }
                result += char;
                i++;

                // 跳过连续标点
                while (i < line.length && TARGET_PUNCTUATION.includes(line[i])) {
                    result += line[i];
                    i++;
                }
            } else {
                result += char;
                i++;
            }
        }

        return result;
    }

    // ==================== 页面适配器 ====================

    // 查找输入框
    function findInputBox() {
        if (isChatPage) {
            return findChatInputBox();
        } else if (isDiscussPage) {
            return findDiscussInputBox();
        } else {
            return findFeedInputBox();
        }
    }

    // 私信输入框查找
    function findChatInputBox() {
        const selectors = [
            'textarea.frame.lfe-form-sz-middle',
            'textarea[class*="frame"]',
            'textarea[class*="lfe-form"]',
            'textarea[placeholder*="消息"]',
            'textarea[placeholder*="输入"]',
            'textarea'
        ];

        for (const selector of selectors) {
            try {
                const elements = document.querySelectorAll(selector);
                for (const element of elements) {
                    if (element.offsetParent !== null && !element.disabled) {
                        console.log(`✅ 找到私信输入框: ${selector}`);
                        return element;
                    }
                }
            } catch (e) {}
        }

        return null;
    }

    // 讨论区输入框查找
    function findDiscussInputBox() {
        // 查找CodeMirror编辑器
        const codeMirrorSelectors = [
            '.cm-content[contenteditable="true"]',
            '.cm-editor .cm-content',
            'div[contenteditable="true"].ProseMirror',
            'div[contenteditable="true"][role="textbox"]'
        ];

        for (const selector of codeMirrorSelectors) {
            try {
                const element = document.querySelector(selector);
                if (element && element.offsetParent !== null && element.isContentEditable) {
                    console.log(`✅ 找到CodeMirror编辑器: ${selector}`);
                    return element;
                }
            } catch (e) {}
        }

        // 传统textarea
        const textareaSelectors = [
            'textarea[placeholder*="发表帖子"]',
            'textarea[placeholder*="发表话题"]',
            'textarea[placeholder*="回复"]',
            'textarea[placeholder*="评论"]',
            'textarea[placeholder*="说点什么"]',
            'textarea'
        ];

        for (const selector of textareaSelectors) {
            try {
                const elements = document.querySelectorAll(selector);
                for (const element of elements) {
                    if (element.offsetParent !== null && !element.disabled) {
                        console.log(`✅ 找到讨论区textarea: ${selector}`);
                        return element;
                    }
                }
            } catch (e) {}
        }

        return null;
    }

    // 犇犇输入框查找
    function findFeedInputBox() {
        const feedSelectors = [
            'textarea[placeholder*="犇"]',
            'textarea[placeholder*="说"]',
            'textarea[placeholder*="动态"]',
            '.feed-input textarea',
            '.feeds-container textarea',
            'textarea'
        ];

        for (const selector of feedSelectors) {
            try {
                const element = document.querySelector(selector);
                if (element && element.offsetParent !== null) {
                    console.log(`✅ 找到犇犇输入框: ${selector}`);
                    return element;
                }
            } catch (e) {}
        }

        return null;
    }

    // ==================== 输入处理核心 ====================

    // 处理输入框
    function processInputElement(element) {
        if (!element || !isFeatureEnabled) return false;

        if (element.tagName === 'TEXTAREA' || element.tagName === 'INPUT') {
            return processTextarea(element);
        } else if (element.isContentEditable) {
            return processContentEditable(element);
        }

        return false;
    }

    // 确保所有函数都正确定义
    function countMiaoBeforePosition(text, position) {
        if (!text || position <= 0) return 0;

        let count = 0;
        // 只计算光标位置之前的文本
        for (let i = 0; i < Math.min(position, text.length); i++) {
            const char = text[i];

            if (TARGET_PUNCTUATION.includes(char)) {
                // 检查前面是否已经是"喵"
                if (i === 0 || text[i-1] !== '喵') {
                    count++;
                }
            }
        }

        return count;
    }

    // 修复processTextarea函数 - 确保普通textarea的光标也正确
    function processTextarea(element) {
        const oldValue = element.value;
        const selectionStart = element.selectionStart;
        const selectionEnd = element.selectionEnd;

        if (!oldValue) return false;

        const pageType = isChatPage ? 'chat' : (isDiscussPage ? 'discuss' : 'feed');
        const newValue = addMiao(oldValue, pageType);

        if (newValue !== oldValue) {
            console.log('需要添加喵字到textarea');

            // 计算光标前需要添加的喵字数量
            const miaoCountBeforeCursor = countMiaoBeforePosition(oldValue, selectionStart);

            // 更新值
            element.value = newValue;

            // 设置新的光标位置 - 确保是有效的数字
            const newCursorPos = selectionStart + miaoCountBeforeCursor;
            element.selectionStart = newCursorPos;
            element.selectionEnd = newCursorPos;

            // 触发事件
            const inputEvent = new Event('input', { bubbles: true });
            element.dispatchEvent(inputEvent);

            console.log(`✅ 已添加喵字到textarea,光标: ${selectionStart} -> ${newCursorPos}, 喵字数: ${miaoCountBeforeCursor}`);
            return true;
        }

        return false;
    }

    function calculateCursorPositionForCodeMirror(oldText, cursorPosition) {
        if (!oldText) return cursorPosition;

        // 简单方法:计算光标前需要添加的喵字数量
        let miaoCount = 0;

        // 只计算严格在光标位置之前的字符
        for (let i = 0; i < Math.min(cursorPosition, oldText.length); i++) {
            const char = oldText[i];

            if (TARGET_PUNCTUATION.includes(char)) {
                // 检查前面是否已经是"喵"
                if (i === 0 || oldText[i-1] !== '喵') {
                    miaoCount++;
                }
            }
        }

        return cursorPosition + miaoCount;
    }

    // 修复restoreCursorPositionFinal - 确保普通编辑器光标恢复
    function restoreCursorPositionFinal(element, position) {
        const selection = window.getSelection();
        selection.removeAllRanges();

        const range = document.createRange();

        try {
            let currentPos = 0;
            let targetNode = null;
            let targetOffset = 0;

            // 遍历子节点
            const walker = document.createTreeWalker(
                element,
                NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
                null,
                false
            );

            let node;
            while (node = walker.nextNode()) {
                let nodeLength = 0;

                if (node.nodeType === Node.TEXT_NODE) {
                    nodeLength = node.textContent.length;
                } else if (node.nodeType === Node.ELEMENT_NODE) {
                    const tagName = node.tagName.toLowerCase();
                    if (tagName === 'br') {
                        nodeLength = 1; // 换行符
                    }
                }

                // 检查是否到达目标位置
                if (currentPos + nodeLength >= position) {
                    targetNode = node;
                    targetOffset = position - currentPos;
                    break;
                }

                currentPos += nodeLength;
            }

            if (targetNode) {
                if (targetNode.nodeType === Node.TEXT_NODE) {
                    // 文本节点
                    const safeOffset = Math.min(targetOffset, targetNode.textContent.length);
                    range.setStart(targetNode, safeOffset);
                    range.setEnd(targetNode, safeOffset);
                } else if (targetNode.nodeType === Node.ELEMENT_NODE && targetNode.tagName.toLowerCase() === 'br') {
                    // br元素
                    if (targetOffset === 0) {
                        range.setStartBefore(targetNode);
                        range.setEndBefore(targetNode);
                    } else {
                        range.setStartAfter(targetNode);
                        range.setEndAfter(targetNode);
                    }
                } else {
                    // 其他元素,放在前面
                    range.setStartBefore(targetNode);
                    range.setEndBefore(targetNode);
                }
            } else {
                // 光标在末尾
                if (element.lastChild) {
                    const lastChild = element.lastChild;
                    if (lastChild.nodeType === Node.TEXT_NODE) {
                        range.setStart(lastChild, lastChild.textContent.length);
                        range.setEnd(lastChild, lastChild.textContent.length);
                    } else if (lastChild.nodeType === Node.ELEMENT_NODE && lastChild.tagName.toLowerCase() === 'br') {
                        range.setStartAfter(lastChild);
                        range.setEndAfter(lastChild);
                    } else {
                        range.setStartAfter(lastChild);
                        range.setEndAfter(lastChild);
                    }
                } else {
                    // 空元素
                    range.setStart(element, 0);
                    range.setEnd(element, 0);
                }
            }

            range.collapse(true);
            selection.addRange(range);
        } catch (e) {
            console.log('恢复光标位置失败,放在末尾:', e);
            // 失败时放在末尾
            range.selectNodeContents(element);
            range.collapse(false);
            selection.addRange(range);
        }
    }

    // 修复processContentEditable - 确保正确区分编辑器和使用正确的函数
    function processContentEditable(element) {
        // 获取当前选区
        const selection = window.getSelection();
        if (selection.rangeCount === 0) return false;

        const range = selection.getRangeAt(0);

        // 获取带换行的文本
        const oldText = getTextWithLineBreaksFixed(element);

        if (!oldText && oldText !== '') return false;

        const pageType = isDiscussPage ? 'discuss' : 'chat';
        const newText = addMiao(oldText, pageType);

        if (newText !== oldText) {
            console.log('需要添加喵字到可编辑元素');

            // 检查是否是CodeMirror
            const isCodeMirror = element.classList.contains('cm-content') ||
                  element.classList.contains('ProseMirror');

            let cursorPosition;
            if (isCodeMirror) {
                // CodeMirror使用专门的方法
                cursorPosition = getCursorPositionForCodeMirror(element, range);
            } else {
                // 普通编辑器
                cursorPosition = getCursorPositionWithBreaksFixed(element, range, oldText);
            }

            console.log('原始光标位置:', cursorPosition, '文本长度:', oldText.length, 'CodeMirror:', isCodeMirror);

            // 计算新光标位置 - 统一使用相同的方法
            let newCursorPos = cursorPosition + countMiaoBeforePosition(oldText, cursorPosition);

            console.log('新光标位置:', newCursorPos, '新文本长度:', newText.length);

            // 更新内容
            updateContentFixed(element, newText);

            // 恢复光标位置
            if (isCodeMirror) {
                restoreCursorPositionForCodeMirror(element, newCursorPos);
            } else {
                restoreCursorPositionFinal(element, newCursorPos);
            }

            // 触发事件
            const inputEvent = new Event('input', { bubbles: true });
            element.dispatchEvent(inputEvent);

            console.log(`✅ 已添加喵字到可编辑元素,光标: ${cursorPosition} -> ${newCursorPos}, CodeMirror: ${isCodeMirror}`);
            return true;
        }

        return false;
    }

    // 正确的获取带换行的文本 - 简单统计<br>数量
    function getTextWithLineBreaksFixed(element) {
        let result = '';

        // 遍历所有节点
        const nodes = [];
        const walker = document.createTreeWalker(
            element,
            NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
            null,
            false
        );

        let node;
        while (node = walker.nextNode()) {
            nodes.push(node);
        }

        // 处理节点
        for (let i = 0; i < nodes.length; i++) {
            const node = nodes[i];

            if (node.nodeType === Node.TEXT_NODE) {
                result += node.textContent;
            } else if (node.nodeType === Node.ELEMENT_NODE) {
                const tagName = node.tagName.toLowerCase();

                if (tagName === 'br') {
                    // br元素:直接添加换行
                    result += '\n';
                }
                else if (tagName === 'div' || tagName === 'p') {
                    // 块级元素:如果是CodeMirror行
                    if (node.classList.contains('cm-line')) {
                        // 不是第一个行,前面加换行
                        if (result !== '' && !result.endsWith('\n')) {
                            result += '\n';
                        }
                    }
                    // 对于普通div/p,不添加换行,因为它们的内容已经在文本节点中
                }
            }
        }

        return result;
    }

    // 辅助函数:获取在CodeMirror一行内的位置
    function getPositionInLine(lineElement, container, offset) {
        if (container === lineElement) {
            // 容器就是行元素本身
            return offset;
        }

        let position = 0;
        const walker = document.createTreeWalker(
            lineElement,
            NodeFilter.SHOW_TEXT,
            null,
            false
        );

        let node;
        while (node = walker.nextNode()) {
            if (node === container) {
                // 找到目标节点
                return position + Math.min(offset, node.textContent.length);
            }
            position += node.textContent.length;
        }

        return position;
    }

    // 修复getCursorPositionWithBreaksFixed函数 - 确保普通编辑器也工作
    function getCursorPositionWithBreaksFixed(element, range, fullText) {
        try {
            // 简单方法:获取光标前的文本长度
            const tempRange = document.createRange();
            tempRange.setStart(element, 0);
            tempRange.setEnd(range.startContainer, range.startOffset);

            // 获取临时range的文本
            let beforeText = '';
            const walker = document.createTreeWalker(
                tempRange.cloneContents(),
                NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
                null,
                false
            );

            let node;
            while (node = walker.nextNode()) {
                if (node.nodeType === Node.TEXT_NODE) {
                    beforeText += node.textContent;
                } else if (node.nodeType === Node.ELEMENT_NODE) {
                    const tagName = node.tagName.toLowerCase();
                    if (tagName === 'br') {
                        beforeText += '\n';
                    }
                }
            }

            return beforeText.length;

        } catch (e) {
            console.log('获取光标位置失败,使用文本长度:', e);
            return fullText ? fullText.length : 0;
        }
    }

    // 专门为CodeMirror设计的光标位置获取
    function getCursorPositionForCodeMirror(element, range) {
        try {
            const lineElements = element.querySelectorAll('.cm-line');
            if (lineElements.length === 0) return 0;

            // 找到光标所在的行
            let targetLineIndex = -1;
            for (let i = 0; i < lineElements.length; i++) {
                const line = lineElements[i];
                if (line === range.startContainer || line.contains(range.startContainer)) {
                    targetLineIndex = i;
                    break;
                }
            }

            if (targetLineIndex === -1) {
                // 光标可能在行间或其他位置
                return 0;
            }

            // 计算前面所有行的总长度
            let totalLength = 0;
            for (let i = 0; i < targetLineIndex; i++) {
                totalLength += (lineElements[i].textContent || '').length + 1; // +1 for newline
            }

            // 计算在当前行内的位置
            const currentLine = lineElements[targetLineIndex];
            let positionInLine = 0;

            if (range.startContainer === currentLine) {
                // 光标在行元素本身上
                positionInLine = range.startOffset;
            } else {
                // 光标在行内的某个节点上
                const walker = document.createTreeWalker(
                    currentLine,
                    NodeFilter.SHOW_TEXT,
                    null,
                    false
                );

                let node;
                let found = false;
                while (node = walker.nextNode()) {
                    if (node === range.startContainer) {
                        positionInLine += Math.min(range.startOffset, node.textContent.length);
                        found = true;
                        break;
                    }
                    positionInLine += node.textContent.length;
                }

                if (!found) {
                    // 没找到,放在行末
                    positionInLine = currentLine.textContent.length;
                }
            }

            return totalLength + Math.min(positionInLine, currentLine.textContent.length);

        } catch (e) {
            console.log('CodeMirror获取光标位置失败:', e);
            return 0;
        }
    }

    // 修复的从range获取带换行的文本
    function getTextWithLineBreaksFromRangeFixed(range) {
        let result = '';

        // 获取range包含的节点
        const fragment = range.cloneContents();
        const walker = document.createTreeWalker(
            fragment,
            NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
            null,
            false
        );

        let node;
        while (node = walker.nextNode()) {
            if (node.nodeType === Node.TEXT_NODE) {
                result += node.textContent;
            } else if (node.nodeType === Node.ELEMENT_NODE) {
                const tagName = node.tagName.toLowerCase();
                if (tagName === 'br' || tagName === 'div' || tagName === 'p') {
                    // 避免连续重复换行
                    if (!result.endsWith('\n')) {
                        result += '\n';
                    }
                }
                // 继续遍历子元素
                walker.currentNode = node;
            }
        }

        return result;
    }

    // 正确的内容更新 - 一对一映射<br>和\n
    function updateContentFixed(element, newText) {
        // 保存当前焦点状态
        const wasFocused = document.activeElement === element;

        // 如果新文本为空,清空元素
        if (!newText) {
            element.innerHTML = '';
            if (wasFocused) element.focus();
            return;
        }

        // 检查是否是CodeMirror编辑器
        const isCodeMirror = element.classList.contains('cm-content') ||
              element.classList.contains('ProseMirror');

        // 清空元素
        while (element.firstChild) {
            element.removeChild(element.firstChild);
        }

        if (isCodeMirror) {
            // CodeMirror:每行一个.cm-line
            const lines = newText.split('\n');
            for (let i = 0; i < lines.length; i++) {
                const lineDiv = document.createElement('div');
                lineDiv.className = 'cm-line';
                lineDiv.textContent = lines[i];
                element.appendChild(lineDiv);
            }
        } else {
            // 普通编辑器:直接重建文本和<br>
            // 关键:不要用split('\n'),而是直接处理字符串
            let currentText = '';

            for (let i = 0; i < newText.length; i++) {
                if (newText[i] === '\n') {
                    // 遇到换行:添加当前文本的节点,然后加<br>
                    if (currentText !== '' || i === 0) {
                        // 即使是空文本也添加节点
                        const textNode = document.createTextNode(currentText);
                        element.appendChild(textNode);
                        currentText = '';
                    }

                    // 添加<br>
                    const br = document.createElement('br');
                    element.appendChild(br);
                } else {
                    currentText += newText[i];
                }
            }

            // 添加最后一段文本
            if (currentText !== '') {
                const textNode = document.createTextNode(currentText);
                element.appendChild(textNode);
            }

            // 如果文本以换行结束,需要再添加一个空文本节点
            if (newText.endsWith('\n')) {
                const textNode = document.createTextNode('');
                element.appendChild(textNode);
            }
        }

        // 如果之前有焦点,恢复焦点
        if (wasFocused) {
            element.focus();
        }
    }

    // 辅助函数:获取元素中的所有文本节点
    function getTextNodesInElement(element) {
        const textNodes = [];
        const walker = document.createTreeWalker(
            element,
            NodeFilter.SHOW_TEXT,
            null,
            false
        );

        let node;
        while (node = walker.nextNode()) {
            textNodes.push(node);
        }

        return textNodes;
    }

    // 专门为CodeMirror设计的光标恢复
    function restoreCursorPositionForCodeMirror(element, position) {
        const selection = window.getSelection();
        selection.removeAllRanges();

        try {
            const lineElements = element.querySelectorAll('.cm-line');
            if (lineElements.length === 0) {
                // 没有行,放在开头
                const range = document.createRange();
                range.setStart(element, 0);
                range.setEnd(element, 0);
                range.collapse(true);
                selection.addRange(range);
                return;
            }

            // 找到目标位置所在的行
            let currentPos = 0;
            let targetLineIndex = -1;
            let targetOffsetInLine = 0;

            for (let i = 0; i < lineElements.length; i++) {
                const line = lineElements[i];
                const lineText = line.textContent || '';
                const lineLength = lineText.length;

                // 检查是否在这一行
                if (position <= currentPos + lineLength) {
                    targetLineIndex = i;
                    targetOffsetInLine = position - currentPos;
                    break;
                }

                currentPos += lineLength;
                // 如果不是最后一行,加上换行符
                if (i < lineElements.length - 1) {
                    currentPos += 1;
                }
            }

            if (targetLineIndex === -1) {
                // 位置超出文档,放在最后一行末尾
                targetLineIndex = lineElements.length - 1;
                const lastLine = lineElements[targetLineIndex];
                targetOffsetInLine = lastLine.textContent.length;
            }

            const targetLine = lineElements[targetLineIndex];
            const safeOffset = Math.min(targetOffsetInLine, targetLine.textContent.length);

            // 找到行内合适的文本节点
            const textNodes = getTextNodesInElement(targetLine);

            if (textNodes.length === 0) {
                // 行内没有文本节点
                const range = document.createRange();
                range.setStart(targetLine, 0);
                range.setEnd(targetLine, 0);
                range.collapse(true);
                selection.addRange(range);
                return;
            }

            // 在文本节点中找到正确位置
            let nodePos = 0;
            for (const textNode of textNodes) {
                const nodeLength = textNode.textContent.length;

                if (safeOffset <= nodePos + nodeLength) {
                    // 在这个文本节点内
                    const offsetInNode = safeOffset - nodePos;
                    const range = document.createRange();
                    range.setStart(textNode, Math.min(offsetInNode, textNode.textContent.length));
                    range.setEnd(textNode, Math.min(offsetInNode, textNode.textContent.length));
                    range.collapse(true);
                    selection.addRange(range);
                    return;
                }

                nodePos += nodeLength;
            }

            // 没找到,放在最后一个文本节点末尾
            const lastNode = textNodes[textNodes.length - 1];
            const range = document.createRange();
            range.setStart(lastNode, lastNode.textContent.length);
            range.setEnd(lastNode, lastNode.textContent.length);
            range.collapse(true);
            selection.addRange(range);

        } catch (e) {
            console.log('CodeMirror恢复光标失败:', e);
            // 失败时放在开头
            const range = document.createRange();
            range.setStart(element, 0);
            range.setEnd(element, 0);
            range.collapse(true);
            selection.addRange(range);
        }
    }

    // ==================== 智能监听器 ====================

    function setupSmartListener(element) {
        if (!element) return;

        // 检查是否是CodeMirror
        const isCodeMirror = element.classList.contains('cm-content') ||
                            element.classList.contains('cm-editor') ||
                            element.classList.contains('ProseMirror');

        if (isCodeMirror) {
            setupCodeMirrorListener(element);
            return;
        }

        // 普通输入框处理
        if (element.getAttribute('data-miao-attached')) return;
        element.setAttribute('data-miao-attached', 'true');

        console.log(`🎯 安装输入框监听器 (${element.tagName})`);

        let isComposing = false;
        let inputTimer = null;

        function handleCompositionStart() {
            isComposing = true;
            if (inputTimer) clearTimeout(inputTimer);
        }

        function handleCompositionEnd() {
            isComposing = false;
            if (inputTimer) clearTimeout(inputTimer);
            inputTimer = setTimeout(() => {
                processInputElement(element);
                inputTimer = null;
            }, 100);
        }

        function handleInput() {
            if (isComposing) return;
            if (inputTimer) clearTimeout(inputTimer);
            inputTimer = setTimeout(() => {
                processInputElement(element);
                inputTimer = null;
            }, 300);
        }

        function handleBlur() {
            if (inputTimer) clearTimeout(inputTimer);
            processInputElement(element);
        }

        function handleKeyDown(e) {
            // 只在输入标点或回车时处理,避免频繁处理
            if (TARGET_PUNCTUATION.includes(e.key) || e.key === 'Enter') {
                if (inputTimer) clearTimeout(inputTimer);
                inputTimer = setTimeout(() => {
                    if (!isComposing) processInputElement(element);
                    inputTimer = null;
                }, 50);
            }
        }

        element.addEventListener('compositionstart', handleCompositionStart);
        element.addEventListener('compositionend', handleCompositionEnd);
        element.addEventListener('input', handleInput);
        element.addEventListener('blur', handleBlur);
        element.addEventListener('keydown', handleKeyDown);

        // 保存清理函数
        element.cleanupMiaoListener = function() {
            element.removeEventListener('compositionstart', handleCompositionStart);
            element.removeEventListener('compositionend', handleCompositionEnd);
            element.removeEventListener('input', handleInput);
            element.removeEventListener('blur', handleBlur);
            element.removeEventListener('keydown', handleKeyDown);
            if (inputTimer) clearTimeout(inputTimer);
            element.removeAttribute('data-miao-attached');
        };

        // 初始处理
        setTimeout(() => processInputElement(element), 500);
    }

    // CodeMirror监听器 - 使用相同的可编辑元素处理逻辑
    function setupCodeMirrorListener(editor) {
        if (!editor || !isFeatureEnabled) return;

        if (editor.hasAttribute('data-miao-codemirror')) return;
        editor.setAttribute('data-miao-codemirror', 'true');

        console.log('🎯 设置CodeMirror监听器');

        let isComposing = false;
        let inputTimer = null;

        function safeProcess() {
            if (isComposing) return;
            processInputElement(editor);
        }

        editor.addEventListener('compositionstart', () => {
            isComposing = true;
            if (inputTimer) clearTimeout(inputTimer);
        });

        editor.addEventListener('compositionend', () => {
            isComposing = false;
            if (inputTimer) clearTimeout(inputTimer);
            inputTimer = setTimeout(safeProcess, 100);
        });

        editor.addEventListener('input', () => {
            if (isComposing) return;
            if (inputTimer) clearTimeout(inputTimer);
            inputTimer = setTimeout(safeProcess, 300);
        });

        editor.addEventListener('keydown', (e) => {
            if (TARGET_PUNCTUATION.includes(e.key) || e.key === 'Enter') {
                if (inputTimer) clearTimeout(inputTimer);
                inputTimer = setTimeout(safeProcess, 50);
            }
        });

        editor.addEventListener('blur', () => {
            if (inputTimer) clearTimeout(inputTimer);
            safeProcess();
        });

        console.log('✅ CodeMirror监听器设置完成');
    }

    // ==================== 控制面板系统 ====================

    // 创建控制面板(1.7.2风格,三个按钮)
    function createControlPanel() {
        if (!isTargetPage(window.location.pathname) || !CONFIG.showPanel) {
            return null;
        }

        const oldPanel = document.getElementById('miao-control-panel');
        if (oldPanel) oldPanel.remove();

        const panel = document.createElement('div');
        panel.id = 'miao-control-panel';

        // 尝试加载之前保存的位置
        let savedPos = null;
        try {
            savedPos = GM_getValue('panelPosition');
        } catch (e) {
            console.log('无法读取保存的面板位置');
        }

        // 设置位置
        let panelLeft, panelTop;
        if (savedPos && savedPos.x !== undefined && savedPos.y !== undefined) {
            panelLeft = savedPos.x;
            panelTop = savedPos.y;
        } else {
            panelLeft = window.innerWidth - 260;
            panelTop = 20;
        }

        // 确保位置在可视范围内
        panelLeft = Math.max(10, Math.min(panelLeft, window.innerWidth - 250));
        panelTop = Math.max(10, Math.min(panelTop, window.innerHeight - 200));

        // 面板样式
        panel.style.cssText = `
            position: fixed !important;
            left: ${panelLeft}px !important;
            top: ${panelTop}px !important;
            background: white !important;
            border-radius: 10px !important;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15) !important;
            padding: 15px !important;
            z-index: 10001 !important;
            min-width: 220px !important;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
            border: 1px solid #e0e0e0 !important;
            transition: all 0.3s ease !important;
            user-select: none !important;
        `;

        // 面板标题
        const title = document.createElement('div');
        title.textContent = '🐱 洛谷喵化助手 v1.8.1';
        title.style.cssText = `
            font-size: 14px !important;
            font-weight: bold !important;
            margin-bottom: 12px !important;
            color: #333 !important;
            border-bottom: 1px solid #eee !important;
            padding-bottom: 8px !important;
            cursor: move !important;
            user-select: none !important;
            position: relative !important;
        `;

        // 关闭按钮
        const closeBtn = document.createElement('span');
        closeBtn.textContent = '×';
        closeBtn.style.cssText = `
            position: absolute !important;
            right: 0 !important;
            top: 0 !important;
            cursor: pointer !important;
            font-size: 18px !important;
            color: #999 !important;
            width: 20px !important;
            height: 20px !important;
            text-align: center !important;
            line-height: 18px !important;
            border-radius: 50% !important;
        `;
        closeBtn.onmouseenter = () => closeBtn.style.background = '#f0f0f0';
        closeBtn.onmouseleave = () => closeBtn.style.background = '';
        closeBtn.onclick = () => {
            panel.style.display = 'none';
            CONFIG.showPanel = false;
            saveConfig();
        };
        title.appendChild(closeBtn);

        // 功能开关容器
        const switchesContainer = document.createElement('div');
        switchesContainer.style.cssText = 'margin-bottom: 15px !important;';

        // 犇犇开关
        const feedSwitch = createSwitch('犇犇喵化', CONFIG.feedEnabled, (checked) => {
            CONFIG.feedEnabled = checked;
            saveConfig();
            updatePanelStatus();
            if (!isChatPage && !isDiscussPage) {
                window.location.reload();
            }
        });

        // 私信开关
        const chatSwitch = createSwitch('私信喵化', CONFIG.chatEnabled, (checked) => {
            CONFIG.chatEnabled = checked;
            saveConfig();
            updatePanelStatus();
            if (isChatPage) {
                window.location.reload();
            }
        });

        // 讨论区开关
        const discussSwitch = createSwitch('讨论区喵化', CONFIG.discussEnabled, (checked) => {
            CONFIG.discussEnabled = checked;
            saveConfig();
            updatePanelStatus();
            if (isDiscussPage) {
                window.location.reload();
            }
        });

        // 面板开关
        const panelSwitch = createSwitch('显示面板', CONFIG.showPanel, (checked) => {
            CONFIG.showPanel = checked;
            saveConfig();
            if (!checked) {
                panel.style.display = 'none';
            } else {
                panel.style.display = 'block';
            }
        });

        // 将开关添加到容器
        switchesContainer.appendChild(feedSwitch);
        switchesContainer.appendChild(chatSwitch);
        switchesContainer.appendChild(discussSwitch);
        switchesContainer.appendChild(panelSwitch);

        // 按钮容器
        const buttonsContainer = document.createElement('div');
        buttonsContainer.style.cssText = `
            display: flex !important;
            flex-direction: column !important;
            gap: 8px !important;
            margin-top: 10px !important;
        `;

        // 测试按钮
        const testButton = document.createElement('button');
        testButton.textContent = '🐱 测试喵化';
        testButton.style.cssText = `
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            border: none !important;
            padding: 8px 12px !important;
            border-radius: 6px !important;
            cursor: pointer !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            transition: all 0.2s !important;
        `;
        testButton.onmouseenter = () => testButton.style.opacity = '0.9';
        testButton.onmouseleave = () => testButton.style.opacity = '1';
        testButton.onclick = () => {
            const testText = '这是一个测试句子。真的吗?!今天天气真好~';
            const pageType = isChatPage ? 'chat' : (isDiscussPage ? 'discuss' : 'feed');
            const result = addMiao(testText, pageType);
            alert(`测试输入:${testText}\n输出结果:${result}`);
        };

        // 重置按钮
        const resetButton = document.createElement('button');
        resetButton.textContent = '🔄 重置设置';
        resetButton.style.cssText = `
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
            color: white !important;
            border: none !important;
            padding: 8px 12px !important;
            border-radius: 6px !important;
            cursor: pointer !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            transition: all 0.2s !important;
        `;
        resetButton.onmouseenter = () => resetButton.style.opacity = '0.9';
        resetButton.onmouseleave = () => resetButton.style.opacity = '1';
        resetButton.onclick = resetAllSettings;

        // 隐藏按钮
        const hideButton = document.createElement('button');
        hideButton.textContent = '👁️ 隐藏面板';
        hideButton.style.cssText = `
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%) !important;
            color: white !important;
            border: none !important;
            padding: 8px 12px !important;
            border-radius: 6px !important;
            cursor: pointer !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            transition: all 0.2s !important;
        `;
        hideButton.onmouseenter = () => hideButton.style.opacity = '0.9';
        hideButton.onmouseleave = () => hideButton.style.opacity = '1';
        hideButton.onclick = () => {
            panel.style.display = 'none';
            CONFIG.showPanel = false;
            saveConfig();
        };

        // 将按钮添加到容器
        buttonsContainer.appendChild(testButton);
        buttonsContainer.appendChild(resetButton);
        buttonsContainer.appendChild(hideButton);

        // 状态指示器
        const statusIndicator = document.createElement('div');
        statusIndicator.id = 'miao-status-indicator';
        statusIndicator.style.cssText = `
            margin-top: 10px !important;
            padding: 6px 10px !important;
            border-radius: 5px !important;
            font-size: 12px !important;
            text-align: center !important;
        `;

        function updatePanelStatus() {
            const currentEnabled = CONFIG[currentFeature + 'Enabled'];
            const pageName = isChatPage ? '私信' : (isDiscussPage ? '讨论区' : '犇犇');
            statusIndicator.textContent = `当前页面: ${pageName} (${currentEnabled ? '已启用' : '已禁用'})`;
            statusIndicator.style.background = currentEnabled ? '#e8f5e9' : '#ffebee';
            statusIndicator.style.color = currentEnabled ? '#2e7d32' : '#c62828';
        }

        updatePanelStatus();

        // 组装面板
        panel.appendChild(title);
        panel.appendChild(switchesContainer);
        panel.appendChild(buttonsContainer);
        panel.appendChild(statusIndicator);

        // 添加拖拽功能
        makeDraggable(panel, title);

        document.body.appendChild(panel);
        console.log('✅ 控制面板已创建(1.7.2风格)');
        return panel;
    }

    // 创建开关控件
    function createSwitch(label, checked, onChange) {
        const container = document.createElement('div');
        container.style.cssText = `
            display: flex !important;
            justify-content: space-between !important;
            align-items: center !important;
            margin-bottom: 10px !important;
            font-size: 13px !important;
        `;

        const labelSpan = document.createElement('span');
        labelSpan.textContent = label;
        labelSpan.style.cssText = 'color: #555 !important;';

        const switchContainer = document.createElement('label');
        switchContainer.style.cssText = `
            position: relative !important;
            display: inline-block !important;
            width: 40px !important;
            height: 20px !important;
        `;

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.checked = checked;
        checkbox.style.cssText = `
            opacity: 0 !important;
            width: 0 !important;
            height: 0 !important;
        `;

        const slider = document.createElement('span');
        slider.style.cssText = `
            position: absolute !important;
            cursor: pointer !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            background-color: ${checked ? '#4CAF50' : '#ccc'} !important;
            transition: .4s !important;
            border-radius: 20px !important;
        `;

        const knob = document.createElement('span');
        knob.style.cssText = `
            position: absolute !important;
            content: "" !important;
            height: 16px !important;
            width: 16px !important;
            left: ${checked ? '22px' : '2px'} !important;
            bottom: 2px !important;
            background-color: white !important;
            transition: .4s !important;
            border-radius: 50% !important;
            box-shadow: 0 1px 3px rgba(0,0,0,0.3) !important;
        `;

        checkbox.addEventListener('change', function() {
            const isChecked = this.checked;
            slider.style.backgroundColor = isChecked ? '#4CAF50' : '#ccc';
            knob.style.left = isChecked ? '22px' : '2px';
            onChange(isChecked);
        });

        switchContainer.appendChild(checkbox);
        switchContainer.appendChild(slider);
        switchContainer.appendChild(knob);

        container.appendChild(labelSpan);
        container.appendChild(switchContainer);

        return container;
    }

    // 使元素可拖拽
    function makeDraggable(element, handle) {
        let isDragging = false;
        let startX, startY, initialLeft, initialTop;

        handle.style.cursor = 'move';

        handle.addEventListener('mousedown', startDrag);

        function startDrag(e) {
            if (e.target === handle.querySelector('span') || e.target.textContent === '×') {
                return;
            }

            if (e.button !== 0) return;

            e.preventDefault();
            e.stopPropagation();

            startX = e.clientX;
            startY = e.clientY;

            const rect = element.getBoundingClientRect();
            initialLeft = rect.left;
            initialTop = rect.top;

            isDragging = true;

            element.style.opacity = '0.9';
            element.style.boxShadow = '0 8px 30px rgba(0,0,0,0.3)';
            element.style.transition = 'none';
            element.style.zIndex = '10002';

            document.addEventListener('mousemove', onDrag);
            document.addEventListener('mouseup', stopDrag);
        }

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

            const dx = e.clientX - startX;
            const dy = e.clientY - startY;

            let newX = initialLeft + dx;
            let newY = initialTop + dy;

            const minX = -element.offsetWidth + 50;
            const maxX = window.innerWidth - 50;
            const minY = -element.offsetHeight + 50;
            const maxY = window.innerHeight - 50;

            newX = Math.max(minX, Math.min(newX, maxX));
            newY = Math.max(minY, Math.min(newY, maxY));

            element.style.left = `${newX}px`;
            element.style.top = `${newY}px`;
        }

        function stopDrag(e) {
            if (!isDragging) return;

            isDragging = false;

            document.removeEventListener('mousemove', onDrag);
            document.removeEventListener('mouseup', stopDrag);

            element.style.opacity = '';
            element.style.boxShadow = '0 4px 20px rgba(0,0,0,0.15)';
            element.style.transition = 'all 0.3s ease';
            element.style.zIndex = '10001';

            const rect = element.getBoundingClientRect();
            GM_setValue('panelPosition', {
                x: rect.left,
                y: rect.top
            });
        }

        window.addEventListener('resize', () => {
            const rect = element.getBoundingClientRect();
            const maxX = window.innerWidth - 50;
            const maxY = window.innerHeight - 50;

            if (rect.left > maxX || rect.top > maxY) {
                element.style.left = `${Math.min(rect.left, maxX)}px`;
                element.style.top = `${Math.min(rect.top, maxY)}px`;
            }
        });
    }

    // 显示控制面板
    function showControlPanel() {
        CONFIG.showPanel = true;
        saveConfig();
        currentPanel = createControlPanel();
    }

    // 重置所有设置
    function resetAllSettings() {
        if (confirm('确定要重置所有设置吗?\n这将重置所有开关和面板位置。')) {
            GM_setValue('feedEnabled', true);
            GM_setValue('chatEnabled', true);
            GM_setValue('discussEnabled', true);
            GM_setValue('showPanel', true);
            GM_setValue('panelPosition', null);
            window.location.reload();
        }
    }

    // ==================== 界面反馈 ====================

    function showStatusNotice(message) {
        const oldNotice = document.getElementById('miao-status-notice');
        if (oldNotice) oldNotice.remove();

        const notice = document.createElement('div');
        notice.id = 'miao-status-notice';
        notice.textContent = message;
        notice.style.cssText = `
            position: fixed !important;
            bottom: 20px !important;
            left: 50% !important;
            transform: translateX(-50%) !important;
            background: linear-gradient(135deg, ${getPageColor()} 0%, ${getPageColor(true)} 100%) !important;
            color: white !important;
            padding: 10px 20px !important;
            border-radius: 8px !important;
            font-size: 13px !important;
            z-index: 10000 !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
            animation: miaoSlideUp 0.3s ease !important;
            max-width: 300px !important;
            text-align: center !important;
        `;

        if (!document.querySelector('#miao-notice-animation')) {
            const style = document.createElement('style');
            style.id = 'miao-notice-animation';
            style.textContent = `
                @keyframes miaoSlideUp {
                    from { transform: translateX(-50%) translateY(100%); opacity: 0; }
                    to { transform: translateX(-50%) translateY(0); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
        }

        document.body.appendChild(notice);

        setTimeout(() => {
            if (notice.parentNode) {
                notice.style.opacity = '0';
                notice.style.transition = 'opacity 0.5s';
                setTimeout(() => notice.remove(), 500);
            }
        }, 3000);
    }

    // 获取页面颜色
    function getPageColor(isDark = false) {
        if (isChatPage) return isDark ? '#2E7D32' : '#4CAF50';
        if (isDiscussPage) return isDark ? '#7B1FA2' : '#9C27B0';
        return isDark ? '#764ba2' : '#667eea';
    }

    // ==================== 主初始化 ====================

    function init() {
        const pageName = isChatPage ? '私信' : (isDiscussPage ? '讨论区' : '犇犇');
        console.log(`🚀 初始化洛谷喵化助手 v1.8.1 (${pageName}模式)`);

        setupRouteMonitoring();

        if (CONFIG.showPanel) {
            currentPanel = createControlPanel();
        }

        if (!isFeatureEnabled) {
            console.log('功能已禁用,跳过初始化');
            showStatusNotice(`🐱 ${pageName}喵化功能已禁用`);
            return;
        }

        showStatusNotice('正在寻找输入框...');

        setTimeout(() => {
            const inputBox = findInputBox();
            if (inputBox) {
                setupSmartListener(inputBox);
                showStatusNotice(`🐱 ${pageName}喵化助手已就绪`);
            }
        }, 1500);
    }

    // ==================== 启动脚本 ====================

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(init, 1000);
        });
    } else {
        setTimeout(init, 1000);
    }

    console.log('✅ 洛谷喵化助手 v1.8.1 初始化完成');
})();