// ==UserScript==
// @name B站评论树 · 时间轴
// @namespace local.bili.comment.timeline
// @version 1.7.44
// @description 把B站评论区重建成带圆环节点的时间轴树状视图,楼中楼按真实层级缩进,整栋可折叠,跟随深浅色主题
// @author congeejun
// @license MIT
// @homepageURL https://greasyfork.org/zh-CN/scripts/607651
// @supportURL https://greasyfork.org/zh-CN/scripts/607651/feedback
// @compatible edge
// @compatible chrome
// @match https://www.bilibili.com/video/*
// @match https://www.bilibili.com/list/*
// @match https://www.bilibili.com/medialist/*
// @match https://www.bilibili.com/bangumi/play/*
// @match https://www.bilibili.com/cheese/play/*
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAASFBMVEVTV2Dt2+IgICf1Z5AVGS8eHyaUnZ79rMb6jaweHydBLTl0eIW9xMUAAFU4OkJ6gIseICYhIikbHCMAAACBhpMdHSQWFx76cpkLVoMeAAAAGHRSTlP//+//D1z///+b////A////v79AP8q///fvveCAAACD0lEQVR42u2XXVfDIAyGQ4CtVTcJdfT//1MDtjo+2gL1xnPM5c7yLAnw7g1Ma+gRTVVYHLX6ToM1HYmoDmD4m/iN8AA1PbA6e2WgmtQCUJNuTPd9kNGBECpozw9F6KWCh+nJ94SlAuzLZwLPgQG6N58JPAboL4ABRk2gC6fcUgKMlKQ75+qv1DhB3AFZBwDOUu0YbxCdIVl8E0K84ReBihEPAeLfJyFmOQtBnsDlWJeEjauzjxiAFyHneZbiwp0xBAqBz4QU4MQ1AK7C+QrgoxCvZOsAXMBrCfBOTyUctIClFu57LaRDLIbZHuJ6jKL2GDOAJwzDQK72KuYAQ1LKF9sPsMRT/NsAc7oClMOM3afA53fha3CpJmQ3EYUY5CAEBMLeFdoA8GOSs+TH5O9yrAe2pFMxgByEt+RfE0tdpgeYExLA8hj9ew7PEXaUoAKQ6UGkBEctvPsWcEcJikO0dlGkYRnijhJsSBoEwrX3GJlw9xdpye+6yg7nf0H5BUE5OYNzsn78x3KkB/v+IJeEZn+QSkKzP0glodkfpJLQ7A/ueQvPn1T4g/TUVewTj21eZrcTp9pqNNmp6lNWl72ySt16g9kObv3UvjD6fUH1byxGndqZTNi6/NbW2QTn3372Rtu8N9LT3ti8uVqz5q+7s9Ibfz0buzONKlm+GcHbu60IY4rbu//kph41ocJ3V8AnF4b2ASrFLnAAAAAASUVORK5CYII=
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant unsafeWindow
// @connect api.bilibili.com
// @run-at document-idle
// @noframes
// ==/UserScript==
(function () {
'use strict';
const VER = '1.7.44';
/* 早期这里还有一个"存活探针"(右下角先闪一块 vX.Y,挂载成功再消失),
* 用来区分"脚本没跑"和"跑了但失败"。现在胶囊本身就带版本号,而且失败原因
* 由 showDiag 面板直接写在页面上,探针只会多闪一下,已经去掉。 */
/* ============================================================
* 配置
* ============================================================ */
const CONF = {
replyPageSize: 20, // 楼中楼每页条数(主评论走 next 游标,没有固定页大小)
maxReplyPages: 8, // 单栋楼最多拉取页数(160 条)
indent: 26, // 每层缩进(= 头像宽度的 0.8 倍,给挂钩留出 10px 转身空间)
avatar: 32, // 头像尺寸
maxIndentLevel: 8, // 超过不再缩进,避免挤出屏幕
/* 楼中楼少于等于这个条数就直接展开。
* 定 5 的理由:截图里刷屏的都是"展开 2/3 条",<=5 能覆盖绝大多数小楼,
* 而一栋楼一次请求就能拉完(replyPageSize=20),成本可控;
* 再往上调到 10 会让请求量翻倍,收益却只是少点一下。 */
autoExpandMax: 5,
/* 同时最多几个楼中楼请求在飞。自动展开后一屏里会有好几栋楼同时要拉接口,
* B 站对并发很敏感(容易 412),所以排队走。 */
fetchConcurrency: 3,
};
const SORT_HOT = 2;
const SORT_TIME = 0;
/* ============================================================
* 样式
* ============================================================ */
const CSS = `
#tl-root,#tl-headroot{
--tl-fg:#18191c; --tl-fg2:#61666d; --tl-fg3:#9499a0;
--tl-line:#e3e5e7; --tl-line-strong:#c9ccd0;
--tl-pink:#fb7299; --tl-blue:#00a1d6; --tl-red:#f85d5d;
--tl-pill:#f1f2f3; --tl-hover:#f6f7f8; --tl-bg:#fff;
font-size:14px; color:var(--tl-fg); line-height:22px;
font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;
box-sizing:border-box;
}
#tl-root{
/* 底部留白:B 站 / 其它脚本会在视口底部挂一条吸底输入框,
没有这段留白时最后一条评论和「加载更多评论」会被它压住点不到 */
padding-bottom:var(--tl-fb-gap,92px);
}
#tl-root.tl-dark,#tl-headroot.tl-dark{
--tl-fg:#e3e5e7; --tl-fg2:#a2a7ae; --tl-fg3:#757a80;
--tl-line:#33373c; --tl-line-strong:#454a50;
--tl-pill:#2a2d31; --tl-hover:#222528; --tl-bg:#18191c;
}
#tl-root *,#tl-headroot *{box-sizing:border-box;}
#tl-root a{color:inherit;text-decoration:none;}
/* 注意:上面这条带 #tl-root(特异性 1,0,1),会压掉任何单纯写 .tl-at 的规则,
所以正文里的蓝链必须同样带 #tl-root 前缀,否则会被 inherit 成黑色 */
#tl-root a.tl-at{color:var(--tl-blue);}
#tl-root a.tl-at:hover{text-decoration:underline;}
/* 顶栏 */
.tl-head{display:flex;align-items:center;gap:16px;padding:0 0 14px;border-bottom:1px solid var(--tl-line);margin-bottom:16px;}
/* 树视图里这条顶栏会单独挂到 B 站发布框之前(顺序还原成:评论 N / 最热 / 最新 → 输入框 → 时间轴),
所以不再需要那条分隔线,和输入框留一点空隙就够 */
#tl-headroot .tl-head{padding:0 0 8px;border-bottom:0;margin-bottom:10px;}
.tl-title{font-size:19px;font-weight:600;}
.tl-tabs{display:flex;gap:18px;font-size:14px;color:var(--tl-fg2);}
.tl-tab{cursor:pointer;padding-bottom:2px;border-bottom:2px solid transparent;}
.tl-tab.on{color:var(--tl-blue);border-bottom-color:var(--tl-blue);}
.tl-head-right{margin-left:auto;display:flex;gap:14px;font-size:13px;color:var(--tl-fg2);}
.tl-linkbtn{cursor:pointer;}
.tl-linkbtn:hover{color:var(--tl-blue);}
/* 一栋楼 */
.tl-thread{position:relative;padding:14px 0 4px;}
.tl-thread + .tl-thread{border-top:1px solid var(--tl-line);}
/* 行 */
.tl-row{position:relative;display:flex;padding:0 0 12px;}
.tl-av{flex:0 0 auto;width:32px;height:32px;border-radius:50%;overflow:hidden;background:var(--tl-pill);display:block;}
.tl-av img{width:100%;height:100%;object-fit:cover;display:block;}
.tl-main{flex:1 1 auto;min-width:0;padding-left:10px;padding-top:1px;}
/* 昵称行 */
.tl-meta{display:flex;align-items:center;gap:6px;flex-wrap:wrap;height:20px;}
.tl-name{font-size:13px;color:var(--tl-fg2);font-weight:500;}
.tl-name.is-vip{color:var(--tl-pink);}
.tl-name.is-up{color:var(--tl-pink);}
.tl-pill{font-size:12px;color:var(--tl-fg2);background:var(--tl-pill);border-radius:3px;padding:0 5px;height:18px;line-height:18px;}
.tl-lv{font-size:11px;font-weight:700;color:#fff;background:#f28f7c;border-radius:3px;padding:0 4px;height:16px;line-height:16px;letter-spacing:.3px;}
.tl-lv.lv6{background:#f85d5d;}
.tl-lv.lv5{background:#f28f7c;}
.tl-tag{font-size:12px;color:#fff;background:var(--tl-pink);border-radius:3px;padding:0 5px;height:18px;line-height:18px;}
.tl-tag.pin{background:#ff9f3e;}
.tl-tag.up{background:var(--tl-pink);}
/* 正文 */
.tl-content{margin-top:3px;font-size:14px;line-height:22px;word-break:break-word;white-space:pre-wrap;}
/* 注意:这里不再写 .tl-at{color:...}。它特异性只有 0,1,0,会被上面的 #tl-root a{color:inherit}
整条压掉、只留一点误导;真正生效的是 #tl-root a.tl-at(见样式表开头)。 */
.tl-emote{height:20px;vertical-align:-4px;margin:0 1px;}
.tl-pics{display:flex;gap:6px;margin-top:8px;flex-wrap:wrap;}
.tl-pics img{max-width:140px;max-height:140px;border-radius:4px;cursor:zoom-in;display:block;}
/* 操作行 */
.tl-acts{display:flex;align-items:center;gap:18px;margin-top:6px;font-size:13px;color:var(--tl-fg3);height:20px;}
.tl-act{cursor:pointer;display:inline-flex;align-items:center;gap:4px;}
.tl-act:hover{color:var(--tl-blue);}
.tl-act.liked{color:var(--tl-blue);}
.tl-act svg{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.6;}
.tl-act.liked svg{fill:currentColor;stroke:currentColor;}
/* ★ 时间轴:父级头像正下方一条竖线(spine),每个直接子回复用一小段圆角挂钩(tick)接上去。
竖线归属于"父节点"本身,所以无论嵌套多深、子块多高,都不会被顶断。 */
.tl-kid{position:relative;}
.tl-spine{
position:absolute;width:1px;background:var(--tl-line);
pointer-events:none;z-index:0;
}
.tl-tick{
/* 只画一条横线:竖的那一段由父节点的 .tl-spine 提供。
以前这里还有个 border-left + 7px 圆角,1px 线在圆角处被抗锯齿吃掉,
交界会露出一小截断开的"线头",现在做成直角 T 形接合就没有了。 */
position:absolute;pointer-events:none;z-index:0;
border-bottom:1px solid var(--tl-line);
}
.tl-node{
position:absolute;width:12px;height:12px;border-radius:50%;
border:1px solid var(--tl-line-strong);background:var(--tl-bg);
cursor:pointer;z-index:2;transition:border-color .15s,transform .15s;
}
.tl-node::before{
content:'';position:absolute;left:2px;right:2px;top:50%;height:1px;
background:var(--tl-line-strong);transform:translateY(-50%);
}
.tl-node.is-collapsed::after{
content:'';position:absolute;top:2px;bottom:2px;left:50%;width:1px;
background:var(--tl-line-strong);transform:translateX(-50%);
}
.tl-node:hover{border-color:var(--tl-blue);transform:scale(1.15);}
.tl-node:hover::before{background:var(--tl-blue);}
/* 发布时间:纯文本,不要任何"链接感"(不做手型光标 / 悬停变色 / 可点击) */
.tl-time{color:inherit;cursor:default;user-select:text;}
/* 折叠入口:做成胶囊按钮(蓝底白字),楼里一眼就能扫到。
展开 / 收起共用一套外观,位置不动,视线不用重找 */
.tl-folded{
display:inline-flex;align-items:center;gap:4px;
padding:2px 10px;border-radius:999px;
background:var(--tl-blue);color:#fff;
font-size:12px;line-height:1.5;letter-spacing:.2px;
cursor:pointer;user-select:none;transition:background .15s;
}
.tl-folded:hover{background:#00b3ea;color:#fff;}
.tl-children{position:relative;}
/* 状态 */
.tl-state{padding:18px 0;color:var(--tl-fg2);font-size:13px;text-align:center;}
.tl-more{display:block;width:100%;margin:12px 0 4px;padding:9px 0;border:0;border-radius:6px;
background:var(--tl-pill);color:var(--tl-fg2);font-size:14px;cursor:pointer;}
.tl-more:hover{background:var(--tl-hover);color:var(--tl-blue);}
.tl-hidden{display:none !important;}
/* 回复输入框 */
.tl-editor{margin-top:8px;}
.tl-editor textarea{
width:100%;min-height:64px;padding:8px 10px;border:1px solid var(--tl-line);border-radius:6px;
background:var(--tl-bg);color:var(--tl-fg);font-size:14px;resize:vertical;outline:none;
font-family:inherit;
}
.tl-editor textarea:focus{border-color:var(--tl-blue);}
.tl-editor-bar{display:flex;gap:10px;justify-content:flex-end;margin-top:6px;}
.tl-btn{padding:5px 16px;border-radius:6px;border:1px solid var(--tl-line);background:var(--tl-bg);
color:var(--tl-fg2);font-size:13px;cursor:pointer;}
.tl-btn.primary{background:var(--tl-blue);border-color:var(--tl-blue);color:#fff;}
.tl-btn:disabled{opacity:.5;cursor:not-allowed;}
/* 图片预览:同一条评论带多张图时,左右箭头 / ←→ 键切换 */
.tl-viewer{position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:2147483000;
display:flex;align-items:center;justify-content:center;}
.tl-viewer img{max-width:88vw;max-height:88vh;border-radius:4px;object-fit:contain;
user-select:none;-webkit-user-drag:none;}
.tl-vv-btn{position:absolute;top:50%;transform:translateY(-50%);width:44px;height:44px;
display:flex;align-items:center;justify-content:center;padding:0;border:0;border-radius:50%;
background:rgba(255,255,255,.14);color:#fff;cursor:pointer;transition:background .15s;}
.tl-vv-btn:hover{background:rgba(255,255,255,.28);}
.tl-vv-btn.prev{left:20px;}
.tl-vv-btn.next{right:20px;}
.tl-vv-count{position:absolute;left:50%;bottom:22px;transform:translateX(-50%);
padding:4px 12px;border-radius:999px;background:rgba(0,0,0,.55);color:#fff;
font-size:12px;line-height:1.4;letter-spacing:.5px;pointer-events:none;}
.tl-vv-close{position:absolute;right:18px;top:16px;width:36px;height:36px;padding:0;
border:0;border-radius:50%;background:rgba(255,255,255,.14);color:#fff;
font-size:22px;line-height:1;cursor:pointer;transition:background .15s;}
.tl-vv-close:hover{background:rgba(255,255,255,.28);}
/* ★ 悬浮视图开关:右下角常显胶囊
以前是"贴左下角 + 平时收成 30px 半透明圆点 + 悬停才出字",
结果没人找得到它,甚至有用户点偏一次就永久停在原生视图、树再也出不来。
现在改成常显胶囊:当前视图 + 动作 + 版本号一眼可见,可点面积也够大。
B 站自己的浮钮(小窗 / 客服 / 回顶部)也在右下角这条竖线上,
由 JS 量出来的 --tl-sw-lift 把胶囊整体抬到它们上方,不会互相压住。 */
#tl-switch{
position:fixed;right:16px;bottom:calc(24px + var(--tl-sw-lift,0px));z-index:2147483600;
display:inline-flex;align-items:center;gap:7px;
height:32px;padding:0 12px;border-radius:16px;user-select:none;
background:rgba(255,255,255,.97);color:#61666d;border:1px solid #e3e5e7;
font:12px/1 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;
box-shadow:0 2px 10px rgba(0,0,0,.15);
opacity:.9;cursor:grab;touch-action:none;-webkit-user-drag:none;
transition:color .15s,border-color .15s,box-shadow .15s,opacity .15s;
}
#tl-switch.tl-dragging{cursor:grabbing;opacity:1;transition:none;box-shadow:0 8px 22px rgba(0,0,0,.28);}
#tl-switch:hover{opacity:1;color:#00a1d6;border-color:#00a1d6;box-shadow:0 4px 16px rgba(0,161,214,.26);}
#tl-switch .tl-sw-dot{width:7px;height:7px;border-radius:50%;background:#00a1d6;flex:0 0 auto;}
#tl-switch .tl-sw-txt{white-space:nowrap;}
#tl-switch .tl-sw-ver{font-size:9px;line-height:1;color:#c3c7cc;letter-spacing:.02em;white-space:nowrap;}
#tl-switch.tl-sw-dark .tl-sw-ver{color:#5d636b;}
#tl-switch.tl-is-native .tl-sw-dot{background:#9499a0;}
#tl-switch.tl-sw-dark{background:rgba(34,37,40,.97);color:#a2a7ae;border-color:#33373c;}
#tl-switch.tl-sw-dark:hover{color:#4fc3f7;border-color:#4fc3f7;}
`;
/* ============================================================
* 工具
* ============================================================ */
const esc = (s) => String(s == null ? '' : s)
.replace(/&/g, '&').replace(//g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
/* B站接口偶尔把已经转义过的实体原样塞在正文里(" 最常见,用户从网页编辑器复制时就带上了)。
直接 esc 会二次转义,页面上就显示出 """ 这五个字符。所以先还原成真字符,再统一 esc 一次。
& 必须最后还原,否则 """(用户真的打的这串字)会被解成引号。 */
const ENT = { quot: '"', apos: "'", lt: '<', gt: '>', nbsp: ' ' };
const chr = (n, all) => {
if (!(n > 0 && n <= 0x10ffff) || (n >= 0xd800 && n <= 0xdfff)) return all;
try { return String.fromCodePoint(n); } catch (e) { return all; }
};
const unent = (s) => String(s == null ? '' : s)
.replace(/(\d{1,7});/g, (m, d) => chr(+d, m))
.replace(/([0-9a-f]{1,6});/gi, (m, h) => chr(parseInt(h, 16), m))
.replace(/&(quot|apos|lt|gt|nbsp);/gi, (m, n) => ENT[n.toLowerCase()] || m)
.replace(/&/gi, '&');
const el = (tag, cls, html) => {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (html != null) e.innerHTML = html;
return e;
};
const fmtNum = (n) => {
n = Number(n) || 0;
if (n >= 100000000) return (n / 100000000).toFixed(1).replace(/\.0$/, '') + '亿';
if (n >= 10000) return (n / 10000).toFixed(1).replace(/\.0$/, '') + '万';
return String(n);
};
const fmtTime = (ts) => {
const now = Date.now() / 1000;
const d = now - ts;
if (d < 60) return '刚刚';
if (d < 3600) return Math.floor(d / 60) + '分钟前';
if (d < 86400) return Math.floor(d / 3600) + '小时前';
if (d < 86400 * 30) return Math.floor(d / 86400) + '天前';
const t = new Date(ts * 1000);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}`;
};
const ipOf = (reply) => {
const loc = reply && reply.reply_control && reply.reply_control.location;
if (!loc) return '';
return String(loc).replace(/^IP属地[::]\s*/, '').trim();
};
const getCookie = (name) => {
const m = document.cookie.match(new RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return m ? decodeURIComponent(m[1]) : '';
};
/* ============================================================
* 接口
* ============================================================ */
/* GET / POST 只差 method 和"参数放 URL 还是放 body"两处,
* 解析、code 判断、错误/超时的处理完全一样,所以合成一个请求体。 */
function request(method, path, params) {
const qs = new URLSearchParams(params || {}).toString();
return new Promise((res, rej) => {
const opt = {
method: method,
url: 'https://api.bilibili.com' + path + (method === 'GET' && qs ? '?' + qs : ''),
withCredentials: true,
timeout: 15000,
onload(r) {
let j;
try { j = JSON.parse(r.responseText); } catch (e) { return rej(new Error('解析失败')); }
if (j.code !== 0) return rej(new Error((j.message || '请求失败') + '(' + j.code + ')'));
res(j.data);
},
onerror: () => rej(new Error('网络错误')),
ontimeout: () => rej(new Error('请求超时')),
};
if (method !== 'GET') {
opt.data = qs;
opt.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
}
GM_xmlhttpRequest(opt);
});
}
function api(path, params) { return request('GET', path, params); }
function post(path, params) { return request('POST', path, params); }
/* ============================================================
* 树构建:按 parent 指针把扁平回复拼成树
* ============================================================ */
function buildTree(flat, rootRpid) {
const map = new Map();
const order = [];
(flat || []).forEach((r) => {
if (!r || r.rpid == null) return;
const k = String(r.rpid);
if (map.has(k)) return;
const node = { reply: r, key: k, children: [], parent: null, depth: 0 };
map.set(k, node);
order.push(node);
});
const rootKey = String(rootRpid);
const roots = [];
order.forEach((node) => {
const pk = node.reply.parent != null ? String(node.reply.parent) : '';
const p = (pk && pk !== rootKey && pk !== '0') ? map.get(pk) : null;
if (p && p !== node && !isAncestor(node, p)) {
node.parent = p;
p.children.push(node);
} else {
roots.push(node);
}
});
// 计算深度
const setDepth = (n, d) => {
n.depth = d;
n.children.forEach((c) => setDepth(c, d + 1));
};
roots.forEach((n) => setDepth(n, 0));
// 按时间正序
const byTime = (a, b) => (a.reply.ctime || 0) - (b.reply.ctime || 0);
const sortRec = (arr) => { arr.sort(byTime); arr.forEach((n) => sortRec(n.children)); };
sortRec(roots);
return roots;
}
function isAncestor(a, b) {
let cur = b;
let guard = 0;
while (cur && guard++ < 5000) {
if (cur === a) return true;
cur = cur.parent;
}
return false;
}
/* 每种排序各留一份快照:切回来时直接用上次的结果,
不去打扰接口,顺序和数字才不会因为重新请求而抖动 */
const SortCache = {};
/* ============================================================
* 主控制器
* ============================================================ */
const State = {
oid: null,
type: 1, // 评论区类型代码:视频/番剧=1,课堂/课程=33。跟着页面组件走,不写死
upperMid: 0,
sort: SORT_HOT,
page: 1,
roots: [],
topRpids: new Set(), // 置顶评论的 rpid 集合(UP 置顶 + 管理员置顶)
collapsed: new Set(),
likeBusy: new Set(),
count: 0,
next: 0, // 评论主接口的分页游标
isEnd: false, // 是否已到最后一页
view: 'tree', // 当前视图:tree | native
};
let rootEl = null;
let listEl = null;
let headHost = null; // 顶栏容器:单独插在 B 站 bili-comments 之前,这样「评论 N / 最热 / 最新」在发布框上方
let nativeEl = null; // 原生 bili-comments(主评论区),失败时恢复显示
let hostEl = null; // 我们挂载所在的容器
/* ---------- 诊断:右下角状态徽章 ---------- */
const LOG_TAG = '[评论时间轴]';
const log = function () {
try { console.log.apply(console, [LOG_TAG].concat([].slice.call(arguments))); } catch (e) { /* ignore */ }
};
/* 只在控制台留日志:右下角不再挂任何提示条,否则会和悬浮开关叠成"两个按钮" */
function status(text) {
log(text);
}
/* 启动失败时把原因**画在页面上**,否则用户只能看到"什么都没发生" */
function showDiag(html) {
try {
let box = document.getElementById('tl-diag');
if (!box) {
box = document.createElement('div');
box.id = 'tl-diag';
box.style.cssText = 'position:fixed;left:16px;right:16px;bottom:126px;z-index:2147483601;' +
'background:#fff;color:#1f2329;border:1px solid #ff7a45;border-left:4px solid #ff4d4f;' +
'border-radius:8px;padding:12px 36px 12px 14px;font:12px/1.7 -apple-system,"Microsoft YaHei",sans-serif;' +
'box-shadow:0 8px 28px rgba(0,0,0,.22);max-height:46vh;overflow:auto;white-space:pre-wrap;';
const cp = document.createElement('div');
cp.textContent = '复制诊断';
cp.style.cssText = 'position:absolute;right:34px;top:6px;font-size:11px;color:#00a1d6;' +
'cursor:pointer;border:1px solid #00a1d6;border-radius:4px;padding:1px 7px;background:#fff;';
cp.onclick = function () {
try {
navigator.clipboard.writeText(diagText());
cp.textContent = '已复制';
} catch (e) { cp.textContent = '复制失败'; }
};
box.appendChild(cp);
const x = document.createElement('div');
x.textContent = '×';
x.style.cssText = 'position:absolute;right:8px;top:4px;font-size:20px;line-height:1;' +
'cursor:pointer;color:#8a9099;padding:2px 6px;';
x.onclick = function () { box.remove(); };
box.appendChild(x);
const body = document.createElement('div');
body.id = 'tl-diag-body';
box.appendChild(body);
(document.body || document.documentElement).appendChild(box);
}
const body = box.querySelector('#tl-diag-body');
if (body) {
body.innerHTML = html;
// 诊断面板里允许直接放"可点的动作",省得用户在一堆文字里找按钮
const acts = body.querySelectorAll('[data-tl-act]');
for (let i = 0; i < acts.length; i++) {
const b = acts[i];
b.onclick = function () {
const act = b.getAttribute('data-tl-act');
try { if (act === 'tree') setView('tree'); } catch (e) { /* ignore */ }
try { box.remove(); } catch (e) { /* ignore */ }
};
}
}
} catch (e) { /* ignore */ }
}
function themeDark() {
try {
const root = document.documentElement;
const body = document.body;
if (root.dataset.theme === 'dark' ||
root.classList.contains('dark') ||
(body && body.classList.contains('dark'))) return true;
// 逐层找一个"真正有底色"的元素;全透明时按浅色处理
const lumOf = (node) => {
if (!node) return null;
const c = getComputedStyle(node).backgroundColor || '';
const m = /rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?/.exec(c);
if (!m) return null;
const a = m[4] === undefined ? 1 : Number(m[4]);
if (a < 0.5) return null; // 透明 = 没给答案,继续往下找
return (0.299 * +m[1] + 0.587 * +m[2] + 0.114 * +m[3]) / 255;
};
const lum = lumOf(body) != null ? lumOf(body) : lumOf(root);
if (lum != null) return lum < 0.5;
return false; // 页面没设底色 → 默认浅色(B 站就是白底)
} catch (e) { /* ignore */ }
return matchMedia('(prefers-color-scheme: dark)').matches;
}
/* ============================================================
* 视图切换:树状 ↔ 原生,即时生效 + 记住选择
* ============================================================ */
function getPref() {
try {
const v = GM_getValue('tlView', 'tree');
// tlUserView 只有"用户亲手点过开关"时才会写。
// 老版本遗留的 native(可能是误触,也可能是我以前默认值写错)在这里一次性纠正回 tree,
// 否则用户会卡在原生视图里,看不到树还以为脚本坏了。
const userSet = GM_getValue('tlUserView', 0);
if (v === 'native' && !userSet) return 'tree';
return v === 'native' ? 'native' : 'tree';
} catch (e) { /* ignore */ }
try {
const v = localStorage.getItem('tl-view');
const userSet = localStorage.getItem('tl-user-view');
if (v === 'native' && !userSet) return 'tree';
return v === 'native' ? 'native' : 'tree';
} catch (e) { return 'tree'; }
}
function savePref(v) {
try { GM_setValue('tlView', v); GM_setValue('tlUserView', 1); } catch (e) { /* ignore */ }
try { localStorage.setItem('tl-view', v); localStorage.setItem('tl-user-view', '1'); } catch (e) { /* ignore */ }
}
let switchEl = null;
/* 样式必须"一启动就装",不能等挂载成功才装:
* 挂载失败(比如停在原生视图、或取 aid 失败)时,开关会退化成一段没有样式的裸文字,
* 用户看到的就是"胶囊按钮不见了",等于把唯一的自救入口也弄丢了。 */
function ensureStyle() {
if (document.getElementById('tl-style')) return;
try {
const style = document.createElement('style');
style.id = 'tl-style';
style.textContent = CSS;
(document.head || document.documentElement).appendChild(style);
} catch (e) { /* ignore */ }
}
function updateSwitch() {
if (!switchEl) return;
const isTree = State.view === 'tree';
switchEl.classList.toggle('tl-is-native', !isTree);
const txt = switchEl.querySelector('.tl-sw-txt');
// 常显文案:先说"现在是什么",再说"点了会去哪",
// 避免用户点了一下之后看不出自己正处在哪一侧。
if (txt) txt.textContent = isTree ? '树状视图 · 切回原生' : '原生视图 · 切到树状';
switchEl.title = (isTree
? '当前:树状时间轴视图(点击切回 B 站原生评论区)'
: '当前:B 站原生评论区(点击切到树状视图)') +
'\n按住可以拖到任意位置,双击回到右下角' +
'\nAlt + 点击:复制诊断信息(遇到问题时用)';
}
/* ---------- 让位:把胶囊抬到 B 站浮钮上方 ----------
* B 站在右下角有一条 fixed 竖列(小窗 / 客服 / 回顶部),宽度都在 60px 以内。
* 复古写法:没装着这些浮钮的页面,保持 bottom:24px 贴角;
* 装着的,量出它们最低的 top,把胶囊整体抬上去(最多 240px)。
*/
/* 是不是我们自己插进页面的节点(胶囊 / 顶栏 / 树 / 诊断 / 提示条)。
* 避让取样、找容器的启发式、自检扫描都要先把自己摘出去,写法统一到这里。 */
function isOurs(n) {
try {
return !!(n && n.closest && n.closest('#tl-switch,#tl-headroot,#tl-root,#tl-diag,#tl-toast'));
} catch (e) { return false; }
}
let swLift = 0;
/* 视口尺寸:个别内核里 innerWidth/innerHeight 会是 0,退回文档尺寸。
* 摆放、拖动、记忆位置三处都要用,写一份省得三处各不相同。 */
function vp() {
return {
w: innerWidth || document.documentElement.clientWidth,
h: innerHeight || document.documentElement.clientHeight,
};
}
function placeSwitch() {
if (!switchEl || !switchEl.isConnected) return;
// 用户手动把胶囊拖走了:位置以他为准,不再自动让位
if (swPos) { applySwPos(); return; }
let lift = 0;
try {
const { w: vw, h: vh } = vp();
const r = switchEl.getBoundingClientRect();
const w = (r && r.width) || 150;
const x1 = vw - 16 - w, x2 = vw - 16;
const base = 24;
// 沿右侧竖列取样:B 站浮钮基本都落在这几个高度上
const ys = [vh - 34, vh - 68, vh - 104, vh - 146, vh - 192, vh - 244];
const xs = [vw - 26, vw - 48];
let needBottom = 0;
for (let i = 0; i < ys.length; i++) {
for (let k = 0; k < xs.length; k++) {
let els = [];
try { els = document.elementsFromPoint(xs[k], ys[i]) || []; } catch (e) { continue; }
for (let j = 0; j < els.length; j++) {
const n = els[j];
if (!n || n.nodeType !== 1) continue;
if (isOurs(n)) continue;
let cs = null;
try { cs = getComputedStyle(n); } catch (e) { continue; }
if (cs.position !== 'fixed' && cs.position !== 'sticky') continue;
const fr = n.getBoundingClientRect();
if (fr.width < 10 || fr.height < 10) continue;
if (fr.width > 280 || fr.height > 280) continue; // 遮罩 / 整栏侧边不算
if (fr.bottom > vh + 2 || fr.top < 0) continue;
const ox = Math.min(fr.right, x2) - Math.max(fr.left, x1);
if (ox <= 2) continue; // 横向不重叠
const nb = Math.round(vh - fr.top + 10);
if (nb > needBottom) needBottom = nb;
}
}
}
if (needBottom > base) lift = Math.min(needBottom - base, 240);
} catch (e) { lift = 0; }
if (swExtra) lift += swExtra; // 吸底发布框钉住时整体再抬一截
if (lift === swLift) return;
swLift = lift;
try { switchEl.style.setProperty('--tl-sw-lift', lift + 'px'); } catch (e) { /* ignore */ }
log('开关让位 ' + lift + 'px');
}
/* ---------- 胶囊可拖动 ----------
* 用户嫌它挡内容 / 位置不合适时,直接按住拖到任意处;
* 松手记住坐标(GM 持久化),以后每次加载都在原处。
* 双击恢复默认(右下角 + 自动避让 B 站浮钮)。
*/
let swPos = null; // {left, top};null = 默认右下角、自动让位
let swDrag = null;
function loadSwPos() {
try {
const raw = GM_getValue('tlSwPos', '');
if (!raw) return null;
const o = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (o && isFinite(o.left) && isFinite(o.top)) return { left: +o.left, top: +o.top };
} catch (e) { /* ignore */ }
return null;
}
function saveSwPos() {
try { GM_setValue('tlSwPos', swPos ? JSON.stringify(swPos) : ''); } catch (e) { /* ignore */ }
}
/* 把胶囊摆到视口坐标 (left, top):拖动和"记住的位置"共用同一段写法 */
function placeAt(left, top) {
switchEl.style.setProperty('position', 'fixed', 'important');
switchEl.style.setProperty('left', Math.round(left) + 'px', 'important');
switchEl.style.setProperty('top', Math.round(top) + 'px', 'important');
switchEl.style.setProperty('right', 'auto', 'important');
switchEl.style.setProperty('bottom', 'auto', 'important');
switchEl.style.setProperty('--tl-sw-lift', '0px');
}
function applySwPos() {
if (!switchEl || !swPos) return;
const { w: vw, h: vh } = vp();
const r = switchEl.getBoundingClientRect();
placeAt(Math.max(0, Math.min(swPos.left, vw - (r.width || 120))),
Math.max(0, Math.min(swPos.top, vh - (r.height || 32))));
swLift = -1;
}
function resetSwPos() {
swPos = null;
saveSwPos();
try {
switchEl.style.removeProperty('left');
switchEl.style.removeProperty('top');
switchEl.style.removeProperty('right');
switchEl.style.removeProperty('bottom');
switchEl.style.removeProperty('position');
} catch (e) { /* ignore */ }
swLift = -1; // 强制重算让位
placeSwitch();
toast('悬浮按钮已回到右下角(可再拖动)');
}
function bindSwitchDrag() {
if (!switchEl || switchEl.__tlDragBound) return;
switchEl.__tlDragBound = 1;
switchEl.addEventListener('pointerdown', function (e) {
if (e.button !== 0 && e.pointerType !== 'touch') return;
const r = switchEl.getBoundingClientRect();
swDrag = {
id: e.pointerId, sx: e.clientX, sy: e.clientY,
ox: e.clientX - r.left, oy: e.clientY - r.top,
moved: false, w: r.width, h: r.height,
};
try { switchEl.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ }
switchEl.classList.add('tl-dragging');
});
switchEl.addEventListener('pointermove', function (e) {
if (!swDrag || e.pointerId !== swDrag.id) return;
const dx = e.clientX - swDrag.sx;
const dy = e.clientY - swDrag.sy;
if (!swDrag.moved && Math.abs(dx) + Math.abs(dy) < 5) return;
swDrag.moved = true;
const { w: vw, h: vh } = vp();
placeAt(Math.max(0, Math.min(e.clientX - swDrag.ox, vw - swDrag.w)),
Math.max(0, Math.min(e.clientY - swDrag.oy, vh - swDrag.h)));
});
const finish = function (e) {
if (!swDrag || (e && e.pointerId !== swDrag.id)) return;
const moved = swDrag.moved;
swDrag = null;
switchEl.classList.remove('tl-dragging');
try { switchEl.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ }
if (!moved) return; // 没拖动 → 交给 click 正常切换
const r = switchEl.getBoundingClientRect();
swPos = { left: Math.round(r.left), top: Math.round(r.top) };
saveSwPos();
swLift = -1;
switchEl.__tlClickBlock = Date.now() + 300; // 拖完别顺手把视图切了
log('开关位置已记住:' + swPos.left + ',' + swPos.top);
};
switchEl.addEventListener('pointerup', finish);
switchEl.addEventListener('pointercancel', finish);
switchEl.addEventListener('dblclick', function (e) {
e.preventDefault();
resetSwPos();
});
}
/* 小浮条提示(不依赖样式表,内联到底)。全局只有这一份实现:
* 以前渲染区还留了一份同名函数,靠"后定义的赢"覆盖它,等于前一份白写。 */
let toastEl = null, toastTimer = 0;
function toast(msg) {
try {
if (!toastEl || !toastEl.isConnected) {
toastEl = el('div');
toastEl.id = 'tl-toast';
toastEl.style.cssText = 'position:fixed;left:50%;top:24px;transform:translateX(-50%);' +
'z-index:2147483001;padding:8px 16px;border-radius:6px;background:rgba(0,0,0,.78);' +
'color:#fff;font:13px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;' +
'pointer-events:none;opacity:0;transition:opacity .3s;';
(document.body || document.documentElement).appendChild(toastEl);
}
toastEl.textContent = msg;
toastEl.style.opacity = '1';
clearTimeout(toastTimer);
toastTimer = setTimeout(function () { try { toastEl.style.opacity = '0'; } catch (e) { /* ignore */ } }, 2000);
} catch (e) { /* ignore */ }
}
/* 免开控制台拿诊断:Alt/Option + 点击胶囊 → 诊断文本进剪贴板。
* 之前只有 __tlDiag() 一条路,而它挂在沙箱 window 上,用户在控制台根本调不到。 */
function copyDiag() {
let txt = '';
try { txt = diagText(); } catch (e) { txt = '生成诊断失败:' + (e && e.message ? e.message : e); }
let ok = false;
try {
const ta = document.createElement('textarea');
ta.value = txt;
ta.setAttribute('readonly', 'readonly');
ta.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;';
(document.body || document.documentElement).appendChild(ta);
ta.select();
try { ta.setSelectionRange(0, txt.length); } catch (e2) { /* ignore */ }
ok = document.execCommand('copy');
ta.remove();
} catch (e) { ok = false; }
if (ok) { toast('诊断已复制到剪贴板'); return; }
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(txt).then(
function () { toast('诊断已复制到剪贴板'); },
function () { toast('复制被浏览器拒绝,请用 F12 控制台'); }
);
return;
}
} catch (e) { /* ignore */ }
toast('复制失败,请用 F12 控制台');
}
function ensureSwitch() {
ensureStyle();
if (switchEl && switchEl.isConnected) { updateSwitch(); return switchEl; }
/* 页面上根本没有评论组件时先不建:番剧详情页(/bangumi/media/md…)、首页这类地方
* 会一直浮着一个点了没反应的按钮,看起来像"插件装了但没用"。
* 等真找到评论区(组件出现 / 已经挂上树 / 用户主动切到过原生视图)再建。 */
try {
if (!mounted && !rootEl && State.view !== 'native' && !document.querySelector('bili-comments')) return null;
} catch (e) { /* ignore */ } // 若页面上已有一枚"不是本实例"的同 id 开关,说明还装着另一个版本的评论脚本,
// 两边会互相抢 DOM(表现为按钮时有时无、评论树来回消失)。这里清掉它并留日志。
const stray = document.getElementById('tl-switch');
if (stray && stray !== switchEl) {
log('检测到另一个同名开关,可能装了多个评论脚本(旧版请禁用):' + nodePath(stray));
try { stray.remove(); } catch (e) { /* ignore */ }
}
const host = document.body || document.documentElement;
if (!host) return null;
switchEl = el('div');
switchEl.id = 'tl-switch';
if (themeDark()) switchEl.classList.add('tl-sw-dark');
switchEl.innerHTML = '' +
'v' + VER + '';
// 有些第三方脚本会把浮层整体顶到极高层级,这里再压一头并强制可点
switchEl.style.setProperty('z-index', '2147483600', 'important');
switchEl.style.setProperty('pointer-events', 'auto', 'important');
switchEl.onclick = (e) => {
if (Date.now() < (switchEl.__tlClickBlock || 0)) return; // 刚拖过,别误切视图
// Alt(Mac 上 Option)/ Win 键 + 点击:把诊断文本复制到剪贴板,不用开控制台
if (e && (e.altKey || e.metaKey)) { copyDiag(); return; }
setView(State.view === 'tree' ? 'native' : 'tree');
};
host.appendChild(switchEl);
swPos = loadSwPos();
updateSwitch();
placeSwitch();
bindSwitchDrag();
return switchEl;
}
/* ---------- 原生区:只藏"列表/标题",保留"发布栏" ----------
* bili-comments 是个 Web Component,评论标题、排序、发布框、列表都在它的
* shadowRoot 里。整块 display:none 会把发布栏一起带走,所以改成:
* 找到含输入框的那个块,只隐藏它的兄弟节点(标题 + 列表),框留着。
*/
let structWarned = false; // "结构认不出"只提示一次
let editorRollbackWarned = false; // "藏完发布框没了,已回滚"只提示一次
let appliedRoot = null;
let hideSheet = null; // 注入到 shadowRoot 里的隐藏样式表
let hideBottom = false; // 树视图下是否要压掉 B 站自带的吸底发布条
let markedCount = 0; // 上一轮打了 data-tl-hide 标记的节点数
let rollbackAt = 0; // 最近一次"回滚"的时间,用于退避,别每秒重试
function deepText(node, depth) {
if (!node || depth > 5) return '';
let s = '';
try {
s = node.textContent || '';
const els = node.querySelectorAll ? node.querySelectorAll('*') : [];
for (let i = 0; i < els.length; i++) {
const sr = els[i].shadowRoot;
if (sr) s += ' ' + deepText(sr, depth + 1);
}
} catch (e) { /* ignore */ }
return s;
}
/* 找"真正的输入框":优先 textarea / contenteditable,
* 最后才退到 bili-comment-box 这类有可能只是空壳的容器。
* 以前直接取第一个 bili-comment-box —— 万一它是个不含输入框的外壳,
* 后面"藏兄弟"就会把真正的发布框一起藏掉,页面表现就是"输入框消失"。
*
* 注意 bili-comment-box 有自己的 shadowRoot,textarea 在它内部,
* 所以通常能查到的是 bili-comment-box 这个宿主本身,高度≈发布框高度,够用。 */
function allEditors(root) {
const out = [];
if (!root) return out;
let budget = 1500;
function push(n) { if (n && out.indexOf(n) < 0) out.push(n); }
function walk(node, depth) {
if (!node || depth > 4 || budget <= 0) return;
let kids = [];
try { kids = [].slice.call(node.children); } catch (e) { return; }
for (let i = 0; i < kids.length; i++) {
if (budget-- <= 0) return;
const k = kids[i];
const tag = (k.tagName || '').toLowerCase();
if (tag === 'textarea' || tag === 'bili-comment-box' || tag === 'input') push(k);
else {
try { if (k.isContentEditable) push(k); } catch (e) { /* ignore */ }
}
/* 必须往下钻:2025 版把发布框放进了 bili-comments-header-renderer 的
* shadowRoot 里,而 querySelectorAll 不穿影子边界 —— 只查浅层的话永远
* 只能找到 B 站那条 display:none 的吸底框(诊断里"候选输入框共 1 个"就是这个)。
* 钻的时候跳过整条评论的正文,省时间。 */
if (k.shadowRoot) walk(k.shadowRoot, depth + 1);
if (tag !== 'bili-comment-thread-renderer') walk(k, depth + 1);
}
}
walk(root, 0);
return out;
}
function visibleNodes(list) {
const out = [];
for (let i = 0; i < list.length; i++) {
const n = list[i];
if (!n || !n.isConnected) continue;
const m = edMetrics(n); // 不能直接用自身 rect:inline 宿主恒为 0x0
if (m.w > 2 && m.h > 2) out.push(n);
}
return out;
}
function findEditor(root) {
const all = allEditors(root);
if (!all.length) return null;
/* ★ 先挑"里面真有可见输入框"的那一份(v1.7.33)。
* B 站切原生再切回树状时会留下两份发布框:旧的 display:none、新的可见。
* visibleNodes 靠 edMetrics 借祖先尺寸判断,会把旧的那份也算成"可见",
* 于是挑中旧框 → 吸底钉住一个看不见的壳(或干脆不钉,输入框"消失")。
* 用 liveInput 直接看有没有真画出来的输入区,挑错的概率小得多。 */
for (let i = 0; i < all.length; i++) {
if (edAlive(all[i])) return all[i];
}
const vis = visibleNodes(all);
return vis.length ? vis[0] : all[0];
}
/* ★ bili-comment-box 是 display:inline 的宿主元素,里面装的是 block 内容,
* 于是它自己的 getBoundingClientRect() 恒为 0x0 —— 但里面那块其实是画出来的。
* 所有"发布框多大 / 可见吗"的判断都必须量到能量出尺寸的那一层:
* ① 自己 → ② 影子树里的真 textarea → ③ 往上找第一层量得出来的祖先(#commentbox)。
* 不这么做,吸底、底部留白、可见性复核会全部失效(诊断里那条
* "发布框:0x0 · 可见=false" 就是这么来的,而屏幕上明明有输入框)。 */
function edMetrics(ed) {
const out = { node: ed, w: 0, h: 0, top: 0, bottom: 0, left: 0, right: 0 };
if (!ed) return out;
function take(n) {
if (!n) return false;
let r = null;
try { r = n.getBoundingClientRect(); } catch (e) { return false; }
if (!r || r.width <= 2 || r.height <= 2) return false;
out.node = n; out.w = r.width; out.h = r.height;
out.top = r.top; out.bottom = r.bottom; out.left = r.left; out.right = r.right;
return true;
}
if (take(ed)) return out;
const sr = ed.shadowRoot;
if (sr) {
let ta = null, ce = null;
try { ta = sr.querySelector('textarea'); } catch (e) { ta = null; }
try { ce = sr.querySelector('[contenteditable="true"]'); } catch (e) { ce = null; }
if (take(ta)) return out;
if (take(ce)) return out;
}
let p = ed.parentElement;
for (let i = 0; p && i < 4; i++) {
if (take(p)) return out;
p = p.parentElement;
}
return out;
}
function containsEditor(n, ed) {
if (!n || !ed) return false;
try { return n === ed || n.contains(ed); } catch (e) { return false; }
}
function editorUsable(ed) {
if (!ed || !ed.isConnected) return false;
const m = edMetrics(ed);
return m.w > 40 && m.h > 6;
}
/* ★ 发布框里"真的有一个画出来的输入区"吗。
*
* 为什么不能靠 edMetrics 判断:它为了兼容 inline 宿主会一路往上借尺寸,
* B 站把发布框 display:none 之后,借到的是 div#contents —— 整个原生列表容器
* (668x260 的空白板)。老版本因此把空白板当发布框钉到底部,还会越长越高。
*
* 也不能只看"祖先链有没有 display:none":切视图时 B 站会留下旧框(隐藏)+
* 新框(可见)两份,挑中旧的就会把真正能打字的那个一起否掉(输入框"消失")。
*
* 做法:只看这一刻真正画出来的东西 —— 输入框自己、或它影子树里的 textarea。 */
function liveInput(ed) {
if (!ed || !ed.isConnected) return null;
const list = [];
const tag = (ed.tagName || '').toLowerCase();
if (tag === 'textarea' || tag === 'input') list.push(ed);
try { if (ed.isContentEditable) list.push(ed); } catch (e) { /* ignore */ }
// 直接 querySelector 钻到底:allEditors 有层数上限,真机上发布框常常超过 4 层
try {
if (ed.shadowRoot) {
const t = ed.shadowRoot.querySelector('textarea,[contenteditable="true"]');
if (t) list.push(t);
}
} catch (e) { /* ignore */ }
try {
const t2 = ed.querySelector('textarea,[contenteditable="true"]');
if (t2) list.push(t2);
} catch (e) { /* ignore */ }
for (let i = 0; i < list.length; i++) {
const n = list[i];
let r = null;
try { r = n.getBoundingClientRect(); } catch (e) { r = null; }
if (!r || r.width < 20 || r.height < 6) continue;
let d = '', v = '';
try { const cs = getComputedStyle(n); d = cs.display; v = cs.visibility; } catch (e) { /* ignore */ }
if (d === 'none' || v === 'hidden') continue;
return n;
}
return null;
}
/* 这份发布框还活着吗。两条路:
* ① 它自己就画出了尺寸(inline 宿主常见 0x0,此时交给 ②)
* ② 它里面/影子树里有一个可见的 textarea
* 两条都不满足 → 它是被页面收起来的空壳,既不吸底、也不拿它的尺寸去排版。 */
function edAlive(ed) {
if (!ed || !ed.isConnected) return false;
let own = null;
try { own = ed.getBoundingClientRect(); } catch (e) { own = null; }
let d = '';
try { d = getComputedStyle(ed).display; } catch (e) { /* ignore */ }
if (own && own.width > 20 && own.height > 6 && own.height < 420 &&
d !== 'none' && !hasVisibleRow(ed)) return true;
return !!liveInput(ed);
}
/* 量发布框,但只在它活着的时候才认这个尺寸。凡是"要给底部留空间 / 要钉多高"
* 的地方都走这里,避免拿着一块空白容器的 260px 去排版。 */
function edSize(ed) {
if (!edAlive(ed)) return { w: 0, h: 0, top: 0, bottom: 0, left: 0, right: 0, node: null };
return edMetrics(ed);
}
/* 原生列表的"行"组件名。
* bili-comment-thread-renderer —— 一条根评论(含楼中楼)
* bili-comment-replies-renderer —— 楼中楼容器
* bili-comments-pagination —— 「点击加载更多」
*
* ★★ 千万别把 bili-comments-header-renderer 加进来 ★★
* 2025 版 B 站把**发布框 (#commentbox / bili-comment-box) 放在这个组件的
* shadowRoot 里**,和标题栏是兄弟关系。按组件名整块藏 = 连输入框一起藏掉,
* 这正是"评论输入框始终不显示"的真凶(诊断里 header-renderer 显示 none
* 却没有 HIDDEN 标记,说明是被样式表按标签名杀的,逐节点保护根本拦不住)。
* 标题栏改为只藏它内部的 #title / #sort-actions / #navbar,见 hideHeaderParts()。 */
const ROW_TAGS = 'bili-comment-thread-renderer,' +
'bili-comment-replies-renderer,bili-comments-pagination';
/* 这个节点(连同它的影子树)里有没有输入框?
* bili-comment-box 的 textarea 在它自己的 shadowRoot 里,
* 普通的 contains() 跨不过 shadow 边界,必须单独穿透查一次。 */
const ED_Q = 'textarea,bili-comment-box,[contenteditable="true"]';
function hasEditorDeep(n) {
if (!n) return false;
const tag = (n.tagName || '').toLowerCase();
if (tag === 'textarea' || tag === 'bili-comment-box' || tag === 'input') return true;
try { if (n.isContentEditable) return true; } catch (e) { /* ignore */ }
try { if (n.querySelector(ED_Q)) return true; } catch (e) { /* ignore */ }
const sr = n.shadowRoot;
if (sr) { try { if (sr.querySelector(ED_Q)) return true; } catch (e) { /* ignore */ } }
return false;
}
/* 保护集合:谁装着输入框,谁以及它的祖先都不许藏。
* 优先用"已经渲染出尺寸/是自定义元素"的那些 —— 纯空壳(宽高都是 0)
* 不该把整个列表一起保下来,否则又回到"两套列表并存"。 */
function pickProtect(allEds) {
const strong = [];
for (let i = 0; i < allEds.length; i++) {
const n = allEds[i];
const tag = (n.tagName || '').toLowerCase();
let h = 0;
try { h = n.getBoundingClientRect().height; } catch (e) { h = 0; }
if (tag.indexOf('-') > 0 || h > 4) strong.push(n);
}
return strong.length ? strong : allEds;
}
/* 注入到 shadowRoot 的样式表。用样式表而不是逐个节点写内联样式,是因为
* B 站会反复重建列表节点(翻页、切排序、发评论),内联样式会随之丢失,
* 表现就是"原生列表又冒出来了、和树并排显示"。样式表只要还在,新节点也自动隐藏。 */
const HIDE_SEL = ROW_TAGS + ',[data-tl-hide]';
/* ---------- B 站自带的那条吸底发布条 ----------
* `.bili-comments-bottom-fixed-wrapper` 是 B 站自己钉在视口底部的"快捷发送条",
* 原生视图里滚过发布框之后它就会冒出来。问题是它在树视图下只是个**壳**:
* 点它要靠 header 里的真发布框去展开,而 header 已经被我们收拾过,于是
* 页面底部就多出一条"看得见、点不动、打不了字"的白条(切原生再切回树时尤其明显)。
* 处理原则:header 里还有能用的发布框 → 把这条压掉,由我们自己钉真框;
* header 里没有发布框(未登录 / 新版布局)→ 留着它,别把唯一的入口也弄没了。 */
function bottomBar(sr) {
if (!sr) return null;
try { return sr.querySelector('.bili-comments-bottom-fixed-wrapper'); } catch (e) { return null; }
}
/* header 里(排除吸底条内部)的输入框 */
function headerEditor(sr) {
if (!sr) return null;
const bw = bottomBar(sr);
const all = allEditors(sr);
const list = [];
for (let i = 0; i < all.length; i++) {
const n = all[i];
if (bw && (n === bw || bw.contains(n))) continue;
list.push(n);
}
if (!list.length) return null;
const vis = visibleNodes(list);
return vis[0] || list[0];
}
function markHide(n) {
if (!n || !n.setAttribute) return false;
try {
if (n.hasAttribute('data-tl-hide')) return false;
n.setAttribute('data-tl-hide', '1');
return true;
} catch (e) { return false; }
}
function restoreNativeHide() {
if (hideSheet) { try { hideSheet.remove(); } catch (e) { /* ignore */ } hideSheet = null; }
const sr = appliedRoot || (nativeEl && nativeEl.shadowRoot);
if (sr) {
try {
const m = sr.querySelectorAll('[data-tl-hide]');
for (let i = 0; i < m.length; i++) m[i].removeAttribute('data-tl-hide');
} catch (e) { /* ignore */ }
// 标题栏内部那张小样式表也得摘掉,否则切回原生时看不见标题
try {
const hs = sr.querySelectorAll('bili-comments-header-renderer');
for (let i = 0; i < hs.length; i++) {
const st = hs[i].shadowRoot && hs[i].shadowRoot.querySelector('#tl-hd-hide');
if (st) st.remove();
}
} catch (e) { /* ignore */ }
}
hdrHidden = 0;
hideBottom = false;
markedCount = 0;
appliedRoot = null;
}
/* 把 B 站自带那条吸底发布条放回来(只撤"压掉它"这一条规则,别的不动)。
*
* 为什么需要:树视图下我们会压掉那条壳、改成自己钉真框。万一真框这一刻钉不了
* (切视图 / 换 P 的瞬间,header 里的发布框被 B 站收起来了),压掉的那条又不在了,
* 底部就彻底没有任何输入入口 —— 用户看到的就是"输入框有时候不显示"。
* 放回来至少留一个能点开的入口;下一轮巡检若发现它是空壳,会重新压掉并继续钉真框。 */
function showBiliBottom() {
if (!hideBottom) return;
hideBottom = false;
try {
if (hideSheet && hideSheet.isConnected) {
hideSheet.textContent = HIDE_SEL + '{display:none!important}';
}
} catch (e) { /* ignore */ }
}
/* 只要这一刻不是"钉着真框",就不该让底部彻底没有入口(v1.7.42)。
* 原来只在 deadEditor 一条分支上兜底,另外几条"没钉"的原因(发布框还在视口里、
* 已经滚过评论区、尺寸还没量出来)同样会把底部那条永久压住 —— 用户看到的就是
* "底部输入框有时候不显示"。这里统一兜一层:连着 2 秒没钉住就把压掉规则撤掉,
* B 站自己会决定那条壳该不该露;真框能钉的时候下一次照常压回去。
* 只撤我们自己那条 display:none,不碰别的样式,抖动风险很低。 */
let idleSince = 0;
function bottomFallback() {
if (!hideBottom) { idleSince = 0; return; }
const now = Date.now();
if (!idleSince) { idleSince = now; return; }
if (now - idleSince < 2000) return;
idleSince = 0;
showBiliBottom();
log('这一轮没钉住真框(' + pinSkips + '),先把 B 站吸底条放回来兜底');
}
/* ① 按组件名藏。命中数 0 说明 B 站换了组件名 */
function hideRows(sr, protect) {
let n = 0, rows = [];
try { rows = sr.querySelectorAll(ROW_TAGS); } catch (e) { rows = []; }
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
let safe = true;
for (let k = 0; k < protect.length; k++) {
if (row === protect[k] || containsEditor(row, protect[k])) { safe = false; break; }
}
if (!safe) continue;
if (hasEditorDeep(row)) continue; // 深穿透兜底:行里装着输入框就绝不藏
if (markHide(row)) n++;
}
return n;
}
/* 不含内容的"皮肤"标签:藏了没用、也不该动 */
const SKIN_TAG = /^(style|link|slot|script)$/;
/* 一个兄弟节点能不能安全标掉:不是"当前链"上的那块、不在保护集合里、
* 有实际高度、且(深穿透)里面没有输入框。hideAround / hideTopLevel 共用。 */
function hideable(k, skip, protect, minH) {
if (!k || k === skip || !k.style) return false;
if (SKIN_TAG.test((k.tagName || '').toLowerCase())) return false;
for (let j = 0; j < protect.length; j++) {
if (k === protect[j] || containsEditor(k, protect[j])) return false;
}
let r = null;
try { r = k.getBoundingClientRect(); } catch (e) { r = null; }
if (!r || r.height < minH) return false; // 空壳、装饰线不动
if (hasEditorDeep(k)) return false; // 深穿透兜底
return true;
}
/* ② 认不出组件名时的几何兜底:从输入框往上走,每层把"不含输入框的兄弟"标掉 */
function hideAround(sr, ed, protect) {
let n = 0;
if (!ed) return 0;
let cur = ed;
for (let d = 0; d < 14 && cur && cur !== sr; d++) {
const p = (cur.parentNode === sr) ? sr : cur.parentElement;
if (!p) break;
let kids = [];
try { kids = [].slice.call(p.children); } catch (e) { kids = []; }
for (let i = 0; i < kids.length; i++) {
if (hideable(kids[i], cur, protect, 8) && markHide(kids[i])) n++;
}
cur = p;
}
return n;
}
/* ③ 最后一招:shadowRoot 的直接子元素里,凡是不含输入框且有高度的都标掉 */
function hideTopLevel(sr, protect) {
let n = 0, kids = [];
try { kids = [].slice.call(sr.children); } catch (e) { kids = []; }
for (let i = 0; i < kids.length; i++) {
if (hideable(kids[i], null, protect, 24) && markHide(kids[i])) n++;
}
return n;
}
/* 标题栏(「评论 N / 最热 / 最新」)住在 header-renderer 自己的 shadowRoot 里,
* 和发布框 #commentbox 是兄弟。只藏 #navbar / #title / #sort-actions 这三块,
* 且逐个确认"这块里没有输入框"才藏 —— 万一某个版本把 #commentbox 嵌进
* #navbar 里,宁可标题栏留着,也不能把输入框带走。 */
let hdrHidden = 0;
let hdrErr = ''; // 注入标题栏样式表时的异常(排查用)
function hideHeaderParts(sr) {
let n = 0, hs = [];
try { hs = [].slice.call(sr.querySelectorAll('bili-comments-header-renderer')); }
catch (e) { return 0; }
for (let i = 0; i < hs.length; i++) {
const hsr = hs[i].shadowRoot;
if (!hsr) continue;
const cands = ['#navbar', '#title', '#sort-actions'];
const safe = [];
for (let j = 0; j < cands.length; j++) {
let node = null;
try { node = hsr.querySelector(cands[j]); } catch (e) { node = null; }
if (!node) continue;
if (hasEditorDeep(node)) continue; // 里边装着输入框 → 放过
safe.push(cands[j]);
}
if (!safe.length) continue;
const css = safe.join(',') + '{display:none!important}';
try {
let st = hsr.querySelector('#tl-hd-hide');
if (!st) {
st = document.createElement('style');
st.id = 'tl-hd-hide';
hsr.appendChild(st);
}
if (st.textContent !== css) st.textContent = css;
n++;
} catch (e) { hdrErr = String((e && e.message) || e); }
}
return n;
}
function applyNativeVisibility(isTree) {
if (!nativeEl) return;
restoreNativeHide();
nativeEl.style.display = '';
try { restoreNativeTweaks(); } catch (e) { /* ignore */ }
if (!isTree) return;
const sr = nativeEl.shadowRoot;
if (!sr) { nativeEl.style.display = 'none'; return; }
appliedRoot = sr;
const allEds = allEditors(sr);
const beforeVis = visibleNodes(allEds);
const ed = findEditor(sr);
// 保护集合:谁装着输入框,谁以及它的祖先都不许藏
const protect = pickProtect(allEds);
/* ① 先插样式表(组件名命中后,连 B 站重建节点都不用管)。
* 顺带决定要不要压掉 B 站自带的吸底条:只有 header 里确实有能用的发布框时才压。 */
const bw = bottomBar(sr);
const hed = headerEditor(sr);
hideBottom = !!(bw && hed && editorUsable(hed));
let css = HIDE_SEL;
if (hideBottom) css += ',.bili-comments-bottom-fixed-wrapper';
try {
hideSheet = document.createElement('style');
hideSheet.id = 'tl-native-hide';
hideSheet.textContent = css + '{display:none!important}';
sr.appendChild(hideSheet);
} catch (e) { hideSheet = null; }
// 标题栏单独处理:只藏内部的三块,绝不整块藏(发布框在里面)
try { hdrHidden = hideHeaderParts(sr); } catch (e) { hdrHidden = 0; }
let hid = hideRows(sr, protect);
if (!hid) hid = hideAround(sr, ed || allEds[0], protect);
if (!hid) hid = hideTopLevel(sr, protect);
markedCount = hid;
/* 收尾复核:藏之前输入框是可见的,藏之后一个都不可见 —— 说明藏错了,整批撤销。
* 反过来,如果藏之前就看不见(未登录 / B 站自己没渲染),绝不能因此判失败,
* 那正是"两套列表并存"的老毛病。 */
const afterVis = visibleNodes(allEds);
if (beforeVis.length && !afterVis.length) {
restoreNativeHide();
rollbackAt = Date.now();
if (!editorRollbackWarned) {
editorRollbackWarned = true;
log('藏原生评论后发布框不可见,已撤销(保留 B 站原生列表)');
}
return;
}
if (!hid && !structWarned) {
structWarned = true;
log('原生评论结构认不出(组件名与几何兜底都没命中),暂时保留原生列表');
}
tidyNativeTree(true);
}
/* ---------- 收拾树视图下的原生区块 ----------
* 只做两件事:
* ① 藏掉原生列表末尾的「没有更多评论」提示(它不在被藏的兄弟节点里,
* 会留在发布框下面撑出一段空白);
* ② 保证发布框可见 + 按它的真实高度给树留底部空间。
*
* 明确**不再**做的事(都试过,副作用更大):
* · 把发布框的 sticky 改成 static —— 用户要的就是"下拉后底部吸底";
* · 给 bili-comments 设 max-height 裁剪 —— 测量一偏差就把发布框裁没了,
* 页面表现就是"评论输入框不显示"。
*/
const END_HINT = /^(没有更多评论|没有更多评论了|没有更多回复|没有更多了|已加载全部评论|已加载全部|已显示全部评论|以上为全部评论|暂时没有更多评论|暂无更多评论|没有更多数据|到底了|已经到底了)$/;
let tailKilled = []; // 被藏掉的"没有更多评论"提示
let clipGuardRoot = null; // 已经挂过 focus 监听的 shadowRoot
let tidyAt = 0;
/* 找输入框要遍历整棵影子树(allEditors 最多 1500 个节点),而滚动时
* pinComposer 每帧都会问一次。这里做 400ms 的短缓存:节点一脱离文档就失效,
* B 站换掉发布框也不会拿到旧的。 */
let edMemo = { sr: null, node: null, at: 0 };
function shadowEditor(sr) {
const now = Date.now();
if (edMemo.sr === sr && edMemo.node && edMemo.node.isConnected && now - edMemo.at < 400) {
return edMemo.node;
}
let ed = findEditor(sr);
if (!ed) {
// 兜底:万一 B 站把发布框挪到 bili-comments 的 light DOM 里
try { ed = nativeEl ? nativeEl.querySelector('textarea, [contenteditable="true"]') : null; }
catch (e) { ed = null; }
}
if (ed) edMemo = { sr: sr, node: ed, at: now };
return ed;
}
/* 记住元素本来的内联 display,恢复时原样写回去(不能 removeProperty,
* 否则 B 站自己写在 style 上的 display 会被一起抹掉) */
function hideTail(n) {
if (!n || !n.style) return;
if (tailKilled.indexOf(n) < 0) {
n.__tlDisp = n.style.display || '';
tailKilled.push(n);
}
n.style.setProperty('display', 'none', 'important');
}
/* 藏掉"没有更多评论"这类收尾提示(连同因此变空的壳一起收) */
function killEndHints(sr, ed) {
(function walk(node, depth) {
if (!node || depth > 6) return;
const kids = node.children;
for (let i = 0; i < kids.length; i++) {
const c = kids[i];
if (!c || c.nodeType !== 1) continue;
if (SKIN_TAG.test((c.tagName || '').toLowerCase())) continue;
if (ed && c.contains(ed)) { walk(c, depth + 1); continue; } // 发布框这条链只能往里钻
let cs = null;
try { cs = getComputedStyle(c); } catch (e) { continue; }
if (cs.display === 'none') continue; // 已经藏过,整棵跳过
const t = (c.textContent || '').trim();
if (t.length <= 24 && END_HINT.test(t)) {
hideTail(c);
// 上游若只是个为这条提示撑高度的空壳,一起收掉(否则空白还在)
let p = c.parentElement;
for (let k = 0; p && p !== sr && k < 6; k++) {
if (ed && (p === ed || p.contains(ed))) break;
let vis = false;
for (let j = 0; j < p.children.length; j++) {
const s = p.children[j];
if (s === c) continue;
const stag = (s.tagName || '').toUpperCase();
if (stag === 'STYLE' || stag === 'LINK' || stag === 'SCRIPT') continue;
let scs = null;
try { scs = getComputedStyle(s); } catch (e) { vis = true; break; }
if (scs.display === 'none') continue;
vis = true; break;
}
if (vis) break;
hideTail(p);
p = p.parentElement;
}
continue;
}
if (c.firstElementChild) walk(c, depth + 1);
}
})(sr, 0);
}
/* 输入框失焦后重排一次(表情面板关掉、高度变化,连线要跟着重算) */
function guardClipFocus(sr) {
if (clipGuardRoot === sr) return;
clipGuardRoot = sr;
try {
sr.addEventListener('focusout', function () {
setTimeout(function () { if (State.view === 'tree') { tidyAt = 0; tidyNativeTree(); } }, 350);
}, true);
} catch (e) { /* ignore */ }
}
/* 发布框自愈。历史上这里会"把发布框祖先链上所有 display:none 全擦掉",
* 那是**错误**的:B 站自己就是靠 display / 类名控制输入框的展开状态,
* 我们一擦,页面就变成一个没有文字的空灰壳,而且切回原生也不会恢复
* (原值没记录)。现在的隐藏方案已经保证不会碰输入框,所以这里只做两件事:
* ① 清掉我们可能残留的 max-height / 整块 display:none;
* ② 量一下高度,异常时往控制台留一条线索。绝不改 B 站自己的 display。
*/
let editorWarned = false;
function ensureEditorVisible(ed) {
if (nativeEl) {
try {
if (nativeEl.style.maxHeight) { nativeEl.style.maxHeight = ''; nativeEl.style.overflow = ''; }
if (nativeEl.style.display === 'none') nativeEl.style.display = '';
} catch (e) { /* ignore */ }
}
let h = 0;
try { h = edMetrics(ed).h; } catch (e) { /* ignore */ }
if (h < 8 && !editorWarned) {
editorWarned = true;
log('发布框高度只有 ' + Math.round(h) + 'px:可能被 B 站自己隐藏,或页面未登录');
}
}
/* 底部留白:按发布框真实高度给树留出空间。
* 保留 B 站自己的吸底(sticky)发布框,但滚到最底部时它会浮在视口底部,
* 不留这段空间就会盖住最后一条评论和「加载更多评论」按钮。
*/
let swExtra = 0; // 吸底发布框钉住时,胶囊要额外抬高的像素
function setSwitchExtra(px) {
const v = Math.max(0, Math.round(px));
if (v === swExtra) return;
swExtra = v;
try { placeSwitch(); } catch (e) { /* ignore */ }
}
function syncFabGap(ed) {
if (!rootEl) return;
let h = 0;
try { h = Math.round(edSize(ed).h); } catch (e) { /* ignore */ }
setFabGap(h >= 24 ? h + 28 : 92);
}
let curFabGap = 0;
function setFabGap(gap) {
if (!rootEl || gap === curFabGap) return;
curFabGap = gap;
try { rootEl.style.setProperty('--tl-fb-gap', gap + 'px'); } catch (e) { /* ignore */ }
}
/* ============================================================
* 下拉时"跟随滚动的输入框"
* ------------------------------------------------------------
* B 站自己的发布框是 position:sticky 的,它的吸附范围只到 bili-comments 这块
* 容器为止;我们把原生列表藏掉以后容器高度只剩发布框本身,sticky 就没有
* 行程可走 —— 页面表现就是"往下拉,输入框跟着滚没了"。
* 这里不改 DOM、不复制输入框,只在"用户已经滚过发布框"的时候,把 B 站那个
* 真·发布框原地改成 position:fixed 钉在视口底部(宽度对齐评论列),
* 滚回去再恢复原样。用的还是 B 站原来的输入框,登录态、表情、发布逻辑都不变。
* ============================================================ */
const PIN_PROPS = ['position', 'left', 'right', 'top', 'bottom', 'width', 'z-index', 'background', 'box-shadow',
'transform', 'height', 'min-height', 'max-height', 'overflow', 'box-sizing', 'padding', 'border-radius'];
let fbPin = null;
let pinTries = 0, pinSkips = '', pinFix = '', scrollN = 0, pinGhosts = 0; // 排查用计数
let deadSince = 0, reviveAt = 0; // 发布框"点不着"持续多久 / 上次放回 B 站条的时间
/* 跨影子树找父节点:影子树顶层的元素 parentElement 是 null,
* 但 parentNode 是 ShadowRoot,它的 .host 就是宿主元素。 */
function parentAcross(n) {
if (!n) return null;
if (n.parentElement) return n.parentElement;
const p = n.parentNode;
if (p && p.host) return p.host;
return null;
}
/* 这块里有没有"还没被藏掉的评论行"?有就说明已经越过发布框、进了列表区。
* 之前只看高度,一旦原生列表因为回滚 / B 站重建短暂恢复显示,就会把整块
* 评论区当成发布框钉到底部 —— 页面表现是"底部一条白条,里面混着一条评论,
* 打不了字"(切原生再切回树时最容易撞上)。 */
function hasVisibleRow(n) {
if (!n || !n.querySelectorAll) return false;
let rows = null;
try { rows = n.querySelectorAll('bili-comment-thread-renderer,bili-comment-replies-renderer'); }
catch (e) { return false; }
for (let i = 0; i < rows.length; i++) {
let r = null;
try { r = rows[i].getBoundingClientRect(); } catch (e) { r = null; }
if (r && r.height > 8 && r.width > 20) return true;
}
return false;
}
function composerBlock(ed) {
const sr = nativeEl && nativeEl.shadowRoot;
const base = edMetrics(ed).h;
// 高度量不出来就绝不往上走:以前 base=0 时循环条件永远不成立,
// 会一路顶到 shadowRoot 的直接子元素,把整块评论区当"发布框"钉成 fixed,
// 页面表现就是"原生评论区整块消失,只剩树"。
if (base < 8) return null;
let n = ed, best = null;
for (let i = 0; i < 10; i++) {
const p = parentAcross(n);
if (!p || p === sr || !p.getBoundingClientRect) break;
if (p === nativeEl) break; // 到 bili-comments 就打住,别把整个评论区当发布框
let ph = 0;
try { ph = p.getBoundingClientRect().height; } catch (e) { ph = 0; }
// 一旦祖先明显比输入框高出一大截,说明已经跨进列表区了,停在上一层
if (ph > base * 1.5 + 16) break;
if (hasVisibleRow(p)) break; // 里面混着评论行 → 绝不钉这块
best = p;
n = p;
}
return best || ed;
}
/* B 站给发布框写过好几种"收起态":外层写死 43px 高度 + overflow:hidden、
* 或者把高度算在外层而内容溢在里层。钉到底部之后这些裁切就变成"输入框缺一截"。
* 这里只沿"输入框 → bili-comments"这一条链,把**确实在裁内容**的元素临时放开,
* 原值记在 fbPin.unclip 里,unpin 时逐条还原。绝不碰 body / 页面容器。 */
function unclipChain(ed) {
if (!fbPin) return 0;
if (!fbPin.unclip) fbPin.unclip = [];
const saved = fbPin.unclip;
const list = [];
let cur = ed, guard = 0;
while (cur && cur.nodeType === 1 && guard++ < 24) {
list.push(cur);
if (cur === nativeEl) break;
cur = parentAcross(cur);
}
let n = 0;
for (let i = 0; i < list.length; i++) {
const el = list[i];
if (!el.style) continue;
let over = 0, ch = 0;
try { over = el.scrollHeight - el.clientHeight; ch = el.clientHeight; } catch (e) { continue; }
// 只处理"真被裁掉"的:有高度、内容超出、但超出量不大(大的是整块评论区,不能动)
if (!(ch > 0 && over > 4 && over < 320)) continue;
let rec = null;
for (let j = 0; j < saved.length; j++) if (saved[j].node === el) { rec = saved[j]; break; }
if (!rec) {
rec = {
node: el,
h: el.style.getPropertyValue('height'),
mh: el.style.getPropertyValue('max-height'),
ov: el.style.getPropertyValue('overflow'),
};
saved.push(rec);
}
try {
el.style.setProperty('height', 'auto', 'important');
el.style.setProperty('max-height', 'none', 'important');
el.style.setProperty('overflow', 'visible', 'important');
n++;
} catch (e) { /* ignore */ }
}
return n;
}
function unpinChain() {
if (!fbPin || !fbPin.unclip) return;
const saved = fbPin.unclip;
for (let i = 0; i < saved.length; i++) {
const r = saved[i], n = r.node;
if (!n || !n.style) continue;
try {
['height', 'max-height', 'overflow'].forEach(function (k) {
const v = r[k === 'height' ? 'h' : (k === 'max-height' ? 'mh' : 'ov')];
if (v) n.style.setProperty(k, v); else n.style.removeProperty(k);
});
} catch (e) { /* ignore */ }
}
fbPin.unclip = [];
}
/* ============================================================
* "空着却被撑高的编辑区"(v1.7.42)
* ------------------------------------------------------------
* 2025 版发布框的编辑区是 bili-comment-rich-textarea 影子树里的 .brt-editor:
* line-height 32px、min-height 32px、max-height 100px,行内 height 由 B 站自己算。
* 一旦它被算成 96px(正好 3 行)而里面还是空的:
* · 用户点进去,光标按落点算行 → 落在第 2 行(看着像"凭空多了一行");
* · 打第一个字,B 站重算成 19px → 光标跳回第 1 行、整个框还矮一截。
* 这里只在**内容为空**时把行内 height 去掉,让 CSS 的 min-height 重新接管(回到一行);
* 一旦有内容就完全不管,交回 B 站自己。量不到这个编辑区(老版/改版)就什么都不做。
* ============================================================ */
let boxMemo = { host: null, node: null, at: 0 };
function editorBoxNode(ed, fresh) {
if (!ed) return null;
const now = Date.now();
if (!fresh && boxMemo.host === ed && boxMemo.node && boxMemo.node.isConnected &&
now - boxMemo.at < 500) {
return boxMemo.node;
}
let out = null, rta = null;
/* bili-comment-rich-textarea 有的版本挂在影子树里,有的放在 light DOM —— 两处都找 */
try { rta = ed.shadowRoot && ed.shadowRoot.querySelector('bili-comment-rich-textarea'); }
catch (e) { rta = null; }
if (!rta) {
try { rta = ed.querySelector && ed.querySelector('bili-comment-rich-textarea'); }
catch (e) { rta = null; }
}
if (rta && rta.shadowRoot) {
const cands = ['.brt-editor', '[contenteditable="true"]', 'textarea'];
for (let i = 0; i < cands.length && !out; i++) {
try { out = rta.shadowRoot.querySelector(cands[i]); } catch (e) { out = null; }
}
}
if (!out) {
try { out = ed.shadowRoot && ed.shadowRoot.querySelector('textarea,[contenteditable="true"]'); }
catch (e) { out = null; }
}
if (!out) {
try { out = ed.querySelector && ed.querySelector('textarea,[contenteditable="true"]'); }
catch (e) { out = null; }
}
if (out) boxMemo = { host: ed, node: out, at: now };
return out;
}
function editorBoxEmpty(e) {
if (!e) return false;
try {
const tag = (e.tagName || '').toLowerCase();
if (tag === 'textarea' || tag === 'input') return !String(e.value || '').trim();
if (e.textContent && e.textContent.replace(/[\s\u200b\ufeff]+/g, '')) return false;
if (e.querySelector && e.querySelector('img,video,audio')) return false;
return true;
} catch (err) { return false; }
}
let clampN = 0;
function clampEmptyEditor(ed) {
let e = null;
try { e = editorBoxNode(ed); } catch (err) { return 0; }
if (!e || !e.style) return 0;
/* 只管 contenteditable 那种富文本编辑区(.brt-editor)。老版 textarea 的高度是
* 布局的一部分(43px 收起态就靠它),随手去掉行内 height 反而会破坏排版。 */
const etag = (e.tagName || '').toLowerCase();
if (etag === 'textarea' || etag === 'input') return 0;
try { if (!e.isContentEditable) return 0; } catch (err) { return 0; }
if (!editorBoxEmpty(e)) return 0;
let r = null;
try { r = e.getBoundingClientRect(); } catch (err) { return 0; }
if (!r || r.height <= 0) return 0;
let lh = 0, pt = 0, pb = 0;
try {
const cs = getComputedStyle(e);
lh = parseFloat(cs.lineHeight) || 0;
pt = parseFloat(cs.paddingTop) || 0;
pb = parseFloat(cs.paddingBottom) || 0;
} catch (err) { /* ignore */ }
if (!(lh > 8)) lh = 20;
if (r.height <= lh + pt + pb + 10) return 0; // 已经是一行(32 / 19),不动它
try {
e.style.removeProperty('height');
e.style.removeProperty('min-height');
} catch (err) { /* ignore */ }
clampN++;
if (clampN === 1) log('发布框空着却被撑到 ' + Math.round(r.height) + 'px,已压回一行');
return Math.round(r.height);
}
/* 钉住之后按"实际落点"纠一次偏。
* 为什么需要:B 站给发布框自己和它的祖先都写过 transform(吸底用的滑入动画、
* 部分页面还给外层容器加了 transform 做层叠),一旦祖先带 transform,
* position:fixed 的定位基准就从视口变成那个祖先,bottom:0 会把发布框推到
* 视口下方,页面表现就是"底部只露出输入框的一条边"。
* transform 是相对元素自身位置的位移,跟祖先的定位基准无关,所以用它纠偏最稳。
* 另一个坑:钉的块比里面的内容矮(B 站写死高度),只看块的 rect 会把输入框下半截
* 留在屏幕外 —— 所以取"块底边"和"输入框底边"里更低的那个当基准。 */
function pinCorrect(blk, treeR, ed) {
const vh = innerHeight || document.documentElement.clientHeight;
let r = null;
try { blk.style.setProperty('transform', 'none', 'important'); } catch (e) { /* ignore */ }
try { r = blk.getBoundingClientRect(); } catch (e) { return 0; }
if (!r) return 0;
try { unclipChain(ed); } catch (e) { /* ignore */ }
// 输入框的实际占位(跨影子树量)。发布框没渲染时 edSize 返回 0,不会借列表容器的尺寸
let em = null;
try { if (ed) em = edSize(ed); } catch (e) { em = null; }
/* ★ 硬上限:钉的块最多占半屏多一点。超过就直接放手 —— 说明钉错了对象
* (整块原生列表 / 被克隆的容器),继续纠偏只会让它越长越大。 */
const vhNow = innerHeight || document.documentElement.clientHeight;
const capH = Math.max(180, Math.min(560, Math.round(vhNow * 0.55)));
if (r.height > capH) {
pinSkips = 'blkHuge';
try { log('吸底块高 ' + Math.round(r.height) + 'px 超过上限 ' + capH + ',已放开'); } catch (e) { /* ignore */ }
unpinComposer();
return 0;
}
/* ★ 自我参照保护(v1.7.32):wantH 不能拿"块自己的高度"来算。
* 钉错对象时 em.node 就是块本身,于是 需求高 = 当前高 + 内边距 → 长高 → 下一轮再量更大,
* 每秒长 24px,视觉上就是"底部白块不断升高直到顶满全屏"。只认同块内部的输入框尺寸。 */
let emOK = !!(em && em.node && em.node !== blk && blk.contains && blk.contains(em.node));
/* 块比输入框还矮 —— 就是"底部输入框只露出半截"的元凶:B 站把发布框收起态
* 写成死高度(常见 43px),我们再补上下 12px 内边距,内容区就只剩十几像素,
* 输入框被压成一条细边。这时现量的 em.h 自己也是扁的,所以拿"钉之前量到的
* 自然高度" fbPin.edH 当参考,按 输入框 + 上下内边距 给块一个兜底高度。 */
/* ★ edH 要跟着"最矮的样子"走(v1.7.42)。
* 以前它只在钉住那一刻量一次:如果那一拍发布框正好是展开态(或还没排好),
* edH 就永远停在 92~96px,之后每轮纠偏都拿它当"至少这么高",卡片再也收不回去 ——
* 用户看到的是"没点到输入框时也是一大坨"。改成记录观察到的最小值(>24 才算数),
* 它就会稳定收敛到收起态的一行高度。 */
if (fbPin && emOK && em.h >= 24 && em.h <= 400) {
fbPin.edH = fbPin.edH > 6 ? Math.min(fbPin.edH, em.h) : em.h;
}
const wantH = Math.max(emOK && em.h > 6 ? em.h : 0, (fbPin && fbPin.edH) || 0);
if (wantH > 0) {
/* 输入框被 flex 压扁时,块再高也救不回来 —— 直接把它自己钉回自然高度。
* 这是"底部输入框只剩一条细边"的另一个成因:B 站发布框用 flex 排版,
* 外层写死高度后 textarea 是 flex:1,我们补的内边距全靠压它来消化。
* ★ 只对真正的 textarea 做(2025 版的编辑区是 contenteditable,
* 本身带 min-height/max-height,给它写 min-height 只会把它撑高)。 */
const edTag = (ed && ed.tagName ? ed.tagName : '').toLowerCase();
if (edTag === 'textarea' && ed.style && fbPin && fbPin.edH > 6 && (emOK && em.h < fbPin.edH - 4)) {
try {
if (!fbPin.edSaved) {
fbPin.edSaved = {
node: ed,
h: ed.style.getPropertyValue('min-height'),
f: ed.style.getPropertyValue('flex'),
};
}
ed.style.setProperty('min-height', fbPin.edH + 'px', 'important');
ed.style.setProperty('flex', '0 0 auto', 'important');
em = edSize(ed);
emOK = !!(em && em.node && em.node !== blk && blk.contains && blk.contains(em.node));
} catch (e) { /* ignore */ }
}
let pt = 0, pb = 0;
try {
const cs = getComputedStyle(blk);
pt = parseFloat(cs.paddingTop) || 0;
pb = parseFloat(cs.paddingBottom) || 0;
} catch (e) { /* ignore */ }
const need = Math.ceil(wantH + pt + pb);
if (r.height < need - 2) {
try {
blk.style.setProperty('height', 'auto', 'important');
blk.style.setProperty('max-height', 'none', 'important');
blk.style.setProperty('overflow', 'visible', 'important');
blk.style.setProperty('min-height', need + 'px', 'important');
if (fbPin) fbPin.minH = need;
r = blk.getBoundingClientRect();
} catch (e) { /* ignore */ }
} else if (fbPin && fbPin.minH && r.height > fbPin.minH + 8) {
/* 卡片已经比我们撑的那点还高(B 站自己长上去了,或者它收起来变矮了)——
* 说明这条 min-height 不再起作用,撤掉,免得它拦住"收起态"变矮。 */
try {
const orig = fbPin.saved ? (fbPin.saved['min-height'] || '') : '';
if (orig) blk.style.setProperty('min-height', orig); else blk.style.removeProperty('min-height');
} catch (e) { /* ignore */ }
fbPin.minH = 0;
}
}
let low = r.bottom, high = r.top;
if (emOK && em.h > 6) { low = Math.max(low, em.bottom); high = Math.min(high, em.top); }
const span = Math.max(r.height, (emOK && em.h > 6) ? (low - high) : 0);
let dx = Math.round(treeR.left - r.left);
let dy = Math.round(low - (vh - 10)); // >0 说明探出视口底部,需要往上抬
if (Math.abs(dx) < 2) dx = 0;
if (Math.abs(dy) < 2) dy = 0;
pinFix = dx + ',' + dy;
if (dx || dy) {
try { blk.style.setProperty('transform', 'translate(' + dx + 'px,' + (-dy) + 'px)', 'important'); }
catch (e) { /* ignore */ }
}
return Math.round(span);
}
/* 钉成"卡片"之后,B 站原本的紧凑排布就露馅了:头像和输入框几乎贴着块的
* 上下边缘,视觉上非常挤。这里给块补一点内边距(上下 12、左右 14),
* 取"现有值"和"目标值"里较大的那个,不会把 B 站已经留好的间距改小;
* 同时强制 border-box,宽度不会因为 padding 变胖。原值都在 PIN_PROPS 里
* 存过,unpin 时自动还原。 */
function padCard(blk) {
if (!blk || !blk.style) return;
let pt = 12, pb = 12, pl = 14, pr = 14, rad = 12;
try {
const cs = getComputedStyle(blk);
pt = Math.max(pt, parseFloat(cs.paddingTop) || 0);
pb = Math.max(pb, parseFloat(cs.paddingBottom) || 0);
pl = Math.max(pl, parseFloat(cs.paddingLeft) || 0);
pr = Math.max(pr, parseFloat(cs.paddingRight) || 0);
rad = Math.max(rad, parseFloat(cs.borderTopLeftRadius) || 0);
} catch (e) { /* ignore */ }
try {
/* 先放开死高度再加内边距。顺序反了就是"底部输入框只露半截":B 站把发布框
* 收起态写成 height:43px,我们再补上下 12px,内容区只剩 19px,输入框被裁掉。
* box-sizing:border-box 保宽度,height:auto 让块按内容自己长。 */
blk.style.setProperty('box-sizing', 'border-box', 'important');
blk.style.setProperty('height', 'auto', 'important');
blk.style.setProperty('max-height', 'none', 'important');
blk.style.setProperty('overflow', 'visible', 'important');
blk.style.setProperty('padding', Math.round(pt) + 'px ' + Math.round(pr) + 'px ' +
Math.round(pb) + 'px ' + Math.round(pl) + 'px', 'important');
blk.style.setProperty('border-radius', Math.round(rad) + 'px', 'important');
} catch (e) { /* ignore */ }
}
/* 钉住时在节点上留个印记,把"我们改过的原值"一起存进去。
* 为什么需要:B 站重建/克隆评论区时会把节点的内联样式**一起复制**,
* 复制品带着 position:fixed + 巨大 z-index 复活,变成一条盖在底部、
* 点不动也打不了字的"幽灵卡片"(切原生再切回树状时必现)。
* 有了印记就能在巡检里认出它们,按原值还原干净。 */
const PIN_ATTR = 'data-tl-pin';
function restorePinStyle(el, raw) {
if (!el || !el.style) return;
let saved = null;
try { saved = raw ? JSON.parse(decodeURIComponent(raw)) : null; } catch (e) { saved = null; }
try {
for (let i = 0; i < PIN_PROPS.length; i++) {
const k = PIN_PROPS[i];
const v = saved ? (saved[k] || '') : '';
if (v) el.style.setProperty(k, v); else el.style.removeProperty(k);
}
} catch (e) { /* ignore */ }
}
/* 每秒扫一遍:凡是带着印记、但不是当前正在钉的那个节点,一律还原并摘掉印记。
* 返回清理数量(写进诊断,方便确认"幽灵卡片"是不是这条路清掉的)。 */
function sweepPinGhosts() {
const keep = (fbPin && fbPin.node) || null;
const roots = [];
try { if (nativeEl && nativeEl.shadowRoot) roots.push(nativeEl.shadowRoot); } catch (e) { /* ignore */ }
roots.push(document);
let n = 0;
for (let i = 0; i < roots.length; i++) {
let list = null;
try { list = roots[i].querySelectorAll('[' + PIN_ATTR + ']'); } catch (e) { list = null; }
if (!list) continue;
for (let j = 0; j < list.length; j++) {
const el = list[j];
if (el === keep) continue;
restorePinStyle(el, el.getAttribute(PIN_ATTR));
try { el.removeAttribute(PIN_ATTR); } catch (e) { /* ignore */ }
n++;
}
}
if (n) pinGhosts += n;
return n;
}
function unpinComposer() {
if (!fbPin) return;
const blk = fbPin.node;
try { unpinChain(); } catch (e) { /* ignore */ }
// 还原被我们钉回自然高度的输入框(pinCorrect 里的 flex 压缩保护)
try {
const s = fbPin.edSaved;
if (s && s.node && s.node.style) {
if (s.h) s.node.style.setProperty('min-height', s.h); else s.node.style.removeProperty('min-height');
if (s.f) s.node.style.setProperty('flex', s.f); else s.node.style.removeProperty('flex');
}
} catch (e) { /* ignore */ }
try {
if (blk && blk.style) {
for (let i = 0; i < PIN_PROPS.length; i++) {
const k = PIN_PROPS[i], v = fbPin.saved[k];
if (v) blk.style.setProperty(k, v); else blk.style.removeProperty(k);
}
}
} catch (e) { /* ignore */ }
try { if (blk) blk.removeAttribute(PIN_ATTR); } catch (e) { /* ignore */ }
fbPin = null;
setSwitchExtra(0);
/* 不再钉底了,"输入中让位"这档也必须当场撤掉 —— 否则小窗会一直待在低位,
* 用户看到的是"右下角小窗被什么东西压住了",而且他没法自己点回来。 */
try { if (miniLow) setMiniLow(0); } catch (e) { /* ignore */ }
try { if (nativeEl) { const ed = shadowEditor(nativeEl.shadowRoot); if (ed) syncFabGap(ed); } } catch (e) { /* ignore */ }
}
function pinComposer() {
pinTries++;
if (State.view !== 'tree' || !nativeEl || !nativeEl.isConnected || !rootEl || !rootEl.isConnected) {
pinSkips = 'noRef';
unpinComposer();
return;
}
const sr = nativeEl.shadowRoot;
if (!sr) { pinSkips = 'noShadow'; unpinComposer(); return; }
const ed = shadowEditor(sr);
/* ★ 发布框被 B 站藏了(切原生再切回树状时会出现 display:none)就别钉。
* 以前只判 editorUsable,而它会借用祖先尺寸,把整块 #contents 当成"发布框"
* 钉到视口底部 —— 底部一块大白板,还会一路自我撑高涨到顶部。 */
if (!ed || !editorUsable(ed) || !edAlive(ed)) {
pinSkips = 'deadEditor';
unpinComposer();
/* 发布框这一刻确实点不着(切原生再切回树、换 P、B 站重排的那一下最常见)。
* 我们通常会把 B 站那条壳压掉,于是"真框不可用 + 壳被压掉"= 底部彻底没入口,
* 用户看到的就是"输入框有时候不显示"。
* 撑过 3 秒还救不回来,就把那条放回来;60 秒内只放一次,避免和下一轮
* "重新压掉"来回抖。真框恢复后下一次压掉/钉底会自动接管。 */
const nowD = Date.now();
if (!deadSince) deadSince = nowD;
if (hideBottom && nowD - deadSince > 3000 && nowD - reviveAt > 60000) {
reviveAt = nowD;
showBiliBottom();
log('发布框 3 秒内没恢复,先把 B 站吸底条放回来兜底');
}
return;
}
deadSince = 0;
/* B 站自己那条吸底发布条(.bili-comments-bottom-fixed-wrapper):
* 只有"我们没压掉它"且它里面确实有能打字的输入框时才让位。否则压掉它、自己钉真框 ——
* 切原生再切回树之后,它常常是个点不动也打不了字的空壳,让位就会变成底部一条死条。 */
try {
const bw = bottomBar(sr);
if (bw && !hideBottom) {
const br = bw.getBoundingClientRect();
if (br.height > 10 && br.width > 40) {
let usable = false;
const vhh = innerHeight || document.documentElement.clientHeight;
try {
/* ★ 必须量"真画出来的那个 textarea"(liveInput),不能用 edMetrics。
* edMetrics 为了兼容 inline 宿主会往上借祖先尺寸 —— 吸底条里那个 0×0 的
* 空壳会被借成整条的 1440×56,于是误判"可用",我们就让位给一条点不动、
* 打不了字的壳。页面表现正是"底部输入框有时候不显示"(看起来有位置,其实没框)。 */
const eds = allEditors(bw);
for (let i = 0; i < eds.length; i++) {
const tag = (eds[i].tagName || '').toLowerCase();
if (tag !== 'textarea' && !eds[i].isContentEditable) continue;
const li = liveInput(eds[i]);
if (!li) continue;
let lr = null;
try { lr = li.getBoundingClientRect(); } catch (e) { lr = null; }
if (!lr || lr.width < 60 || lr.height < 12) continue;
if (lr.bottom <= 0 || lr.top >= vhh) continue; // 画在视口外,用户看不见
usable = true; break;
}
} catch (e) { usable = false; }
if (usable) { pinSkips = 'biliBottom'; unpinComposer(); return; }
/* 露着、但里面没有能打字的输入框 —— 典型就是切原生再切回树之后的那个空壳。
* 直接把压掉规则补进样式表,然后继续往下自己钉真框。 */
if (!hideBottom) {
hideBottom = true;
try {
if (hideSheet && hideSheet.textContent.indexOf('bottom-fixed-wrapper') < 0) {
hideSheet.textContent = HIDE_SEL + ',.bili-comments-bottom-fixed-wrapper{display:none!important}';
}
} catch (e) { /* ignore */ }
pinSkips = 'killBiliBottom';
}
}
}
} catch (e) { /* ignore */ }
const vh = innerHeight || document.documentElement.clientHeight;
const sy = window.pageYOffset || document.documentElement.scrollTop || 0;
const treeR = rootEl.getBoundingClientRect();
if (fbPin) {
// 已经钉住了:等用户滚回发布框原来的位置(或滚过整棵树的底部)再放开
const naturalVisible = sy <= fbPin.naturalY - 40;
if (naturalVisible || treeR.bottom < 80) { unpinComposer(); return; }
idleSince = 0;
const blk = fbPin.node;
if (!blk || !blk.isConnected) { unpinComposer(); return; }
blk.style.setProperty('left', Math.round(treeR.left) + 'px', 'important');
blk.style.setProperty('width', Math.round(treeR.width) + 'px', 'important');
padCard(blk); // 被 B 站重建/重排冲掉了就补回来(幂等,不会越加越大)
try { clampEmptyEditor(ed); } catch (e) { /* ignore */ }
const hh = pinCorrect(blk, treeR, ed);
if (hh > 0) {
setFabGap(hh + 16);
setSwitchExtra(hh + 8); // 胶囊抬到吸底框上方,别互相压
}
return;
}
const em = edSize(ed); // inline 宿主自身是 0x0,必须量到内层
const r = { top: em.top, bottom: em.bottom, width: em.w, height: em.h };
if (r.width < 40) { pinSkips = 'width'; bottomFallback(); return; } // 还没渲染出来
if (r.bottom >= 30) { pinSkips = 'inView'; bottomFallback(); return; } // 发布框还在视口里,交给 B 站自己
if (treeR.bottom < 120) { pinSkips = 'treeOut'; bottomFallback(); return; } // 已经滚过评论区了
// 钉之前先把上一轮遗留的"幽灵卡片"(B 站克隆带过来的内联样式)清干净
try { sweepPinGhosts(); } catch (e) { /* ignore */ }
const blk = composerBlock(ed);
if (!blk || !blk.style || blk === sr) { pinSkips = 'noBlk'; bottomFallback(); return; }
/* 这几个 id 是原生列表自己的容器,绝不可能当发布框钉 —— 钉上就是"底部一块空白板"。
* 兜底黑名单:正常 composerBlock 走不到这,真机那次是 #contents。 */
const badId = (blk.id || '').toLowerCase();
if (badId === 'contents' || badId === 'feed' || badId === 'new' || badId === 'replies') {
pinSkips = 'blkIsList'; return;
}
// 保险:要钉的块不能比输入框高太多 —— 那说明它是整个原生评论区,
// 钉住它等于把评论列表整块搬到视口底部,页面表现就是"原生区消失、只剩树"。
let bh = 0;
const eh = em.h;
try { bh = blk.getBoundingClientRect().height; } catch (e) { bh = 0; }
if (eh > 0 && bh > eh * 2 + 24) { pinSkips = 'tooBig'; return; }
/* 绝对上限:超过半屏就不可能是发布框(正常 43~120,最多带表情面板)。
* 真机被钉成 260px 的那次就是 #contents,有这条连"开始长"的机会都没有。 */
const capH0 = Math.max(180, Math.min(560, Math.round(vh * 0.55)));
if (bh > capH0) { pinSkips = 'blkHuge'; return; }
if (hasVisibleRow(blk)) { pinSkips = 'hasRow'; return; } // 混着评论行 → 不钉
const saved = {};
for (let i = 0; i < PIN_PROPS.length; i++) saved[PIN_PROPS[i]] = blk.style.getPropertyValue(PIN_PROPS[i]);
// edH:钉之前量到的输入框自然高度。钉之后块可能把它压扁,现量就不准了
fbPin = { node: blk, saved: saved, naturalY: Math.round(sy + r.top), edH: Math.round(em.h) };
// 留印记 + 原值:B 站克隆节点时会把它们一起复制,巡检据此把复制品还原
try { blk.setAttribute(PIN_ATTR, encodeURIComponent(JSON.stringify(saved))); } catch (e) { /* ignore */ }
blk.style.setProperty('position', 'fixed', 'important');
blk.style.setProperty('right', 'auto', 'important');
blk.style.setProperty('top', 'auto', 'important');
blk.style.setProperty('bottom', '10px', 'important'); // 与视口底留 10px,纠偏的目标也是 vh-10
blk.style.setProperty('left', Math.round(treeR.left) + 'px', 'important');
blk.style.setProperty('width', Math.round(treeR.width) + 'px', 'important');
blk.style.setProperty('z-index', '2147482400', 'important');
blk.style.setProperty('background', themeDark() ? '#17181a' : '#ffffff', 'important');
blk.style.setProperty('box-shadow', '0 -2px 12px rgba(0,0,0,.16)', 'important');
padCard(blk); // 补内边距,别让头像/输入框贴着卡片边缘
// 钉住这一刻就先把"空着却三行高"的编辑区压回一行,免得第一下点击光标落错行
try { clampEmptyEditor(ed); } catch (e) { /* ignore */ }
// 按实际落点纠偏后,再用真实高度给树留底部空间、把胶囊抬上去
const h = pinCorrect(blk, treeR, ed);
if (h > 0) {
setFabGap(h + 16);
setSwitchExtra(h + 8); // 胶囊抬到吸底框上方,别互相压
}
log('发布框已钉到视口底部(' + h + 'px,纠偏 ' + pinFix + ')');
/* 钉住的一瞬间光标本来就在输入框里(滚回来接着打字)——补一次让位判定,
* 这种情况等不来 focusin(焦点从头到尾没动过)。 */
try {
if (focusInComposer()) { lowHold = Date.now() + LOW_HOLD; setMiniLow(1); }
} catch (e) { /* ignore */ }
}
function tidyNativeTree(force) {
if (State.view !== 'tree' || !nativeEl || !nativeEl.isConnected) return;
const now = Date.now();
if (!force && now - tidyAt < 1500) return;
tidyAt = now;
const sr = nativeEl.shadowRoot;
if (!sr) return;
const ed = shadowEditor(sr);
if (!ed) return;
guardClipFocus(sr);
killEndHints(sr, ed);
ensureEditorVisible(ed);
syncFabGap(ed);
try { pinComposer(); } catch (e) { /* ignore */ }
}
function restoreNativeTweaks() {
for (let i = 0; i < tailKilled.length; i++) {
const n = tailKilled[i];
try { n.style.display = n.__tlDisp || ''; delete n.__tlDisp; } catch (e) { /* ignore */ }
}
tailKilled = [];
tidyAt = 0;
}
/* ---------- 只保留一个原生评论区 ----------
* B 站有时会在页面里留下第二份评论容器(先渲染一个空壳,稍后又在别处
* 渲染真正的列表),树视图下就会在页面底部多出一整块原生评论区。
* 这里:主评论区 = 第一个"带发布框"的 bili-comments,其余全部藏掉。
*/
function hasBox(n) {
const sr = n && n.shadowRoot;
if (!sr) return false;
try { return !!(sr.querySelector('bili-comment-box') || sr.querySelector('textarea')); }
catch (e) { return false; }
}
/* 给每个 bili-comments 打分,选出"真正的评论区":
* 有发布框 +6、有楼层列表 +4、有标题栏 +1、有实际高度 +2,
* 空壳(没有 shadowRoot 或高度为 0)直接判负。只看"有没有发布框"太脆——
* 未登录 / 新版布局下发布框可能整块不存在,结果选到页面末端的空壳上。 */
function nativeScore(n) {
const sr = n && n.shadowRoot;
if (!sr) return -100;
let s = 0;
try {
if (sr.querySelector('bili-comment-box, textarea, [contenteditable="true"]')) s += 6;
if (sr.querySelector('bili-comment-thread-renderer, [class*="reply-item"], .reply-list')) s += 4;
if (sr.querySelector('bili-comments-header-renderer')) s += 1;
if (/评论\s*\d/.test(sr.textContent || '')) s += 1;
const r = n.getBoundingClientRect();
if (r.height > 200) s += 2;
if (r.height < 5) s -= 10;
} catch (e) { return -100; }
return s;
}
function pickPrimaryNative() {
const all = [].slice.call(document.querySelectorAll('bili-comments'));
if (!all.length) return null;
let best = null, bestS = -999;
// 第一优先级:影子树里真的有输入框的那些。
// 只按分数选曾经翻过车 —— 页面里同时存在"还没加载的空壳"和"真评论区"时,
// 空壳可能因为坐标/时机拿到更高分,一旦选错,后面 sweepNative 会把真正的
// 评论区(连同输入框)一起隐藏,表现就是"输入框消失"。
const withEditor = [];
for (let i = 0; i < all.length; i++) {
const sr = all[i].shadowRoot;
if (sr && findEditor(sr)) withEditor.push(all[i]);
}
const pool = withEditor.length ? withEditor : all;
for (let i = 0; i < pool.length; i++) {
const s = nativeScore(pool[i]);
if (s > bestS) { bestS = s; best = pool[i]; }
}
// 全是空壳(都还没加载出来)时先返回第一个,等下一轮再挑
return bestS <= -99 ? pool[0] : best;
}
function sweepNative() {
const all = document.querySelectorAll('bili-comments');
if (!nativeEl || !nativeEl.isConnected) nativeEl = pickPrimaryNative();
for (let i = 0; i < all.length; i++) {
const n = all[i];
if (n === nativeEl || !n.isConnected) continue;
if (rootEl && (n.contains(rootEl) || rootEl.contains(n))) continue;
if (State.view === 'tree') { n.style.display = 'none'; n.setAttribute('data-tl-dup', '1'); }
else if (n.getAttribute('data-tl-dup')) { n.style.display = ''; n.removeAttribute('data-tl-dup'); }
}
// 包裹层(老版 comment-container / #comment)里若还有一整套评论,也一起收掉
const wraps = document.querySelectorAll('.comment-container, #comment, .comment-wrap');
for (let i = 0; i < wraps.length; i++) {
const w = wraps[i];
if (w === hostEl || !w.isConnected) continue;
if (rootEl && (w.contains(rootEl) || w.contains(nativeEl))) continue;
if (!w.querySelector('bili-comments, textarea')) continue;
if (State.view === 'tree') { w.style.display = 'none'; w.setAttribute('data-tl-dup', '1'); }
else if (w.getAttribute('data-tl-dup')) { w.style.display = ''; w.removeAttribute('data-tl-dup'); }
}
}
// 立即应用当前视图,不刷新页面
function applyView() {
const isTree = State.view === 'tree';
if (rootEl) rootEl.classList.toggle('tl-hidden', !isTree);
if (headHost) {
headHost.classList.toggle('tl-hidden', !isTree);
// 顶栏搬出了 #tl-root,深色主题要跟着列表走,别一半白一半黑
if (rootEl) headHost.classList.toggle('tl-dark', rootEl.classList.contains('tl-dark'));
}
applyNativeVisibility(isTree);
sweepNative();
// 切视图时立刻收一次残局:上一轮钉出来的内联样式(以及被 B 站克隆带走的复制品)
// 必须马上还原,否则会变成盖在底部、点不动的"幽灵卡片"。
try { sweepPinGhosts(); } catch (e) { /* ignore */ }
updateSwitch();
if (isTree) {
schedulePaint();
// 切回树就立刻重排一次(pin / 发布框 / 底部留白),别等 1.5 秒的巡检节流
try { tidyAt = 0; tidyNativeTree(true); } catch (e) { /* ignore */ }
}
}
async function setView(v) {
if (v !== 'tree' && v !== 'native') return;
if (State.view === v) return;
State.view = v;
savePref(v);
applyView();
if (v === 'tree') {
if (mounted && rootEl && rootEl.isConnected) { applyView(); return; }
// 之前一直停在原生视图:这时才真正去拉数据
startPolling();
await boot();
applyView();
status('已切到树状视图', 'ok');
} else {
status('已切回 B 站原生评论区');
}
}
/* ============================================================
* 常驻自愈看门狗
* 之前所有"维持现状"的动作都塞在 mount() 里的定时器里,一旦 boot 失败、
* 或者挂载后被 B 站重建,就没人再管了 —— 表现为:评论树消失、原生评论区
* 又露出来、开关也丢了。现在改成每秒一次无条件巡检:
* 谁没了补谁,全部 try/catch 隔离,任何一步出错都不影响其它步骤。
* ============================================================ */
let supTimer = null;
let lastBootTry = 0;
let bootBackoff = 1200;
function enforceTree() {
if (!rootEl || !rootEl.isConnected) return false;
let needPaint = false;
if (rootEl.classList.contains('tl-hidden')) rootEl.classList.remove('tl-hidden');
if (headHost && headHost.classList.contains('tl-hidden')) headHost.classList.remove('tl-hidden');
if (!nativeEl || !nativeEl.isConnected) nativeEl = pickPrimaryNative();
/* 顶栏必须紧贴在 bili-comments 之前:B 站重建评论区时会把整块节点换掉,
* 我们那块顶栏就跟着掉队(跑到列表下面,或者干脆不在文档里)。补一次很便宜。 */
try {
if (headHost && nativeEl && nativeEl.parentNode && headHost.nextSibling !== nativeEl) {
nativeEl.parentNode.insertBefore(headHost, nativeEl);
}
} catch (e) { /* ignore */ }
if (nativeEl) {
const sr = nativeEl.shadowRoot;
let need = !sr;
if (!need) {
if (appliedRoot !== sr) need = true; // 原生组件被重建过
else if (!hideSheet || !hideSheet.isConnected) need = true; // 样式表被 B 站清掉了
else if (markedCount > 0) {
try { if (!sr.querySelector('[data-tl-hide]')) need = true; } catch (e) { /* ignore */ }
}
if (!need && nativeEl.style.display === 'none' && markedCount > 0) need = true;
}
// 刚因为"发布框被藏没"回滚过的话,退避 8 秒再试,别每秒空转一遍
if (need && Date.now() - rollbackAt > 8000) {
applyNativeVisibility(true);
needPaint = true;
}
}
sweepNative();
// B 站会把发布框的吸底样式重新刷回来(发完评论、切排序等),这里低频补一遍
try { tidyNativeTree(); } catch (e) { /* ignore */ }
// 不再"每秒把树搬到原生评论区旁边"。
// 之前按 nativeEl.parentElement 搬,一旦 primary 认错(页面末端那个空壳),
// 树就被反复搬到页面最底部,真正的评论区位置反而空着 —— 这是"树跑到末端"的元凶。
// 现在树的落点只在 mount() 里决定一次;容器被 B 站整体替换时 rootEl 会脱离文档,
// enforceTree 返回 false,由 tryMount() 重新挂载。
if (needPaint) schedulePaint();
return true;
}
function enforceNative() {
try { unpinComposer(); } catch (e) { /* ignore */ }
if (rootEl && rootEl.isConnected && !rootEl.classList.contains('tl-hidden')) {
rootEl.classList.add('tl-hidden');
}
if (headHost && headHost.isConnected && !headHost.classList.contains('tl-hidden')) {
headHost.classList.add('tl-hidden');
}
if (nativeEl && (hideSheet || appliedRoot || nativeEl.style.display || tailKilled.length)) {
applyNativeVisibility(false);
}
sweepNative();
}
/* 诊断:树视图下若还露着"另一套原生评论区",把它的 DOM 路径打到控制台一次
* (自动隐藏不好盲改选择器,先让日志告诉我它长什么样) */
const rogueLogged = {};
let rogueTick = 0;
function nodePath(n) {
const parts = [];
let p = n;
for (let i = 0; p && i < 5; i++) {
let cls = '';
if (typeof p.className === 'string' && p.className.trim()) {
cls = '.' + p.className.trim().split(/\s+/).slice(0, 2).join('.');
}
parts.unshift(p.tagName.toLowerCase() + (p.id ? '#' + p.id : '') + cls);
p = p.parentElement;
}
return parts.join(' > ');
}
function rogueProbe() {
try {
const nodes = document.querySelectorAll('bili-comments-header-renderer,[class*="comment-header"],[class*="reply-header"]');
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
if (isOurs(n)) continue;
if (!n.getClientRects || !n.getClientRects().length) continue;
const t = (n.textContent || '').replace(/\s+/g, '');
if (!/^评论\d/.test(t)) continue;
const path = nodePath(n);
if (rogueLogged[path]) continue;
rogueLogged[path] = 1;
log('发现另一套原生评论区(未隐藏):' + path);
}
} catch (e) { /* ignore */ }
}
function tryMount() {
if (booting) return; // 正在挂,别叠加
const now = Date.now();
if (now - lastBootTry < bootBackoff) return;
lastBootTry = now;
Promise.resolve(boot()).then(function (ok) {
bootBackoff = ok ? 1000 : Math.min(3000, Math.round(bootBackoff * 1.5));
}, function () { bootBackoff = Math.min(3000, Math.round(bootBackoff * 1.5)); });
}
/* 清理"被克隆出来的副本"。
* B 站的评论小窗 / 某些布局会把整个评论区 DOM 复制一份,复制品里自然也带着
* 我们的 #tl-root 和 #tl-switch —— 于是页面末端就多出一整块"和我做的一模一样"的
* 评论树。那不是示意模块,是副本。这里只保留本实例那一份,其余直接移除。 */
function killClones() {
const roots = document.querySelectorAll('#tl-root');
for (let i = 0; i < roots.length; i++) {
const r = roots[i];
if (r === rootEl) continue;
if (rootEl && rootEl.contains(r)) continue;
try { r.remove(); log('已移除重复的评论树副本'); } catch (e) { /* ignore */ }
}
const sws = document.querySelectorAll('#tl-switch');
for (let i = 0; i < sws.length; i++) {
if (sws[i] === switchEl) continue;
try { sws[i].remove(); } catch (e) { /* ignore */ }
}
const heads = document.querySelectorAll('#tl-headroot');
for (let i = 0; i < heads.length; i++) {
if (heads[i] === headHost) continue;
try { heads[i].remove(); } catch (e) { /* ignore */ }
}
}
let swTick = 0;
let supN = 0;
let remountAt = 0; // 上一次"树被摘掉重挂"的时间(退避用)
let remountN = 0; // 连续重挂次数,挂成功后清零
/* 只读、只看第一优先级来源:评论组件自己的 data-params("type,oid")。
* 换视频 / 合集连播时它会先变,比 __INITIAL_STATE__ 可靠。 */
/* 列表页(稍后再看 / 收藏夹 / 合集连播)换集时,组件的 data-params 不一定跟着更新,
* 所以看门狗只信"组件自己变了"(跟上次观测到的值不同)这一个判据;
* 地址那一路交给 pageKey 去触发整页重建,两边不互相否定 ——
* 否则 地址=333 / 组件=444 会来回打架,每次巡检重拉一遍评论,页面疯狂闪烁。
* 刚重建完的 3 秒是静默期,只记录不判断,等 B 站把 data-params 写完。 */
let lastDomOid = -1;
let oidLockUntil = 0;
/* 评论组件自己带着 "type,oid",这两个值是唯一权威来源:
* 视频页 "1,aid" · 番剧页 "1,aid" · 课堂/课程页 "33,ep 或 ss"。
* 以前只取 oid、type 写死 1,课程页就成了拿 type=1 去查 33 的 oid,
* 接口直接回 12002「当前页面评论功能已关闭」,树上只剩一行报错。
* 切视图时 B 站会留一份隐藏克隆体,优先取真在页面上的那个。 */
function paramsOf() {
let first = null, vis = null;
try {
const cs = document.querySelectorAll('bili-comments[data-params]');
for (let i = 0; i < cs.length; i++) {
const parts = String(cs[i].getAttribute('data-params')).split(',');
const t = Number(parts[0]);
const o = Number(parts[1]);
if (!(o > 0)) continue;
const cur = { type: t > 0 ? t : 1, oid: o };
if (!first) first = cur;
let v = false;
try { v = cs[i].getClientRects().length > 0; } catch (e) { v = false; }
if (v) { vis = cur; break; }
}
} catch (e) { /* ignore */ }
return vis || first;
}
function domOid() {
const p = paramsOf();
return p ? p.oid : 0;
}
let lastDomType = 1;
function oidQuick() {
try {
const p = paramsOf();
const d = p ? p.oid : 0;
if (Date.now() < oidLockUntil) {
if (d) { lastDomOid = d; if (p) lastDomType = p.type; }
return 0;
}
const changed = !!d && d !== lastDomOid;
if (d) lastDomOid = d;
if (p) lastDomType = p.type;
return (changed && State.oid && d !== State.oid) ? d : 0;
} catch (e) { return 0; }
}
/* 让右下角小窗压在吸底发布框前面。
*
* 真机实测的层叠结构(1400×900):
* .bpx-player-container position:fixed z-index:100000 ← 小窗态
* 它的祖先 .left-container 是 sticky + z-index:1(形成层叠上下文),
* 而发布框(bili-comments 影子树里的原生 #commentbox)也在这个上下文里 ——
* 两边能直接比数值。发布框钉底时写的是 2147482400,比 100000 大,
* 于是发布框反过来压住小窗右下角一块(截图里那条白条切掉画面就是它)。
*
* 做法:只在小窗真的出现(position 变成 fixed)时,把小窗抬到发布框之上一档。
* 仍低于胶囊 2147483600 和图片查看器 2147483000,所以那两个按钮照样能点;
* 也不去动发布框自己的层级,其他浮层压不住它。
* 退出小窗(回到普通播放器)就把内联 z-index 还回去,不留下副作用。 */
const MINI_Z = '2147482500';
/* v1.7.40:光标进输入框时反过来 —— 小窗退到吸底框(2147482400)下面,让"正在打字
* 的那一条"完整露出来;光标一离开立刻升回去。只改这一个数值:不新增浮层、不动
* 发布框自己的层级(v1.7.38 试过压发布框,反而更乱)。真要关掉,把 LOW 改成和
* MINI_Z 一样即可,其余代码全部失效为空操作。 */
const MINI_Z_LOW = '2147482300';
let miniLow = 0; // 1 = 正在给吸底发布框让位
let lowHold = 0; // 这个时刻之前不自动让位(用户还在发布框里连着点)
const LOW_HOLD = 500; // 让位后至少保持这么久,兜住"点表情/按钮"的 blur→focus 抖动
function raiseMini() {
let cs;
try { cs = document.querySelectorAll('.bpx-player-container'); } catch (e) { return; }
/* 吸底框没了(滚回去 / 换页 / 被 B 站换掉)就当场复位:那种"小窗永远被压着"
* 的假状态用户自己没法恢复,绝不能留着。 */
if (miniLow && !(fbPin && fbPin.node && fbPin.node.isConnected)) miniLow = 0;
const z = miniLow ? MINI_Z_LOW : MINI_Z;
for (let i = 0; i < cs.length; i++) {
const n = cs[i];
let mini = false;
try { mini = getComputedStyle(n).position === 'fixed'; } catch (e) { mini = false; }
try {
if (mini) {
n.setAttribute('data-tl-mini', '1');
n.style.setProperty('z-index', z, 'important');
} else if (n.getAttribute('data-tl-mini') === '1') {
n.removeAttribute('data-tl-mini');
n.style.removeProperty('z-index');
}
} catch (e) { /* ignore */ }
}
}
/* ---------- 输入中的层级让位(v1.7.40)----------
* 判定只认一件事:这次操作是不是冲着**被钉住的那个发布框**去的。
*
* ① pointerdown 命中发布框 → 立刻降小窗。必须赶在 mousedown 生效前改完,
* 否则点了输入框却因为小窗在上面而丢焦点,用户看到的是"点不进去"。
* ② focus / Tab 聚焦 → 同上(键盘操作没有 pointerdown)。
* ③ blur 后 90ms 复核:焦点确实离开发布框了才升回去。点表情、点发布框
* 里的按钮会连着触发 blur→focus,90ms 窗口 + lowHold 能兜住这一串。
* 点小窗自己的时候**不动层级**:此时 mousedown 已经发出去了,改 z-index 只会让
* mouseup 落到别的元素上,把拖动 / 双击全屏打断。交给 ③ 和 click 去处理。
*/
function hitIn(e, node) {
if (!node) return false;
let p = null;
try { p = e && e.composedPath ? e.composedPath() : null; } catch (err) { p = null; }
if (p && p.length) {
for (let i = 0; i < p.length; i++) if (p[i] === node) return true;
return false; // 影子树里的真实路径,直接判定,别退回去用 target(会被 retarget 成宿主)
}
let n = e && e.target;
for (let i = 0; n && i < 40; i++) { if (n === node) return true; n = parentAcross(n); }
return false;
}
/* 焦点此刻是不是在吸底发布框里。bili-comments 的影子树是分层的(宿主 →
* bili-comment-box → textarea),只看 document.activeElement 会误判成"没聚焦",
* 必须一层层 shadowRoot.activeElement 钻到底,再沿 parentAcross 往上比。 */
function focusInComposer() {
let blk = null;
try { blk = fbPin && fbPin.node; } catch (e) { blk = null; }
if (!blk || !blk.isConnected) return false;
let n = null;
try { n = document.activeElement; } catch (e) { return false; }
for (let i = 0; n && n.nodeType === 1 && i < 24; i++) {
if (n === blk) return true;
const sr = n.shadowRoot;
if (sr && sr.activeElement && sr.activeElement !== n) { n = sr.activeElement; continue; }
n = parentAcross(n);
}
return false;
}
function setMiniLow(v) {
if (miniLow === v) return;
miniLow = v;
try { raiseMini(); } catch (e) { /* ignore */ }
}
try {
document.addEventListener('pointerdown', function (e) {
try {
if (!fbPin || !fbPin.node || !fbPin.node.isConnected) return;
if (hitIn(e, fbPin.node)) {
lowHold = Date.now() + LOW_HOLD; // 还在发布框里操作,先别急着让回去
setMiniLow(1);
} else {
lowHold = 0; // 按到别处(小窗 / 树 / 空白)→ 允许让回去
}
} catch (err) { /* ignore */ }
}, true);
/* 坑:shadow DOM 里的 focusin/focusout 是 composed:false,传到影子树边界就断了,
* document 上永远收不到 —— 必须用 focus/blur(composed:true、不冒泡,靠捕获阶段
* 才拿得到)。这是第一版写完在 mock 里"点了输入框没反应"的原因。 */
document.addEventListener('focus', function () {
try {
if (focusInComposer()) {
lowHold = Date.now() + LOW_HOLD;
setMiniLow(1);
/* 光标刚进来:如果编辑区还空着却被撑成两三行,光标会落在中间那一行。
* 这里立刻压回一行(不等下一秒巡检),用户点下去看到的才是第 1 行。 */
try {
if (nativeEl && nativeEl.shadowRoot) clampEmptyEditor(shadowEditor(nativeEl.shadowRoot));
} catch (err) { /* ignore */ }
}
} catch (err) { /* ignore */ }
}, true);
document.addEventListener('blur', function () {
if (!miniLow) return;
/* 90ms 让"blur → focus"这一串先走完(点表情 / 点发布框里的按钮会连着触发);
* 若正好落在 lowHold 窗口里,就等窗口到期再判一次 —— 这里直接 return 会把
* "聚焦了一下又点到别处"卡在低位,而且再没有事件把它叫醒。 */
setTimeout(function () {
const check = function () {
try { if (!focusInComposer()) setMiniLow(0); } catch (err) { /* ignore */ }
};
try {
const wait = lowHold - Date.now();
if (wait > 0) { setTimeout(check, wait + 20); return; }
check();
} catch (err) { /* ignore */ }
}, 90);
}, true);
} catch (e) { /* ignore */ }
/* 有些页面把整个评论区折在「评论(213)」这样的 tab 里(课堂 / 课程最典型)。
* 实测:树挂上去了、行数也对,但祖先 .archive-comment-box 是 display:none,
* offsetParent 为 null、rect 0×0 —— 用户看到的就是"这个页面没生效"。
* 这里检测到"树被祖先藏住"时,替用户点一次那个 tab;只点一次、只认
* 「评论 / 评论(数字)」这种文案,点不开就算了,不做别的。
* 注意:用户自己点的"收起整栋楼"不会触发 —— 那是子树,不是 rootEl 的祖先。 */
let unfoldTried = '';
function unfoldComments() {
if (!rootEl || !rootEl.isConnected) return;
let hidden = false;
try {
let p = rootEl, d = 0;
while (p && d < 12) {
const st = getComputedStyle(p);
if (st.display === 'none') { hidden = true; break; }
p = p.parentElement; d++;
}
} catch (e) { return; }
if (!hidden) return;
if (unfoldTried === location.pathname) return;
unfoldTried = location.pathname;
let best = null;
try {
const cands = document.querySelectorAll('[role=tab],li,div,span,a,button');
for (let i = 0; i < cands.length; i++) {
const n = cands[i];
const t = (n.textContent || '').replace(/\s+/g, '');
if (!/^评论[((]?\d*[))]?$/.test(t)) continue;
const r = n.getBoundingClientRect();
if (r.width < 24 || r.height < 12) continue;
if (best && best.w * best.h >= r.width * r.height) continue;
best = { n: n, w: r.width, h: r.height };
}
} catch (e) { /* ignore */ }
if (!best) return;
log('评论区被折叠(' + nodePath(best.n) + '),自动展开一次');
try { best.n.click(); } catch (e) { /* ignore */ }
}
function supervise() {
supN++;
try { raiseMini(); } catch (e) { /* ignore */ }
try { ensureSwitch(); } catch (e) { /* ignore */ }
// 每 3 秒复量一次:B 站浮钮(小窗 / 客服 / 回顶部)是懒加载的,
// 出现得比开关晚,量一次就不再管会一直压着它们。
if (++swTick % 3 === 0) { try { placeSwitch(); } catch (e) { /* ignore */ } }
try { killClones(); } catch (e) { /* ignore */ }
try { sweepPinGhosts(); } catch (e) { /* ignore */ }
if (State.view === 'tree' && (++rogueTick % 5 === 0)) rogueProbe();
try {
if (State.view === 'tree') {
if (!rootEl || !rootEl.isConnected) mounted = false;
/* 体检一:换分P 时 aid 不变,B 站却会把评论区容器整块换掉。最坏的情况是
* 我们的树连父容器一起"还在文档里",但被塞进了一个已经塌成 0 高的新层——
* isConnected 为 true、enforceTree 一切正常,页面上却什么都没有。
* 只有"有内容 + 量出来高度约等于 0"这一个组合能确定是坏了,摘掉重挂。 */
if (mounted && rootEl && rootEl.isConnected && State.roots.length) {
let h = 0, hh = 0;
try { h = rootEl.getBoundingClientRect().height; } catch (e) { h = 0; }
try { hh = hostEl ? hostEl.getBoundingClientRect().height : 0; } catch (e) { hh = 0; }
/* 宿主自己就是 0 高(课程页评论没展开、番剧页评论折在 tab 里)时树自然也量不出高度,
* 那不是坏了。不加这道闸会每 2.5 秒"摘掉重挂"一次,用户看到评论区一直在转圈,
* 表现为"插件没生效"。 */
if (h < 12 && hh > 0 && Date.now() - remountAt > 2500 && remountN < 6) {
remountAt = Date.now();
remountN++;
log('树被换了容器(高度 ' + Math.round(h) + '),摘掉重挂');
try { rootEl.remove(); } catch (e) { /* ignore */ }
if (headHost) { try { headHost.remove(); } catch (e) { /* ignore */ } }
rootEl = null;
listEl = null;
headHost = null;
mounted = false;
}
}
/* 体检二:oid 变了(合集自动连播 / 稍后再看自动切集 / 站内跳转到另一条视频,
* 地址还没来得及触发重建)。树还在、但里面是上一条视频的评论 ——
* 用户看到的就是"评论区没变"。 */
if (mounted && State.oid && supN % 3 === 0) {
const o = oidQuick();
if (o && o !== State.oid) {
log('评论区 oid 变化:' + State.oid + ' → ' + o + ',重新拉评论');
State.oid = o;
if (lastDomType > 0) State.type = lastDomType;
Object.keys(SortCache).forEach(function (k) { delete SortCache[k]; });
State.roots = [];
State.page = 1;
State.next = 0;
State.isEnd = false;
State.collapsed.clear();
if (listEl) { try { renderAll(true); } catch (e) { log('重拉评论失败', e); } }
}
}
if (!enforceTree()) {
/* 评论组件"晚到"时尽快出树:番剧 / 影视 / 课程的评论区常常折在「评论」tab 里,
* 点开才插入 bili-comments。原来退避会涨到 3 秒,从点开到出树有明显空白,
* 用户看到的就是"点了没反应 / 没启动"。这里发现宿主已经在了就把退避压到 0.8 秒。 */
try { if (!rootEl && findHost()) bootBackoff = Math.min(bootBackoff, 800); } catch (e) { /* ignore */ }
tryMount();
}
/* 标题栏那张小样式表会被 B 站重建节点带走(它住在 header-renderer 的
* shadowRoot 里)。每秒补一次,成本极低,不补的话切排序/翻页后标题栏会回来。 */
try {
if (nativeEl && nativeEl.shadowRoot) hdrHidden = hideHeaderParts(nativeEl.shadowRoot);
} catch (e) { /* ignore */ }
try { pinComposer(); } catch (e) { /* ignore */ }
// 评论容器换了一份(换 P / 切排序 / SPA 重建)就重挂观察器,晚到的发布框能立刻接住
try { watchComments(); } catch (e) { /* ignore */ }
// 每 2 秒看一次"树是不是被折叠的评论区藏住了"(课堂/课程页常见)
if (supN % 2 === 0) { try { unfoldComments(); } catch (e) { /* ignore */ } }
} else {
enforceNative();
updateSwitch();
}
} catch (e) { log('自愈巡检出错', e); }
}
function startSupervisor() {
if (supTimer) return;
supTimer = setInterval(supervise, 1000);
supervise();
}
/* ---------- 渲染一个节点 ---------- */
function renderNode(node, ctx) {
const r = node.reply;
const m = r.member || {};
const depth = Math.min(node.depth, CONF.maxIndentLevel);
const isUP = State.upperMid && m.mid === State.upperMid;
const isRootPin = ctx.isRoot && State.topRpids.has(String(r.rpid));
const row = el('div', 'tl-row');
row.style.paddingLeft = (depth * CONF.indent) + 'px';
row.dataset.rpid = r.rpid;
// 头像
const av = el('a', 'tl-av');
av.href = '//space.bilibili.com/' + (m.mid || '');
av.target = '_blank';
av.rel = 'noopener noreferrer';
const img = el('img');
let face = m.avatar || '';
if (face.indexOf('//') === 0) face = 'https:' + face;
img.src = face.replace(/@[^/]*$/, '') + '@64w_64h_1c.webp';
img.alt = '';
img.loading = 'lazy';
img.referrerPolicy = 'no-referrer';
img.onerror = () => { img.style.display = 'none'; };
av.appendChild(img);
row.appendChild(av);
// 主体
const main = el('div', 'tl-main');
const meta = el('div', 'tl-meta');
if (isRootPin) meta.appendChild(el('span', 'tl-tag pin', '置顶'));
const nameCls = 'tl-name' + (isUP ? ' is-up' : (m.vip && m.vip.status === 1 ? ' is-vip' : ''));
const nameEl = el('span', nameCls, esc(m.uname || ''));
meta.appendChild(nameEl);
const ip = ipOf(r);
if (ip) meta.appendChild(el('span', 'tl-pill', esc(ip)));
const lv = (m.level_info && m.level_info.current_level) || 0;
if (lv) meta.appendChild(el('span', 'tl-lv lv' + lv, 'LV' + lv));
if (isUP) meta.appendChild(el('span', 'tl-tag up', '楼主'));
main.appendChild(meta);
// 正文
const content = el('div', 'tl-content');
content.innerHTML = renderText(r);
main.appendChild(content);
// 图片:同一条评论的多张图共用一份地址表,点开任意一张都能左右切
const pics = r.content && r.content.pictures;
if (pics && pics.length) {
const box = el('div', 'tl-pics');
const urls = [];
pics.forEach((p) => {
const s = ((p && (p.img_src || p.src)) || '').replace(/^\/\//, 'https://');
if (s) urls.push(s); // 空地址先剔掉,否则点开后的索引会和缩略图错位
});
urls.forEach((src, i) => {
const pi = el('img');
pi.src = src;
pi.loading = 'lazy';
pi.referrerPolicy = 'no-referrer';
pi.onclick = () => openViewer(urls, i);
box.appendChild(pi);
});
if (urls.length) main.appendChild(box);
}
// 操作行
const acts = el('div', 'tl-acts');
const likeBtn = el('span', 'tl-act');
likeBtn.innerHTML = thumbSvg() + '' + (r.like ? fmtNum(r.like) : '') + '';
likeBtn.title = '点赞';
likeBtn.onclick = () => doLike(r, likeBtn);
acts.appendChild(likeBtn);
const dislike = el('span', 'tl-act');
dislike.innerHTML = thumbSvg(true);
dislike.title = '点踩';
acts.appendChild(dislike);
const replyBtn = el('span', 'tl-act', '回复');
replyBtn.onclick = () => openEditor(main, r, node);
acts.appendChild(replyBtn);
/* 发布时间只当纯文本:以前做成了可点的"定位"入口(手型光标 + 悬停变色),
* 看起来像跳转链接,容易误触,按用户要求去掉这层效果。 */
const timeEl = el('span', 'tl-time', fmtTime(r.ctime));
acts.appendChild(timeEl);
main.appendChild(acts);
row.appendChild(main);
/* ---------- 时间轴几何 ----------
* 竖线不再"每行画一段"(那样一来某行带子回复,父层线就被子块顶断),
* 而是由**父节点自己**在头像正下方垂一条整线(.tl-spine),
* 每个直接子回复再从这条线拐一小段圆角挂钩(.tl-tick)接到自己头像中线。
* 线的 x 恒等于父头像的水平中心,所以"次级回复"的线一定长在"一级回复"头像下面。
*/
const wrap = el('div', 'tl-kid');
wrap.appendChild(row);
const depthPx = depth * CONF.indent;
const hasKids = node.children.length > 0;
// 挂钩:从父头像中心的竖线拐到本行头像左沿(顶层楼没有父级,不画)
if (!ctx.isRoot) {
const pCenterX = (depth - 1) * CONF.indent + CONF.avatar / 2;
const tick = el('div', 'tl-tick');
tick.style.left = pCenterX + 'px';
tick.style.width = (depthPx - pCenterX) + 'px'; // 收在头像左沿,不压住头像
tick.style.top = (CONF.avatar / 2 - 10) + 'px';
tick.style.height = '10px'; // 底边正好落在头像垂直中线
row.appendChild(tick);
}
if (hasKids) {
const kids = el('div', 'tl-children');
kids.id = 'tl-kids-' + r.rpid;
node.children.forEach((c) => kids.appendChild(renderNode(c, { isRoot: false })));
wrap.appendChild(kids);
attachParentUI(node, wrap, row, depth);
if (State.collapsed.has(String(r.rpid))) {
kids.classList.add('tl-hidden');
const nb = row.querySelector(':scope > .tl-node');
if (nb) nb.classList.add('is-collapsed');
}
}
return wrap;
}
/* 这栋楼一共多少条回复(含所有层级的后代)。楼中楼分页拉取时可能不是全量,
* 所以算的是"树里实际有的",和底部胶囊的 N 条回复口径一致。 */
function countDesc(node) {
let n = 0;
const walk = (item) => {
item.children.forEach((c) => { n += 1; walk(c); });
};
walk(node);
return n;
}
/* ---------- 父节点装饰:头像下的竖线 + 圆环折叠钮 ---------- */
function attachParentUI(node, wrap, row, depth) {
const d = Math.min(depth, CONF.maxIndentLevel);
const centerX = d * CONF.indent + CONF.avatar / 2;
let spine = wrap.querySelector(':scope > .tl-spine');
if (!spine) {
spine = el('div', 'tl-spine');
spine.style.left = centerX + 'px';
spine.style.top = CONF.avatar + 'px'; // 从头像底边开始,不留空档
spine.style.height = '0px';
wrap.appendChild(spine);
}
let btn = row.querySelector(':scope > .tl-node');
if (!btn) {
btn = el('div', 'tl-node');
btn.style.left = (centerX - 6) + 'px';
btn.style.top = (CONF.avatar + 3) + 'px';
row.appendChild(btn);
} else if (btn.classList.contains('is-collapsed')) {
/* 复用收起态预置的那颗圆环(见 attachPreloadNode):楼中楼一加载出来就是
* 展开的,加号要当场换回减号,否则会出现"楼已经展开、圆环还是 +" */
const kids = wrap.querySelector(':scope > .tl-children');
if (kids && !kids.classList.contains('tl-hidden')) btn.classList.remove('is-collapsed');
}
/* 无论新建还是复用,点击语义都要换成"折叠/展开":
* 预置那颗原本绑的是"加载楼中楼",加载完还留着就会点了没反应。 */
btn.onclick = (e) => {
e.stopPropagation();
toggleFold(node, btn, wrap);
};
/* 圆环只有 12px,光看形状判断不出这栋楼的规模。提示里带上总数:
* 不用展开、也不用滚到楼底那颗胶囊,悬停就知道有多少条。 */
btn.title = '这栋楼共 ' + fmtNum(countDesc(node)) + ' 条回复 · 点击折叠 / 展开';
return { spine, btn };
}
/* 没加载过楼中楼的楼,时间轴上也要留一颗圆环。
* 以前圆环只在"展开成功"之后才补(attachParentUI 只被 load 调用),
* 于是收起态的大楼整条时间轴就缺一颗节点,看着像断了一截
* (用户截图反馈:收起时有的楼没有圆环)。
* 这里预先画一颗“+”,点它等同于点下面那颗「展开 N 条回复」。 */
function attachPreloadNode(wrap, row, centerX, total, onOpen) {
let spine = wrap.querySelector(':scope > .tl-spine');
if (!spine) {
spine = el('div', 'tl-spine');
spine.style.left = centerX + 'px';
spine.style.top = CONF.avatar + 'px';
spine.style.height = (12 + 3 - 1) + 'px'; // 只垂到圆环下沿,不留尾巴
wrap.appendChild(spine);
}
if (!row) return null;
let btn = row.querySelector(':scope > .tl-node');
if (!btn) {
btn = el('div', 'tl-node is-collapsed');
btn.style.left = (centerX - 6) + 'px';
btn.style.top = (CONF.avatar + 3) + 'px';
btn.onclick = function (e) {
e.stopPropagation();
onOpen();
};
row.appendChild(btn);
}
btn.title = '这栋楼共 ' + fmtNum(total) + ' 条回复 · 点击展开';
return btn;
}
/* ---------- 连线绘制:只算"父头像底 → 最后一个子回复头像中线"这一段长度 ---------- */
function paintLines() {
if (!rootEl) return;
const wraps = rootEl.querySelectorAll('.tl-kid');
for (let i = 0; i < wraps.length; i++) {
const wrap = wraps[i];
const spine = wrap.querySelector(':scope > .tl-spine');
if (!spine) continue;
const kids = wrap.querySelector(':scope > .tl-children');
/* 收起(或没有可见子回复)时,竖线只能垂到圆环下沿就停。
* 圆环:top = 头像高 + 3,直径 12;竖线起点是头像底边,所以 12+3 = 15。
* 以前这里固定的 20px 会从圆环底下多伸出 5px,收起的楼下方就挂着一小截
* 悬空的"尾巴"(用户截图反馈)。留 1px 余量,避免正好压在圆环描边上。 */
const ringBottom = 12 + 3 - 1;
if (!kids || kids.classList.contains('tl-hidden')) {
spine.style.height = ringBottom + 'px';
continue;
}
const rows = kids.querySelectorAll(':scope > .tl-kid > .tl-row');
if (!rows.length) { spine.style.height = ringBottom + 'px'; continue; }
const last = rows[rows.length - 1];
const wrapTop = wrap.getBoundingClientRect().top;
// 最后一个子回复头像中线(相对本 wrap),减去竖线起点(头像底边 = 32)
const endY = last.getBoundingClientRect().top - wrapTop + CONF.avatar / 2;
spine.style.height = Math.max(ringBottom, Math.round(endY - CONF.avatar)) + 'px';
}
}
let paintQueued = false;
let paintTimer = 0;
function runPaint() {
paintQueued = false;
if (paintTimer) { clearTimeout(paintTimer); paintTimer = 0; }
paintLines();
}
function schedulePaint() {
if (paintQueued) return;
paintQueued = true;
// rAF 负责"下一帧准",setTimeout 兜底(后台标签页 / 节流环境下 rAF 可能长时间不回调,
// 一旦卡住 paintQueued 就再也画不出来,所以必须有超时保底)
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(runPaint);
paintTimer = setTimeout(runPaint, 120);
}
/* 圆环节点点击:翻转当前开合状态 */
function toggleFold(node, nodeBtn, wrap) {
swingFold(node, nodeBtn, wrap);
}
/* 收起时把留在原地的那颗"展开"胶囊拉回鼠标位置。
* 楼中楼一收,底部那颗"收起"当场消失,顶部这颗瞬间跳回主评论下方,
* 鼠标不动就落空了;这里按点击落点补一次滚动,让胶囊回到光标下,
* 想再展开不用挪鼠标。
* 只处理收起:展开时主评论本身不动,跟着滚反而会把上一条评论顶出视野。
*
* 为什么要连着校正近 1 秒、而不是只补一帧:
* 往上滚会把顶部的评论区头部("评论 N 条 / 最热 最新" + 发布框)拉进视口,
* B 站这时会把发布框从一行提示展开成整块,高度是**带着过渡动画变的**;
* 头部在楼上边,一变高整棵树就往下走,胶囊跟着离开光标几十像素。
* 只补一帧刚好错过这个动画,于是前几栋楼收起时总差那么一点。 */
function anchorPill(wrap, cursorY) {
if (typeof cursorY !== 'number') return;
// 用户一旦自己滚轮/按方向键,就立刻停手,别跟人抢滚动条
let stopped = false;
const stop = () => { stopped = true; };
const clear = () => {
window.removeEventListener('wheel', stop);
window.removeEventListener('touchstart', stop);
window.removeEventListener('keydown', stop, true);
};
try {
window.addEventListener('wheel', stop, { passive: true });
window.addEventListener('touchstart', stop, { passive: true });
window.addEventListener('keydown', stop, true);
} catch (e) { /* ignore */ }
const gaps = [0, 80, 140, 200, 240, 300]; // 累计约 0 / 80 / 220 / 420 / 660 / 960ms
let step = 0;
const align = () => {
if (stopped) { clear(); return; }
if (step >= gaps.length) { clear(); return; }
let pill = null;
// 收起后只剩一颗可见胶囊,直接按"有没有渲染盒"挑,不依赖 DOM 顺序
const list = wrap.querySelectorAll(':scope > div > .tl-folded');
for (let i = 0; i < list.length; i++) {
if (list[i].getClientRects().length) { pill = list[i]; break; }
}
if (pill) {
const r = pill.getBoundingClientRect();
if (r.height) {
const d = Math.round(cursorY - (r.top + r.height / 2));
if (Math.abs(d) >= 2) {
/* d>0:胶囊跑到光标上面去了,要往上滚(内容下移);d<0 反过来。
* 两个方向都交给浏览器自己夹到合法范围,滚不动就停在边界。 */
try { window.scrollBy({ top: -d, left: 0, behavior: 'instant' }); }
catch (e) { window.scrollBy(0, -d); }
}
}
}
const wait = gaps[step++];
if (wait >= 0) setTimeout(align, wait);
};
align();
}
function swingFold(node, nodeBtn, wrap, cursorY) {
const kids = wrap.querySelector('#tl-kids-' + node.reply.rpid);
if (!kids) return;
finishFold(node, nodeBtn, wrap, !kids.classList.contains('tl-hidden'), cursorY);
}
/* 唯一的落状态入口:圆环、文字按钮、恢复历史状态全走这里,
* 保证 DOM、State.collapsed、竖线三者不会打架 */
function finishFold(node, nodeBtn, wrap, collapsed, cursorY) {
const r = node.reply;
const kids = wrap.querySelector('#tl-kids-' + r.rpid);
if (!kids) return;
const key = String(r.rpid);
kids.classList.toggle('tl-hidden', collapsed);
if (nodeBtn) nodeBtn.classList.toggle('is-collapsed', collapsed);
if (collapsed) State.collapsed.add(key); else State.collapsed.delete(key);
if (wrap._tlSync) wrap._tlSync(collapsed);
// 直接量一次:点完立刻正确,不等下一帧
paintLines();
// 只有"点底部那颗收起"才需要跟手,圆环在楼顶本来就不动
if (collapsed && typeof cursorY === 'number') anchorPill(wrap, cursorY);
schedulePaint();
}
function currentBvid() {
const m = location.pathname.match(/\/video\/(BV[0-9A-Za-z]+)/i);
return m ? m[1] : '';
}
function renderText(reply) {
const c = reply.content || {};
let msg = c.message || '';
const emotes = c.emote || {};
const jumps = c.jump_url || {};
// @ 提及的 名字 -> mid
const midMap = {};
const atMap = c.at_name_to_mid || {};
Object.keys(atMap).forEach((k) => { midMap[k] = atMap[k]; });
(c.members || []).forEach((mb) => {
if (mb && mb.uname) midMap[mb.uname] = mb.mid;
});
// 楼中楼的正文自带 "回复 @某人 :",树里本来就挂在被回复者下面,重复且占地方
msg = msg.replace(/^\s*回复\s*@[^\s::]{1,30}\s*[::]\s*/, '');
// 先还原接口里自带的实体(" 之类),再统一转义,避免二次转义露出 " 字样
msg = esc(unent(msg));
/* 生成的 HTML 片段一律先抽成占位符,等所有正则都跑完再拼回来。
否则后一轮正则会在前一轮生成的 内部再命中一次,
把标签撬开、属性变成正文(表现为链接后面跟着一串 target="_blank")。
占位符的序号用字母编码:时间戳/BV号/网址这些 key 都带数字或 :/,
不可能在占位符内部命中,占位符也就不会被咬坏。 */
const parts = [];
const enc = (n) => String(n).split('').map((d) => 'abcdefghij'[+d]).join('');
const dec = (s) => +s.split('').map((c) => 'abcdefghij'.indexOf(c)).join('');
const keep = (html) => '\u0001' + enc(parts.push(html) - 1) + '\u0001';
const MARK = /\u0001([a-j]+)\u0001/g;
/* @某人 -> 主页链接。只认接口能解析出 mid 的(at_name_to_mid / members):
解析不到的就是普通文字,一律不染色 —— 染成蓝色却点不动,比不打眼更容易误导,
而且原生评论区对认不出的 @ 也是黑字。 */
msg = msg.replace(/(^|[\s>])(@[^\s@::,,。!?]{1,24})/g, (all, pre, at) => {
const mid = midMap[at.slice(1)];
if (!mid) return all;
return pre + keep('' + at + '');
});
/* 普通网址。字符类要挡住中文/全角标点/emoji/方括号:
评论里常写成 "https://b23.tv/xx,看这个视频"(逗号后没有空格),
只挡空白的话会把整句都吃进 href,点开就是 https://b23.tv/xx,看这个视频 这种 404。 */
const URL_RE = /(https?:\/\/[^\s<>"'\[\]\u0001\u3000-\u303f\u4e00-\u9fff\uff00-\uffef\ud800-\udfff]+)/g;
msg = msg.replace(URL_RE, (u) => {
// "https://b23.tv/xx," 这种把逗号句号也算进 href 的,标点留在链接外面
const tail = (u.match(/[.,;:!?。,、;:!?…]+$/) || [''])[0];
const url = tail ? u.slice(0, -tail.length) : u;
if (!url) return u;
return keep('' + url + '') + tail;
});
/* jump_url:接口单独标注的可跳转文本。只保留「本身就是一个地址或编号」的 key:
时间戳(1:36) / BV 号 / 裸网址(b23.tv/xxx)。
其余一律不加链接 —— B 站会给正文里的中文关键词也塞一条 search.bilibili.com 的跳转
(TD退订、不要点开我的头像、rickroll、月下待杜鹃不来…),但原生评论区里这些就是普通黑字。
照着接口全做出来就是「原生黑、树状蓝」,点了还是个搜索页,纯属误导。 */
const bvid = currentBvid();
Object.keys(jumps).forEach((key) => {
const j = jumps[key] || {};
let href = '';
const isUrl = /^https?:\/\/\S+$/i.test(key) || /^(?:[a-z0-9-]+\.)+[a-z]{2,}(?:\/\S*)?$/i.test(key);
// 兜底:带空白 / 超长 / 含中文全角 / 含 [表情] 的 key 肯定不是地址(B 站偶尔把整句当网址塞进来)
if (/\s/.test(key) || key.length > 120 ||
/[\u3000-\u303f\u4e00-\u9fff\uff00-\uffef]/.test(key) || /\[[^\]]*\]/.test(key)) return;
if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(key)) {
const sec = key.split(':').reduce((a, b) => a * 60 + Number(b), 0);
if (bvid) href = '//www.bilibili.com/video/' + bvid + '?t=' + sec;
} else if (/^BV[0-9A-Za-z]{6,}$/i.test(key)) {
href = '//www.bilibili.com/video/' + key;
} else if (isUrl) {
const pu = j.pc_url || '';
href = pu ? (/^\/\//.test(pu) ? 'https:' + pu : pu)
: (/^https?:\/\//i.test(key) ? key : 'https://' + key);
}
if (!href) return;
/* 双保险:任何「站内搜索」目标一律不做链接。
这类 href 只可能来自 B 站给中文关键词配的跳转(from_source=webcommentline_search),
原生评论区里那些词是黑字,做成蓝链就是「原生黑、树状蓝」。 */
if (/^https?:\/\/(?:[a-z0-9-]+\.)*search\.bilibili\.com\//i.test(href)) return;
const label = esc(key);
const safe = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/* 边界:时间戳两边必须是「非数字非冒号」,别让 1:36 命中 11:36;
其它(BV 号 / 网址)两边必须是「非字母数字」,别在长单词中间截一段出来变蓝。 */
const isTime = /^\d{1,2}(:\d{1,2}){1,2}$/.test(key);
const re = isTime
? new RegExp('(^|[^\\d:])' + safe + '(?![\\d:])', 'g')
: new RegExp('(^|[^0-9A-Za-z])' + safe + '(?![0-9A-Za-z])', 'g');
/* tl-jump 只是个标记(方便在 DOM 里区分"接口给的跳转"和"正文里的网址"),
颜色/下划线/光标全部由 a.tl-at 统一给,不要再单独写样式 */
msg = msg.replace(re, (all, pre) => pre + keep('' + label + ''));
});
// 表情放到最后替换:[xxx] -> img
Object.keys(emotes).forEach((key) => {
const em = emotes[key];
if (!em || !em.url) return;
let src = em.url.indexOf('//') === 0 ? 'https:' + em.url : em.url;
src = src.replace(/@[^/]*$/, ''); // 去掉 @32w_32h 之类裁剪后缀
const k = esc(key);
msg = msg.split(k).join(keep(
''
));
});
// 拼回真正的标签(一次扫描,不会二次替换)
return msg.replace(MARK, (m, tag) => parts[dec(tag)] || '');
}
/* 点赞 / 点踩共用同一枚拇指图标,踩就是把它上下翻转 180° */
function thumbSvg(down) {
const d = 'M2.6 10h3.4v6H2.6zM6 10l3-5.5V3a2 2 0 0 1 3 1.7V8h3.2a1.8 1.8 0 0 1 1.8 2.2l-1 4.2A1.8 1.8 0 0 1 14.2 16H6z';
const style = down ? ' style="transform:rotate(180deg)"' : '';
return '';
}
/* 大图里的左右箭头(用 SVG,别用字符:‹ › 在不同字体下粗细/位置差很多) */
function chevSvg(dir) {
const d = dir < 0 ? 'M12.5 4.5L7 10l5.5 5.5' : 'M7.5 4.5L13 10l-5.5 5.5';
return '';
}
/* 图片查看器。list = 同一条评论的全部图片地址,idx = 点开的是第几张。
* 多于一张时给左右箭头 +「2 / 5」计数;键盘 ← → 也能切,Esc 关闭。
* 首尾循环(和 B 站一致):在最后一张按右键回到第一张,不用先关再点。 */
function openViewer(list, idx) {
const urls = (list || []).filter(Boolean);
if (!urls.length) return;
let at = Math.min(Math.max(Number(idx) || 0, 0), urls.length - 1);
const many = urls.length > 1;
const v = el('div', 'tl-viewer');
const im = el('img');
im.src = urls[at];
im.alt = '';
im.referrerPolicy = 'no-referrer';
v.appendChild(im);
const count = el('div', 'tl-vv-count');
const prev = el('button', 'tl-vv-btn prev', chevSvg(-1));
const next = el('button', 'tl-vv-btn next', chevSvg(1));
const close = el('button', 'tl-vv-close', '×');
prev.type = 'button'; next.type = 'button'; close.type = 'button';
prev.title = '上一张(←)';
next.title = '下一张(→)';
close.title = '关闭(Esc)';
const show = function (i) {
at = ((i % urls.length) + urls.length) % urls.length; // 首尾循环
im.src = urls[at];
count.textContent = (at + 1) + ' / ' + urls.length;
};
let shut = null;
const stop = function (e) { e.stopPropagation(); };
if (many) {
count.textContent = (at + 1) + ' / ' + urls.length;
prev.onclick = function (e) { stop(e); show(at - 1); };
next.onclick = function (e) { stop(e); show(at + 1); };
v.appendChild(prev);
v.appendChild(next);
v.appendChild(count);
}
close.onclick = function (e) { stop(e); if (shut) shut(); };
v.appendChild(close);
v.onclick = function () { if (shut) shut(); };
/* 键盘:左右切换必须抢在页面自己的快捷键前面(B 站播放器拿 ← → 当快退/快进),
* 所以挂捕获阶段并 stopPropagation。关闭时一定要摘掉,否则关掉大图后
* 页面方向键会突然失灵(找不到监听却还在吃键)。 */
const onKey = function (e) {
const k = e.key;
if (k === 'Escape') { e.stopPropagation(); if (shut) shut(); return; }
if (!many) return;
if (k === 'ArrowLeft' || k === 'ArrowRight') {
e.preventDefault();
e.stopPropagation();
show(at + (k === 'ArrowLeft' ? -1 : 1));
}
};
shut = function () {
try { window.removeEventListener('keydown', onKey, true); } catch (e) { /* ignore */ }
try { v.remove(); } catch (e) { /* ignore */ }
};
document.body.appendChild(v);
try { window.addEventListener('keydown', onKey, true); } catch (e) { /* ignore */ }
}
/* ---------- 点赞 ---------- */
async function doLike(reply, btn) {
if (!getCookie('bili_jct')) { toast('请先登录'); return; }
const key = String(reply.rpid);
if (State.likeBusy.has(key)) return;
State.likeBusy.add(key);
const liked = btn.classList.toggle('liked');
try {
await post('/x/v2/reply/action', {
oid: State.oid, type: State.type, rpid: reply.rpid,
action: liked ? 1 : 0, csrf: getCookie('bili_jct'),
});
reply.like = Math.max(0, (reply.like || 0) + (liked ? 1 : -1));
btn.querySelector('span').textContent = reply.like ? fmtNum(reply.like) : '';
} catch (e) {
btn.classList.toggle('liked', !liked);
toast(e.message);
} finally {
State.likeBusy.delete(key);
}
}
/* ---------- 回复 ---------- */
function openEditor(host, reply, node) {
const old = host.querySelector('.tl-editor');
if (old) { old.remove(); return; }
const box = el('div', 'tl-editor');
const ta = el('textarea');
ta.placeholder = '回复 @' + (reply.member && reply.member.uname || '') + ':';
const bar = el('div', 'tl-editor-bar');
const cancel = el('button', 'tl-btn', '取消');
const send = el('button', 'tl-btn primary', '发布');
cancel.onclick = () => box.remove();
send.onclick = async () => {
const msg = ta.value.trim();
if (!msg) return;
if (!getCookie('bili_jct')) { toast('请先登录'); return; }
send.disabled = true;
try {
const root = reply.root && reply.root !== 0 ? reply.root : reply.rpid;
await post('/x/v2/reply/add', {
oid: State.oid, type: State.type, root: root, parent: reply.rpid,
message: msg, csrf: getCookie('bili_jct'),
});
toast('回复成功,刷新可见');
box.remove();
} catch (e) {
toast(e.message);
} finally {
send.disabled = false;
}
};
bar.appendChild(cancel);
bar.appendChild(send);
box.appendChild(ta);
box.appendChild(bar);
host.appendChild(box);
ta.focus();
}
/* ---------- 一栋楼 ---------- */
function renderThread(rootReply, isFirst) {
const thread = el('div', 'tl-thread');
const total = rootReply.rcount || 0;
// 主评论也当作一个普通节点,子回复加载后塞进它自己的 .tl-kid,
// 这样竖线才能从主评论头像底边一路垂下来,中间不断
const node = { reply: rootReply, children: [], depth: 0, key: String(rootReply.rpid) };
const wrap = renderNode(node, { isRoot: true });
thread.appendChild(wrap);
if (total <= 0) return thread;
// 折叠入口 / 加载楼中楼
const bar = el('div');
bar.style.cssText = 'padding-left:' + (CONF.indent + 2) + 'px;margin:0 0 6px';
wrap.appendChild(bar);
const btn = el('span', 'tl-folded', '▸ 展开 ' + fmtNum(total) + ' 条回复');
bar.appendChild(btn);
/* 底部镜像按钮:楼拉得很长时滚到底就能收,不用再爬回顶端。
* 收起态整条 display:none,不留占位。 */
const bar2 = el('div');
bar2.style.cssText = 'padding-left:' + (CONF.indent + 2) + 'px;margin:0 0 6px';
bar2.style.display = 'none';
const btn2 = el('span', 'tl-folded', '▴ 收起');
bar2.appendChild(btn2);
const load = async () => {
if (btn.dataset.busy === '1') return; // 自动展开和手点可能撞在同一栋楼上
btn.dataset.busy = '1';
btn.textContent = '正在加载…';
try {
const all = await slot(() => fetchReplies(rootReply.rpid));
if (!all.length) { bar.remove(); return; }
const tree = buildTree(all, rootReply.rpid);
// 楼中楼从第 1 层开始缩进(第 0 层是主评论)
const bump = (n) => { n.depth += 1; n.children.forEach(bump); };
tree.forEach(bump);
node.children = tree;
const box = el('div', 'tl-children');
box.id = 'tl-kids-' + rootReply.rpid;
tree.forEach((n) => box.appendChild(renderNode(n, { isRoot: false })));
/* 顺序:主评论 → 顶部条 → 楼中楼 → 底部条。
* 两头各留一个"收起",不管人滚到楼上还是楼下都能就近点。
* 注意不能 replace 掉按钮,否则展开一次就再也收不回去。 */
bar.after(box);
box.after(bar2);
bar2.style.display = '';
// 主评论此时才算"有子回复":补上它头像下的竖线和圆环
const ui = attachParentUI(node, wrap, wrap.querySelector(':scope > .tl-row'), 0);
/* 圆环和文字按钮共用一套状态:点圆环收起时,文字也要跟着变成"展开",
* 否则两个入口各说各话(一个收起一个还显示"收起")。 */
wrap._tlSync = (collapsed) => {
const n = fmtNum(all.length) + ' 条回复';
btn.textContent = '▸ 展开 ' + n;
btn2.textContent = '▴ 收起 ' + n;
btn.classList.toggle('is-open', !collapsed);
btn2.classList.toggle('is-open', !collapsed);
// 展开后顶部条让位:收起用主评论头像下的圆环,不必再多一个按钮
bar.style.display = collapsed ? '' : 'none';
// 收起时底部条抽掉,不然主评论下面会多出一条孤零零的"收起"
bar2.style.display = collapsed ? 'none' : '';
};
btn.onclick = () => swingFold(node, ui.btn, wrap);
/* 底部这颗收起要记住点击落点:收完把浮现的"展开"拉回光标下。
* 程序触发的 click(detail=0、clientY=0)不算,否则会被当成"点在视口顶部"
* 而把页面猛地滚到顶。 */
btn2.onclick = (e) => {
const y = e && e.detail > 0 && e.clientY > 0 ? e.clientY : null;
swingFold(node, ui.btn, wrap, y);
};
wrap._tlSync(false);
// 之前手动收起过这栋楼,重渲染后保持收起
if (State.collapsed.has(String(rootReply.rpid))) swingFold(node, ui.btn, wrap);
schedulePaint();
/* 楼中楼刚插进 DOM 时行高还没定型(头像图、表情、长图都会二次撑开),
* 当场量出来的竖线会短一大截,之后又没人再量。补两刀等布局稳定。 */
setTimeout(schedulePaint, 260);
setTimeout(schedulePaint, 1000);
} catch (e) {
btn.dataset.busy = '';
btn.textContent = '加载失败:' + e.message + '(点击重试)';
btn.onclick = load;
}
};
btn.onclick = load;
/* 前 2 栋楼一定展开;其余楼层里,回复数不超过 autoExpandMax 的小楼也直接展开,
* 免得整屏都是"展开 2 条回复"要一个个点。 */
const auto = isFirst || (total > 0 && total <= CONF.autoExpandMax);
if (auto) {
load();
} else {
/* 收起态的大楼:时间轴上补一颗圆环,和展开后的那颗是同一个元素,
* 加载完 attachParentUI 会复用它、只把提示语换掉,不会多出一颗。 */
attachPreloadNode(wrap, wrap.querySelector(':scope > .tl-row'),
CONF.avatar / 2, total, function () {
// 这栋楼若留在"历史收起"记录里,加载完会被自动收起,点了像没反应
State.collapsed.delete(String(rootReply.rpid));
load();
});
}
return thread;
}
/* 楼中楼请求闸门:自动展开会让一屏里同时有好几栋楼去拉接口,
* B 站对并发很敏感(412 风控),这里做个信号量,最多 fetchConcurrency 个在飞。 */
let _slots = 0;
const _slotQ = [];
function slot(fn) {
return new Promise((res, rej) => {
_slotQ.push({ fn: fn, res: res, rej: rej });
pumpSlots();
});
}
function pumpSlots() {
while (_slots < CONF.fetchConcurrency && _slotQ.length) {
const t = _slotQ.shift();
_slots++;
Promise.resolve().then(t.fn).then(t.res, t.rej).then(() => { _slots--; pumpSlots(); });
}
}
async function fetchReplies(rootRpid) {
const out = [];
const seen = new Set();
for (let pn = 1; pn <= CONF.maxReplyPages; pn++) {
const d = await api('/x/v2/reply/reply', {
type: State.type, oid: State.oid, root: rootRpid,
pn: pn, ps: CONF.replyPageSize, sort: 2,
});
const arr = ((d && d.replies) || []).filter((x) => {
const k = String(x.rpid);
if (seen.has(k)) return false;
seen.add(k);
return true;
});
if (!arr.length) break;
out.push.apply(out, arr);
const page = (d && d.page) || {};
if (arr.length < CONF.replyPageSize) break;
if (page.acount && out.length >= page.acount) break;
}
return out;
}
/* ---------- 主列表 ---------- */
function snapshot() {
const mode = State.sort === SORT_HOT ? 3 : 2;
SortCache[mode] = {
roots: State.roots, count: State.count, next: State.next,
isEnd: State.isEnd, top: Array.from(State.topRpids), upper: State.upperMid,
};
}
/* 12002 的备用方案:1=视频/番剧(稿件域)、33=课堂/课程、12=番剧(剧集域)。
* 只在主请求明确回 12002 时试。先拿同一个 oid 换三种类型;都不行再拿
* 地址里的 ep 号试(番剧页偶尔给的 oid 是季/剧集之外的编号),
* 命中一次就把 type / oid 记下来,后续都用它。 */
async function tryTypeAlt(mode, next) {
const tries = [];
[1, 33, 12].forEach(function (t) {
if (t !== State.type) tries.push({ type: t, oid: State.oid });
});
const ep = epFromUrl() || epFromState();
if (ep && ep !== State.oid) {
tries.push({ type: 1, oid: ep });
tries.push({ type: 33, oid: ep });
}
for (let i = 0; i < tries.length; i++) {
const t = tries[i];
try {
const d = await api('/x/v2/reply/main', {
type: t.type, oid: t.oid, mode: mode, next: next || 0, plat: 1,
});
// 空列表也算"查到了但没评论",不能拿它盖掉真正有内容的那一种
const has = d && ((d.replies && d.replies.length) || (d.cursor && d.cursor.all_count));
if (!has) continue;
log('评论接口 12002,改用 type=' + t.type + ' / oid=' + t.oid + ' 读到了评论');
State.type = t.type;
if (t.oid !== State.oid) State.oid = t.oid;
return d;
} catch (e) { /* 试下一组 */ }
}
return null;
}
async function loadPage(reset, force) {
const mode = State.sort === SORT_HOT ? 3 : 2;
if (reset) {
State.page = 1; State.roots = []; State.next = 0; State.isEnd = false;
const cached = !force && SortCache[mode];
if (cached) {
State.roots = cached.roots.slice();
State.count = cached.count;
State.next = cached.next;
State.isEnd = cached.isEnd;
State.topRpids = new Set(cached.top);
if (cached.upper) State.upperMid = cached.upper;
return;
}
}
// 用评论主接口:排序算法与 B 站原生评论区一致,并且会返回置顶数据
// mode: 3=最热, 2=最新
let d;
try {
d = await api('/x/v2/reply/main', {
type: State.type, oid: State.oid,
mode: mode,
next: State.next || 0,
plat: 1,
});
} catch (e) {
/* 12002 = "当前页面评论功能已关闭",它其实是**这个 type 下**查不到该 oid。
* 课程(33)/ 番剧(12)/ 视频(1)三类号会互相串,页面组件偶尔给的
* type 和实际对不上,拿同一个 oid 换一个 type 往往就通了。 */
const m = String((e && e.message) || e);
if (m.indexOf('12002') === -1) throw e;
const alt = await tryTypeAlt(mode, State.next || 0);
if (!alt) throw e;
d = alt;
}
let list = (d && d.replies) || [];
const cur = (d && d.cursor) || {};
if (cur.all_count) State.count = cur.all_count;
State.next = cur.next || 0;
State.isEnd = !!cur.is_end;
if (d && d.upper && d.upper.mid) State.upperMid = d.upper.mid;
// 置顶:UP 置顶 > 管理员置顶 > top_replies,与原生一样排在最前
const idOf = (x) => String((x && (x.rpid || x.rpid_str)) || '');
const tops = [];
const pushTop = (t) => {
if (!t || !idOf(t)) return;
if (!(t.content || t.member)) return;
if (tops.some((x) => idOf(x) === idOf(t))) return;
tops.push(t);
};
const top = (d && d.top) || {};
pushTop(top.upper);
pushTop(top.admin);
(d.top_replies || []).forEach((t) => {
if (t && Number(t.root || 0) === 0) pushTop(t); // 只认主评论级的置顶
});
if (tops.length) State.topRpids = new Set(tops.map(idOf));
if (tops.length && reset) {
list = tops.concat(list.filter((x) => !State.topRpids.has(idOf(x))));
}
if (reset) {
State.roots = list;
} else {
// 翻页时接口偶尔会重复吐同一条,去重后再拼,避免"同一评论出现两次"
const seen = new Set(State.roots.map(idOf));
list.forEach((x) => { if (!seen.has(idOf(x))) { seen.add(idOf(x)); State.roots.push(x); } });
}
snapshot();
}
async function renderAll(force) {
emptyStreak = 0;
listEl.innerHTML = '