// ==UserScript== // @name 吾爱破解增强助手 // @version 1.1.1 // @description 自动签到、无缝翻页、水评论屏蔽、界面美化、内容过滤、悬停预览、版块排序、快捷键等综合增强 // @author 原作者:X.I.U、Tsing、91mdz、MarsTLBAD、wcx19911123、果心豆腐酱;重构:MR.WOO;优化:性能与缺陷修复 // @match https://www.52pojie.cn/* // @homepage https://greasyfork.org/users/20787 // @icon http://52pojie.cn/favicon.ico // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_getValue // @grant GM_setValue // @grant GM_getValues // @grant GM_setClipboard // @license MIT // @run-at document-end // @namespace https://greasyfork.org/users/20787 // ==/UserScript== (function () { 'use strict'; /* ==================== 基础工具 ==================== */ const $ = (selector, ctx = document) => ctx.querySelector(selector); const $$ = (selector, ctx = document) => [...ctx.querySelectorAll(selector)]; const debounce = (fn, delay) => { let timer = null; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; }; const parseHtmlDom = htmlStr => new DOMParser().parseFromString(htmlStr, 'text/html'); // 注意:必须用 function 而非箭头函数,否则作为对象方法调用时 this 恒为 undefined const runIfEnable = (fn, cfgKey) => function (...args) { return config[cfgKey] && fn.apply(this, args); }; /* ==================== 常量 ==================== */ const STORAGE_PREFIX = 'hp52_'; const SEL = Object.freeze({ postList: '#postlist', postItem: '#postlist .plhin:not(.res-postfirst)', postContent: '.t_f', threadList: '#threadlisttableid', threadItem: '#threadlist tbody[id^="normalthread_"]', nextPageBtn: 'a.nxt[href]', forumNextPage: '#autopbn', rateBtn: 'table.ratl a.y.xi2.op', captchaInput: 'input[name="secanswer"]', captchaAnswer: '#seccodeqS0_menu', fastPostTextarea: '#fastpostmessage', settingsEntry: '#g_upmine', rewardIcon: 'img[alt="悬赏"]', globalStickyTitle: '全局置顶主题', goTopBtn: '#goTopBtn', navBar: '#nv', signImg: '#um > p:nth-child(3) > a:nth-child(1) > img', signBtn: '#res-sign > a', }); // 水评论词库:仅用于精确整句匹配(Set 查找,O(1),替代原 92 分支大正则) const WATER_COMMENTS = [ "小小心意,意思一下", "正好需要", "这么厉害!必须给个红包鼓励下", "YYDS~!!", "太厉害了!", "谢分享", "大佬继续更新吧!!!", "6666666", "谢谢@Thanks!", "Thanks", "我很赞同!", "感谢发布原创作品,精易论坛因你更精彩!", "用用试试,看看牛不牛", "鼓励转贴优秀软件安全工具和文档!", "热心回复!", "欢迎分析讨论交流,吾爱破解论坛有你更精彩!", "用心讨论,共获提升!", "感谢您的宝贵建议,我们会努力争取做得更好!", "看起来很强大", "下来试试", "感谢大佬分享", "感谢大大的分享", "好东西先收藏。", "牛,试试看", "支持一下", "厉害了,先收藏", "前来看看", "谢楼主", "感谢LZ分享", "这个看起来很厉害", "有此需求,下来看看", "支持分享", "不错,试试", "虽然不知道怎么用,但还是关注一下", "不错的软件", "楼主好强", "不错,谢谢", "感谢大佬", "先试试再说", "厉害厉害", "感谢发布", "感觉很强大", "看起来", "大佬技术", "好厉害", "好东西", "学习学习", "支持作者大大", "感谢你的分享", "收藏了 很有用", "真的很不错", "楼主辛苦了", "谢大佬", "感谢无私分享", "谢谢谢", "多大用处", "谢谢提供", "支持大佬", "牛逼牛逼", "下载看看", "好心人", "顶级大佬", "我的大佬", "不容错过", "论坛有您更精彩", "感谢大神分享", "大佬牛逼", "谢谢大大", "牛啊大佬", "大佬66", "不得不赞", "厉害了!", "内容自动屏蔽", "不错不错", "收藏备用,谢谢", "很好用,谢谢!", "论坛禁止求脱求破", "未能按照本版块发帖要求发帖", "请勿灌水", "此为违规行为", "广告贴", "感谢您的宝贵建议", "感谢发布原创作品", "欢迎分析讨论交流", "已经处理", "鼓励转贴", "用心讨论" ]; const WATER_COMMENT_SET = new Set(WATER_COMMENTS); /* ==================== 设置项(单一数据源) ==================== 面板、默认配置、样式类全部由此派生,避免三处重复维护。 cls:该项对应的 body 样式类名(无则仅作开关使用) act:切换开关时需要额外执行的动作名 =================================================================== */ const SETTINGS = [ { group: '🔁 自动任务', key: 'autoPageFlip', label: '版块自动无缝翻页' }, { group: '🔁 自动任务', key: 'threadAutoPage', label: '帖子内自动翻页' }, { group: '🔁 自动任务', key: 'autoFoldRate', label: '自动收起免费评分', act: 'rate' }, { group: '🔁 自动任务', key: 'autoFillCaptcha', label: '自动填写回复验证码' }, { group: '🔁 自动任务', key: 'autoSortByCreateTime', label: '版块按发帖时间排序', act: 'sort' }, { group: '🔁 自动任务', key: 'searchSortTime', label: '搜索页按发布时间排序' }, { group: '🔁 自动任务', key: 'autoSign', label: '进入页面后台自动签到', act: 'sign' }, { group: '🚫 内容过滤', key: 'deleteWaterComment', label: '自动屏蔽水评论', act: 'water' }, { group: '🚫 内容过滤', key: 'hideRewardPost', label: '屏蔽导读悬赏贴', act: 'reward' }, { group: '🚫 内容过滤', key: 'hideStickyGlobal', label: '隐藏全局置顶帖', cls: 'hp52-hide-global-sticky' }, { group: '🚫 内容过滤', key: 'hideTopThreads', label: '隐藏分区置顶帖', cls: 'hp52-hide-top-threads' }, { group: '🚫 内容过滤', key: 'hideAvatarDetail', label: '隐藏头像下方详情(奖章/统计)', cls: 'hp52-hide-avatar-detail' }, { group: '🚫 内容过滤', key: 'hideRating', label: '隐藏评分区域', cls: 'hp52-hide-rating' }, { group: '🚫 内容过滤', key: 'hideComment', label: '隐藏点评模块', cls: 'hp52-hide-comment' }, { group: '🎨 界面美化', key: 'hideBannerText', label: '隐藏分区版头说明', cls: 'hp52-hide-banner' }, { group: '🎨 界面美化', key: 'hideTopBar', label: '隐藏顶部入门工具栏', cls: 'hp52-hide-topbar' }, { group: '🎨 界面美化', key: 'hideSignature', label: '隐藏用户签名', cls: 'hp52-hide-signature' }, { group: '🎨 界面美化', key: 'hideColorLinks', label: '隐藏彩色链接', cls: 'hp52-hide-color-links' }, { group: '🎨 界面美化', key: 'hideDefaultAvatar', label: '隐藏默认头像', cls: 'hp52-hide-default-avatar' }, { group: '🎨 界面美化', key: 'showThreadNumber', label: '显示帖子序号', cls: 'hp52-show-thread-num' }, { group: '🎨 界面美化', key: 'circleAvatar', label: '圆形用户头像', cls: 'hp52-circle-avatar' }, { group: '🎨 界面美化', key: 'imgShadow', label: '帖子图片阴影边框', cls: 'hp52-img-shadow' }, { group: '🎨 界面美化', key: 'hideImgTip', label: '隐藏图片悬浮弹窗', cls: 'hp52-hide-img-tip' }, { group: '🎨 界面美化', key: 'clearPageBg', label: '纯净页面背景', cls: 'hp52-clear-bg' }, { group: '🎨 界面美化', key: 'imageMaxHeight70vh', label: '帖子图片最大高度70vh', cls: 'hp52-img-maxvh70' }, { group: '🎨 界面美化', key: 'removePostMinHeight', label: '移除帖子最小高度限制', cls: 'hp52-rm-post-minh' }, { group: '🎨 界面美化', key: 'smoothScrollFix', label: '页面平滑滚动', cls: 'hp52-smooth-scroll' }, { group: '🔍 交互增强', key: 'hoverPreview', label: '悬停预览帖子内容', act: 'preview' }, { group: '🔍 交互增强', key: 'shortcutEnterReply', label: '按Enter快速跳到回复框', act: 'shortcut' }, { group: '🔍 交互增强', key: 'lazySignatureImage', label: '签名图片懒加载', act: 'lazySign' }, { group: '🔍 交互增强', key: 'doubleNavToTop', label: '双击导航栏回到顶部' }, { group: '🔍 交互增强', key: 'codeBlockTools', label: '代码块折叠/复制按钮', act: 'codeTools' }, ]; // 默认开关值(保持不变:仅 hideSignature / hideDefaultAvatar / hideRating / hideComment / hoverPreview 默认关) const DEFAULT_OFF = new Set(['hideSignature', 'hideDefaultAvatar', 'hideRating', 'hideComment', 'hoverPreview']); const DEFAULT_CONFIG = Object.fromEntries(SETTINGS.map(s => [s.key, !DEFAULT_OFF.has(s.key)])); /* ==================== 配置读写 ==================== */ // GM_getValues 为 TM4+ 接口,老环境降级为逐项读取 const config = typeof GM_getValues === 'function' ? GM_getValues(DEFAULT_CONFIG) : Object.fromEntries(Object.entries(DEFAULT_CONFIG).map(([k, def]) => [k, GM_getValue(k, def)])); function refreshStyle() { for (const s of SETTINGS) { if (s.cls) document.body.classList.toggle(s.cls, !!config[s.key]); } } /* ==================== 样式注入 ==================== */ (function injectBaseStyle() { if (document.getElementById('hp52_base_style')) return; const style = document.createElement('style'); style.id = 'hp52_base_style'; style.textContent = ` @keyframes fadeIn{from{opacity:0}to{opacity:1}} a[href="connect.php?mod=config"], #chart, #ft, #custominfo_pmenu, #loadad2, #aswift_0, .dnch_eo_pt, .dnch_eo_pr, .dnch_eo_mu, .dnch_eo_f, ul.xl.xl2.o.cl, dl.pil.cl, td.plc.plm, .dnch_eo_pb, .pls .side-star, .pls .side-group, .res-footer-note, .scbar_hot_td, .md_ctrl, .pls.favatar .xg1 { display:none !important; } #postlist .plc .t_f img, #postlist .plc .tattl img { max-height: 600px !important; width: auto !important; } .pls .avatar { text-align:center; } .t_fsz { min-height:15px; } .pls .pi { text-align:center; padding:10px 0 0 0; border:none; overflow:visible; } .xw1 { font-size:12px; font-weight:500; } textarea#fastpostmessage { background:none !important; } .pcb img { max-width:80%; margin:4px; } .rate { margin:0; } .ratl td { padding:0px; } .xi2,.xi2 a,.xi3 a { color:red; } .toptitle_7ree td { border-top: 1px solid #CDCDCD; } .mtw { margin-top:0px !important; } body.hp52-hide-banner .bml, body.hp52-hide-banner #ct > div > div.bm.bml.pbn > div.bm_c.cl.pbn{ display:none !important; } body.hp52-hide-topbar #toptb{ display: none !important; } body.hp52-hide-top-threads #threadlisttableid tbody[id^=stickthread_]{ display: none !important; } body.hp52-hide-default-avatar #postlist div.avatar:has(img[src*=noavatar]){ display: none !important; } body.hp52-hide-signature td.plc.plm div.sign{ display:none !important; } body.hp52-hide-color-links #postlist div.vw50_kfc_pb, body.hp52-hide-color-links #postlist div.vw50_kfc_pt{ display:none !important; } body.hp52-show-thread-number #threadlisttableid tbody[id^=normalthread_]{ counter-increment:thread-index; } body.hp52-show-thread-number #threadlisttableid tbody[id^=normalthread_] .xst::before{ content:counter(thread-index) "、"; font-weight:bold; margin-right:4px; } @media (min-width:1366px){ body.hp52-circle-avatar .pls .avatar img { width:60px; height:60px; border-radius:60px; background:none; padding:0; border:4px solid #ffffff; box-shadow:0 0 4px #bbbbbb; } body.hp52-circle-avatar .avtm img { width:60px; } } body.hp52-hide-img-tip .aimg_tip { display:none !important; } body.hp52-clear-bg { background:none !important; } body.hp52-img-shadow .zoom { box-shadow: 0 0px 4px #444444; } body.hp52-hide-global-sticky .global-sticky-item { display: none !important; } body.hp52-hide-avatar-detail div.tns.xg2, dl.credit-list { display:none !important; } body.hp52-hide-rating div.pcb > h3.psth.xs1, dl.rate { display:none !important; } body.hp52-hide-comment div.pcb > div.cm { display:none !important; } /* 修复:原写法第二条选择器漏了 body 前缀,导致规则无条件全局生效 */ body.hp52-img-maxvh70 #postlist .plc .t_f img, body.hp52-img-maxvh70 #postlist .plc .tattl img { max-height:70vh !important; } body.hp52-rm-post-minh .pcb > .t_fsz { min-height:auto !important; } body.hp52-smooth-scroll html { scroll-behavior: smooth; } .authicn { cursor: initial; } /* 代码块工具按钮 */ .hp52-code-btn { font-style: normal; margin-right: 8px; } /* 无独立内容容器时(纯文本 pre),压高度露出按钮行即可 */ pre.hp52-code-collapsed { max-height: 2.2em !important; overflow: hidden !important; } `; document.head.appendChild(style); })(); /* ==================== Toast ==================== */ function showToast(message, type = 'success') { const toast = document.createElement('div'); toast.style.cssText = ` position: fixed; top: 20%; left: 50%; transform: translateX(-50%); padding: 10px 20px; border-radius: 8px; z-index: 99999; background: ${type === 'success' ? '#e7f4ff' : '#fff3e7'}; color: ${type === 'success' ? '#3fc91d' : '#CC5500'}; font-size:14px; box-shadow:0 2px 10px rgba(0,0,0,0.1); animation: fadeIn 0.3s ease; `; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.3s'; setTimeout(() => toast.remove(), 300); }, 2000); } /* ==================== 无缝翻页 ==================== */ const PAGE_TYPES = { thread: { next: () => $(SEL.nextPageBtn)?.href || '', source: doc => $$('#postlist > div[id^="post_"]', doc), target: () => $(SEL.postList), pager: doc => [$(SEL.nextPageBtn), $(SEL.nextPageBtn, doc)], }, forum: { // 版块页「下一页」为 #autopbn 按钮 next: () => { const btn = $(SEL.forumNextPage); return btn && btn.textContent.includes('下一页') ? btn.href : ''; }, source: doc => $$('#threadlist .bm_c table tbody', doc).filter(t => t.id?.startsWith('normalthread_')), target: () => $('#threadlist .bm_c table'), pager: doc => [$(SEL.forumNextPage), $(SEL.forumNextPage, doc)], syncText: true, }, // 导读 / 搜索 / 收藏 / 专辑:统一按通用列表结构处理 list: { next: () => $(SEL.nextPageBtn)?.href || '', source: (doc) => { const rows = $$('#threadlist tbody[id^="normalthread_"]', doc); if (rows.length) return rows; return $$('#threadlist .bm_c table tbody', doc).filter(t => t.id?.startsWith('normalthread_')); }, target: () => $('#threadlist .bm_c table') || $('#threadlist table') || $('#threadlist'), pager: doc => [$(SEL.nextPageBtn), $(SEL.nextPageBtn, doc)], }, }; const PageLoader = { nextUrl: '', loading: false, failCount: 0, init: runIfEnable(function () { // 哨兵元素上移 800px,使「即将滚动到底」时提前触发加载 const sentinel = document.createElement('div'); sentinel.id = 'helper_page_sentinel'; sentinel.style.cssText = 'height:1px;margin-top:-800px;'; document.body.appendChild(sentinel); const observer = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && !this.loading) this.loadNextPage(); }, { rootMargin: '200px' }); observer.observe(sentinel); }, 'autoPageFlip'), getSiteType() { const { pathname: path, search } = location; if (/thread-\d+-\d+-\d+\.html/.test(path) || search.includes('mod=viewthread')) { return config.threadAutoPage ? 'thread' : null; } if (/forum-\d+-\d+\.html/.test(path) || search.includes('mod=forumdisplay')) return 'forum'; if (search.includes('mod=guide') || search.includes('mod=collection') || search.includes('do=favorite') || path === '/search.php') return 'list'; return null; }, loadNextPage() { const type = this.getSiteType(); if (!type || this.failCount >= 3) return; const schema = PAGE_TYPES[type]; const url = schema.next(); if (!url || url === this.nextUrl) return; this.nextUrl = url; this.loading = true; const done = () => { this.loading = false; }; GM_xmlhttpRequest({ url, method: 'GET', overrideMimeType: 'text/html; charset=gbk', timeout: 8000, onload: (res) => { try { const doc = parseHtmlDom(res.responseText); const source = schema.source(doc); const target = schema.target(); if (source.length && target) { const fragment = document.createDocumentFragment(); source.forEach(el => fragment.appendChild(el)); target.appendChild(fragment); } const [oldPager, newPager] = schema.pager(doc); if (oldPager && newPager) { oldPager.href = newPager.href; if (schema.syncText) oldPager.textContent = newPager.textContent; } this.failCount = 0; handleNewContentAdded(source); } catch (e) { this.failCount++; console.error('[52helper] 翻页解析失败', e); } finally { done(); } }, onerror: () => { this.failCount++; done(); }, ontimeout: () => { this.failCount++; done(); }, }); }, }; /* ==================== 内容过滤 ==================== */ // 水评论:整句精确匹配命中即删除 function processSingleWaterComment(commentEl) { if (commentEl.dataset.waterChecked) return; commentEl.dataset.waterChecked = '1'; const content = commentEl.querySelector(SEL.postContent)?.textContent?.trim(); if (content && WATER_COMMENT_SET.has(content)) commentEl.remove(); } const processAllWaterComments = () => $$(SEL.postItem).forEach(processSingleWaterComment); // 屏蔽导读页悬赏贴 function processSingleRewardPost(tbodyEl) { if (tbodyEl.dataset.rewardChecked) return; tbodyEl.dataset.rewardChecked = '1'; if (tbodyEl.querySelector(SEL.rewardIcon)) tbodyEl.remove(); } function processAllRewardPosts() { if (!location.search.includes('mod=guide&view=newthread')) return; $$(SEL.threadItem).forEach(processSingleRewardPost); } // 全局置顶帖打标(由 CSS 控制显隐,切换开关无需重算) function markGlobalSticky() { $$('#threadlisttableid tr > td.icn > a').forEach((a) => { if (a.getAttribute('title')?.includes(SEL.globalStickyTitle)) { a.closest('tbody')?.classList.add('global-sticky-item'); } }); } /* ==================== 自动收起评分 ==================== */ const FOLD_KEY = STORAGE_PREFIX + 'foldedRateList'; const FOLD_MAX = 2000; // 防止记录无限膨胀 const foldedRateList = new Set(GM_getValue(FOLD_KEY, [])); // 合并写入,避免每条评分都触发一次存储序列化 const saveFoldedList = debounce(() => { GM_setValue(FOLD_KEY, [...foldedRateList].slice(-FOLD_MAX)); }, 500); function processSingleRateFold(btn) { if (!btn.textContent.includes('收起')) return; const id = btn.getAttribute('onclick')?.match(/\d+/)?.[0]; if (!id || foldedRateList.has(id)) return; foldedRateList.add(id); saveFoldedList(); btn.click(); } const processAllRateFold = () => $$(SEL.rateBtn).forEach(processSingleRateFold); /* ==================== 自动填写验证码 ==================== */ const autoFillCaptcha = runIfEnable(function () { const input = $(SEL.captchaInput); const answerEl = $(SEL.captchaAnswer); const textarea = $(SEL.fastPostTextarea); if (!input || !answerEl || !textarea || input.value) return; const answer = answerEl.innerHTML.split('答案:').pop(); if (!answer) return; textarea.addEventListener('focus', () => { input.value = answer; setTimeout(() => textarea.focus(), 100); }, { once: true }); }, 'autoFillCaptcha'); /* ==================== 版块按发帖时间排序 ==================== */ const autoSortByThreadCreate = runIfEnable(function () { const { pathname: pn, search: sn } = location; const fid = pn.match(/^\/forum-(\d+)-\d+\.html$/)?.[1] ?? sn.match(/fid=(\d+)/)?.[1]; if (!fid) return; const markKey = STORAGE_PREFIX + 'sort_mark_fid_' + fid; // 已跳转过则只打标记,避免重定向死循环 if (sn.includes('filter=author&orderby=dateline')) { sessionStorage.setItem(markKey, '1'); return; } if (sessionStorage.getItem(markKey)) return; sessionStorage.setItem(markKey, '1'); location.assign(`forum.php?mod=forumdisplay&fid=${fid}&filter=author&orderby=dateline`); }, 'autoSortByCreateTime'); /* ==================== 悬停预览 ==================== */ let previewFrame = null; let hoverTimer = null; const PREVIEW_LINK = '#threadlisttableid tbody[id^=normalthread_] th.common > a[href^=thread]'; function onPreviewOver(e) { const link = e.target.closest(PREVIEW_LINK); if (!link) return; clearTimeout(hoverTimer); hoverTimer = setTimeout(() => { if (!previewFrame) return; const rect = link.getBoundingClientRect(); const left = Math.min(rect.right + 10, window.innerWidth * 0.3); previewFrame.style.top = '63px'; previewFrame.style.left = left + 'px'; previewFrame.style.width = (window.innerWidth - left - 30) + 'px'; previewFrame.style.height = (window.innerHeight - 93) + 'px'; if (previewFrame.src !== link.href) previewFrame.src = link.href; previewFrame.style.display = ''; }, 120); } function onPreviewOut() { clearTimeout(hoverTimer); if (previewFrame && !previewFrame.matches(':hover')) previewFrame.style.display = 'none'; } function initHoverPreview() { if (!config.hoverPreview) { // 关闭时必须同时摘掉全局监听,否则反复开关会重复注册 document.removeEventListener('mouseover', onPreviewOver); document.removeEventListener('mouseout', onPreviewOut); clearTimeout(hoverTimer); previewFrame?.remove(); previewFrame = null; return; } if (previewFrame) return; previewFrame = document.createElement('iframe'); previewFrame.style.cssText = 'position:fixed;border:1px solid #ccc;display:none;z-index:9999;'; document.body.appendChild(previewFrame); document.addEventListener('mouseover', onPreviewOver); document.addEventListener('mouseout', onPreviewOut); } /* ==================== 签名图懒加载 ==================== */ const lazySignatureImage = (root = document) => $$('div.sign img:not([loading])', root).forEach(el => el.setAttribute('loading', 'lazy')); /* ==================== 代码块:折叠 + 复制 ==================== */ const CODE_BTN_CLS = 'hp52-code-btn'; const CODE_UNIT_SEL = '.viewsource, pre'; // 每个按钮持有同一份 record:折叠目标 + 复制源 const codeRecords = new WeakMap(); // 复制到剪贴板:GM API → 异步 API → execCommand 三级降级 function setCopy(text, msg = '已复制到剪贴板') { const notify = () => showToast(msg, 'success'); const fallback = () => { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;top:0;left:-9999px;opacity:0;'; document.body.appendChild(ta); ta.select(); let ok = false; try { ok = document.execCommand('copy'); } catch (e) { /* 权限受限 */ } ta.remove(); ok ? notify() : showToast('复制失败,请手动选择复制', 'warn'); }; if (typeof GM_setClipboard === 'function') { try { GM_setClipboard(text, 'text'); notify(); return; } catch (e) { /* 继续降级 */ } } if (navigator.clipboard?.writeText) { navigator.clipboard.writeText(text).then(notify, fallback); } else { fallback(); } } // 单节点取文本:ol/ul 按行拼接,避免行内容粘连成一段 function extractCode(node) { if (node.nodeType === Node.TEXT_NODE) return node.nodeValue; const tag = node.tagName; if ((tag === 'OL' || tag === 'UL') && node.children.length) { return [...node.children].map(li => li.innerText || li.textContent).join('\n'); } return node.innerText || node.textContent || ''; } // 取容器内全部代码文本,排除脚本注入的按钮自身 function collectCode(container) { return [...container.childNodes] .filter(n => !n.classList?.contains(CODE_BTN_CLS)) .map(extractCode) .join('') .replace(/\s+$/, ''); } function makeCodeBtn(text, act) { const em = document.createElement('em'); em.className = CODE_BTN_CLS; em.dataset.act = act; em.style.cssText = 'cursor:pointer;font-size:12px;color:#369 !important;'; em.textContent = ' ' + text; return em; } // 工具栏型代码块(.viewsource):内容区为独立元素,直接 display 切换 function attachViewSourceTools(vs) { const bar = vs.parentElement; if (!bar || bar.querySelector('.' + CODE_BTN_CLS)) return; const box = bar.parentElement; if (!box) return; const content = [...box.children].find( el => el !== bar && /^(OL|PRE|DIV)$/.test(el.tagName) && el.querySelector('li, pre, code') ) || box.lastElementChild; if (!content || content === bar) return; const toggle = makeCodeBtn('隐藏代码', 'toggle'); const copy = makeCodeBtn('复制代码', 'copy'); bar.appendChild(toggle); bar.appendChild(copy); const rec = { el: content, mode: 'display', src: content, collapsed: false, btn: toggle }; codeRecords.set(toggle, rec); codeRecords.set(copy, rec); } // 裸 pre:无独立内容容器,折叠态加在 pre 自身上 function attachPreTools(pre) { if (pre.dataset.hp52Code) return; pre.dataset.hp52Code = '1'; const toggle = makeCodeBtn('隐藏代码', 'toggle'); const copy = makeCodeBtn('复制代码', 'copy'); pre.insertBefore(toggle, pre.firstChild); pre.insertBefore(copy, pre.firstChild); const rec = { el: pre, mode: 'class', src: pre, collapsed: false, btn: toggle }; codeRecords.set(toggle, rec); codeRecords.set(copy, rec); } function onCodeBlockClick(e) { const btn = e.target.closest?.('.' + CODE_BTN_CLS); if (!btn) return; const rec = codeRecords.get(btn); if (!rec) return; if (btn.dataset.act === 'copy') { setCopy(collectCode(rec.src), '代码已复制到剪贴板'); return; } rec.collapsed = !rec.collapsed; if (rec.mode === 'display') rec.el.style.display = rec.collapsed ? 'none' : ''; else rec.el.classList.toggle('hp52-code-collapsed', rec.collapsed); rec.btn.textContent = rec.collapsed ? ' 显示代码' : ' 隐藏代码'; } document.addEventListener('click', onCodeBlockClick); function processCodeUnit(el) { if (el.tagName === 'PRE') attachPreTools(el); else attachViewSourceTools(el); } const initCodeBlockTools = () => $$(CODE_UNIT_SEL).forEach(processCodeUnit); /* ==================== 滚动与快捷键 ==================== */ function initScrollTopEnhance() { const scrollTop = () => window.scrollTo({ top: 0, behavior: 'smooth' }); if (config.doubleNavToTop) { const nv = $(SEL.navBar); if (nv) nv.addEventListener('dblclick', scrollTop); } const goTopBtn = $(SEL.goTopBtn); if (goTopBtn) goTopBtn.onclick = scrollTop; } function handleShortcutKey(e) { const tag = e.target.tagName; if (tag === 'TEXTAREA' || tag === 'INPUT' || e.key !== 'Enter') return; const reply = $(SEL.fastPostTextarea); if (!reply) return; reply.scrollIntoView(); reply.focus(); e.preventDefault(); } function toggleShortcutHandler() { document.removeEventListener('keydown', handleShortcutKey); if (config.shortcutEnterReply) document.addEventListener('keydown', handleShortcutKey); } /* ==================== 后台自动签到 ==================== */ const SIGN_OK = 'https://www.52pojie.cn/home.php?mod=task&item=new'; const SIGN_WAF = 'https://www.52pojie.cn/waf_text_verify.html'; function autoSignFunc() { if (!config.autoSign || window !== window.top) return; const sign1 = $(SEL.signImg); const sign2 = $(SEL.signBtn); const url = sign1?.parentElement?.href; if (!sign1 || !sign2 || !url?.startsWith('https://www.52pojie.cn/home.php?mod=task')) return; showToast('后台签到中...', 'normal'); const iframe = document.createElement('iframe'); iframe.src = url; iframe.style.display = 'none'; document.body.appendChild(iframe); sign1.title = '后台签到中...'; sign1.style.opacity = 0.5; sign1.style.cursor = 'progress'; sign1.height = 20; sign1.src = 'https://static.52pojie.cn/static/image/common/imageloading.gif'; sign1.parentElement.removeAttribute('href'); sign2.textContent = '后台签到中...'; sign2.style.opacity = 0.5; sign2.style.cursor = 'progress'; sign2.removeAttribute('href'); const restoreUi = (msg, restoreHref, icon) => { sign1.title = msg; sign1.style.opacity = 1; sign1.style.cursor = 'default'; sign1.src = icon; sign2.textContent = msg; sign2.style.opacity = 1; sign2.style.cursor = 'default'; if (restoreHref) sign1.parentElement.href = url; }; // 必须设上限:否则 iframe 一直没到终态时定时器永不停止 const startedAt = Date.now(); const timer = setInterval(() => { let curr = ''; try { curr = iframe.contentWindow.location.href; } catch (e) { clearInterval(timer); iframe.remove(); restoreUi('签到状态未知,请刷新查看。', true, 'https://static.52pojie.cn/static/image/common/qds.png'); return; } if (curr === SIGN_OK || /^https:\/\/www\.52pojie\.cn\/*$/.test(curr)) { clearInterval(timer); iframe.remove(); showToast('签到成功!', 'success'); restoreUi('签到成功!', false, 'https://static.52pojie.cn/static/image/common/wbs.png'); setTimeout(() => sign2.remove(), 2000); } else if (curr.startsWith(SIGN_WAF)) { clearInterval(timer); iframe.remove(); showToast('触发防火墙,请刷新检查签到状态', 'warn'); restoreUi('触发了防火墙,请稍后刷新页面检查是否签到成功。', true, 'https://static.52pojie.cn/static/image/common/qds.png'); } else if (Date.now() - startedAt > 15000) { clearInterval(timer); iframe.remove(); restoreUi('签到超时,请稍后刷新页面检查。', true, 'https://static.52pojie.cn/static/image/common/qds.png'); } }, 500); } /* ==================== 设置面板 ==================== */ function addSettingsEntry() { const mine = $(SEL.settingsEntry); if (!mine) return; const entry = document.createElement('a'); entry.href = 'javascript:void(0);'; entry.textContent = '综合助手设置'; entry.style.marginLeft = '8px'; entry.addEventListener('click', openSettingsPanel); mine.parentNode.insertBefore(entry, mine.nextSibling); } function openSettingsPanel() { if ($('#forum_helper_settings')) return; const panel = document.createElement('div'); panel.id = 'forum_helper_settings'; panel.style.cssText = ` position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; padding:20px 26px; border-radius:10px; box-shadow:0 0 20px rgba(0,0,0,0.3); z-index:99999; min-width:460px; max-height:85vh; overflow-y:auto; box-sizing:border-box; user-select:none; `; const esc = s => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); let html = `