,藏它本身不生效,
// 须上溯到块级容器 —— 即 ref/知乎优化1.js 的 `.closest('div').hide()` 等价做法。
// 注意:.Post-SideActions(左侧悬浮操作栏)只在 CSS 里整块 display:none,
// 此处不做上溯 —— 它是定位元素,占不到文档流,上溯只会误伤行容器。
var anchors = doc.querySelectorAll('a[aria-label="边栏锚点"]:not([' + MARK + '-toc])');
for (var j = 0; j < anchors.length; j++) {
var a = anchors[j];
a.setAttribute(MARK + '-toc', '1');
if (hideAncestor(a)) n++;
}
return n;
}
// 阅读上限随视口自适应(纯函数,可测):
// 宽屏放开到用户设定的上限,窄屏收成 88% 视口 —— 保证任何屏宽下左右留白都不过多。
// 下限 900px 是给「窗口被拖得很窄」兜底,避免读数被压到不可用;
// 未传上限(或传了非法值)时退回默认值,保证纯函数始终可用。
function readCap(vw, cap) {
if (typeof cap !== 'number' || !(cap > 0)) cap = READ_W;
if (!vw) return cap;
return Math.min(cap, Math.max(900, Math.round(vw * 0.88)));
}
// 文章页布局自适应(v1.4.0):不依赖任何类名,纯几何驱动。
//
// 为什么改成几何驱动:专栏页布局容器的类名「三代演进」(哈希 .css-* → .Post-Row-Content*
// → .Post-NormalMain*),写死任何一代都会在别的代上整条落空 —— 这正是此前几版
// 在真实页面「一条规则都没命中」的原因。故改为自正文根出发,沿祖先链逐级修正。
//
// 四件事:
// ① 解除窄宽度上限(正文列常写死 690px 上下;视口级约束保持不动);
// ② 双 auto 外边距居中 —— 对 block 父级与 flex 父级都成立(flex 下 auto 外边距
// 优先吸收剩余空间),这是唯一不关心父级 display 的居中写法。
// v1.3.2 只解宽度、从不设 margin,等于「放开了却没搬动」,是本轮修复的重点;
// ③ 清掉为侧栏留位的不对称内边距(一侧内距远大于另一侧时);
// ④ 隐藏行内「窄且几乎没有文字」的兄弟列 —— 目录 / 侧栏的占位列。
//
// 布局判据只能在运行时取。jsdom 无布局引擎(getBoundingClientRect 恒 0),
// 此时本函数自动降级为「只按计算样式做规则式修正」,仍然安全且可测。
function fixPostLayout(doc) {
if (!OPT.hideSidebar) return 0;
var win = doc.defaultView;
if (!win || typeof win.getComputedStyle !== 'function') return 0;
if (!isPostDoc(doc, win)) return 0; // 问题页/首页等绝不按文章页处理(三处共用判据)
var root = pickPostRoot(doc);
if (!root) return 0;
var capW = readCap(win.innerWidth, widthCap(OPT)); // 上限取自面板设置,窄屏再按 88vw 收
var n = 0, el = root, chain = [], i, cs, pcs, mw, p, cw, pw, iw, isNarrow, isRowFlex;
// 链深 9:起点下移到文本根后多了一层(.ztext → .Post-RichTextContainer → …),
// 少一层就可能够不到行容器,居中/解限会在最外一层落空。
for (i = 0; i < 9 && el && el.tagName !== 'BODY' && el.tagName !== 'HTML'; i++) {
chain.push(el);
el = el.parentNode;
}
for (i = 0; i < chain.length; i++) {
el = chain[i];
cs = null; pcs = null;
try { cs = win.getComputedStyle(el); } catch (e) {}
p = el.parentNode;
if (p && p.tagName !== 'BODY' && p.tagName !== 'HTML') {
try { pcs = win.getComputedStyle(p); } catch (e) {}
}
// ① 解除窄宽度上限:正文列常被写死 690px 上下。
// 比阅读上限还窄的 max-width 一律解除(可能是知乎的 690,也可能是旧版脚本自己
// v1.3.2 写死的 1000);比阅读上限更宽的约束(视口级)保持不动,避免拉变形页头页脚。
if (cs && cs.maxWidth && cs.maxWidth !== 'none' && /px$/.test(cs.maxWidth)) {
mw = parseFloat(cs.maxWidth);
if (mw > 0 && mw < capW) { el.style.setProperty('max-width', 'none', 'important'); n++; }
}
// ② 加宽(本轮重点):v1.4.0 只「解上限」不「撑宽度」,而正文列的窄往往来自**
// 自身写死的宽度**(无论是 CSS 类给的,还是内联 style 给的 690px —— 在计算样式里
// 读到的就是 690px),于是居中生效了、左右却各留一大片空白。用户反馈正是这个形态。
// 判据(任一成立即视为「被写死的窄列」):
// · 计算宽度明显窄于父级可用宽度(CSS 类写死的情形)
// · 内联宽度是 px 且小于阅读上限(第一代脚本面对的情形)
// 动作:
// · 父级是 row 方向 flex 容器 → flex-grow 增长(flex-basis 写死的宽度会被填平)
// · 其余(block 等) → width: 100%
// 两条都同时给 box-sizing:border-box,否则内边距会叠加把宽列顶出容器产生横向滚动。
// 注意不能写 width:auto —— flex 行内 auto 会缩成内容宽度,越改越窄。
cw = pxOf(cs && cs.width);
pw = pxOf(pcs && pcs.width);
iw = pxOf(el.style && el.style.width);
isNarrow = (cw > 0 && pw > 0 && cw < pw - 24) || (iw > 0 && iw < capW);
if (isNarrow) {
isRowFlex = !!(pcs && /^(inline-)?flex$/.test(pcs.display) &&
/^row/.test(pcs.flexDirection || 'row'));
if (isRowFlex) {
if (!(parseFloat(cs && cs.flexGrow) > 0)) {
el.style.setProperty('flex-grow', '1', 'important');
n++;
}
} else {
el.style.setProperty('width', '100%', 'important');
n++;
}
el.style.setProperty('box-sizing', 'border-box', 'important');
el.style.setProperty('max-width', capW + 'px', 'important');
el.style.setProperty('margin-left', 'auto', 'important');
el.style.setProperty('margin-right', 'auto', 'important');
}
// ③ 居中:双 auto 外边距(block / flex 父级通吃)
el.style.setProperty('margin-left', 'auto', 'important');
el.style.setProperty('margin-right', 'auto', 'important');
// ④ 清掉为侧栏留位的不对称内边距
if (cs) {
var pl = parseFloat(cs.paddingLeft) || 0, pr = parseFloat(cs.paddingRight) || 0;
if (pl > pr + 40) { el.style.setProperty('padding-left', '0', 'important'); n++; }
if (pr > pl + 40) { el.style.setProperty('padding-right', '0', 'important'); n++; }
}
}
// ⑤ 链上最外层(最接近 body 的那层)收阅读上限:解除宽度后避免在超宽屏上撑到满屏
var outer = chain[chain.length - 1];
if (outer && outer.style) {
outer.style.setProperty('max-width', capW + 'px', 'important');
outer.style.setProperty('margin-left', 'auto', 'important');
outer.style.setProperty('margin-right', 'auto', 'important');
n++;
}
// ⑥ 隐藏行内占位列
n += hideNarrowCols(win, chain);
return n;
}
// 计算样式里的长度取 px 数值;非 px(auto / 100% / '' / none / fit-content…)一律返回 0。
function pxOf(v) {
return (v && /^-?\d+(\.\d+)?px$/.test(v)) ? parseFloat(v) : 0;
}
// 行走行列清理:以「元素实测宽度 > 0」作为「环境有布局引擎」的开关 ——
// jsdom 无布局引擎、宽度恒 0,若只判 w < 320 会把所有兄弟列误判成窄列。
function hideNarrowCols(win, chain) {
var n = 0, i, k;
for (i = 0; i < chain.length; i++) {
var p = chain[i].parentNode;
if (!p || !p.children || p.children.length < 2) continue;
var pcs;
try { pcs = win.getComputedStyle(p); } catch (e) { continue; }
if (!pcs || (pcs.display !== 'flex' && pcs.display !== 'grid' && pcs.display !== 'inline-flex')) continue;
for (k = 0; k < p.children.length; k++) {
var sib = p.children[k];
if (sib === chain[i] || !sib.getBoundingClientRect) continue;
if (sib.getAttribute(MARK + '-col')) continue;
var w = sib.getBoundingClientRect().width;
var txt = (sib.textContent || '').replace(/\s+/g, '').length;
// 「窄」+「几乎没有正文文字」两条同时成立才动手,避免误伤正文列
if (w > 0 && w < 320 && txt < 100) {
sib.setAttribute(MARK + '-col', '1');
sib.style.setProperty('display', 'none', 'important');
n++;
}
}
}
return n;
}
// ======================================================================
// 文章页布局诊断(临时,v1.4.0 引入,定位完成后移除)
//
// 知乎对未登录的自动化浏览器返回反爬空壳(文章页 body 仅 173 字节,
// zhuanlan 直连亦 403),真实 DOM 取不到,只能靠推断 —— 这是此前几轮
// 「改了却不生效」的根本障碍。故本版在「自愈后仍判定未居中」时,把关键
// 几何与结构信息以细横幅暴露在页顶,让真实 DOM 结构能随截图回传。
//
// 横幅自带验收信号:页面没有横幅 = 布局已判定正常。
// ======================================================================
// 纯函数(可测):正文列是否明显偏离居中位置。null = 正常或无法判定。
function layoutVerdict(w, left, viewport) {
if (!w || !viewport || w >= viewport) return null;
return Math.abs(left - (viewport - w) / 2) > 40 ? 1 : null;
}
var DIAG_ID = 'zhx-diag';
function dropDiag(doc) {
var d = doc.getElementById(DIAG_ID);
if (d && d.parentNode) d.parentNode.removeChild(d);
}
function runDiag(doc) {
if (!OPT.hideSidebar) { dropDiag(doc); return; }
if (!isPostDoc(doc)) { dropDiag(doc); return; } // 只在文章页诊断;问题页等拆除残留横幅
var win = doc.defaultView;
var root = pickPostRoot(doc);
if (!win || !root || !root.getBoundingClientRect) { dropDiag(doc); return; }
var r = root.getBoundingClientRect();
if (!layoutVerdict(r.width, r.left, win.innerWidth)) { dropDiag(doc); return; }
var f = function (s) { return doc.querySelector(s) ? '1' : '0'; };
var marks = 'Cat' + f('.Catalog') + ' PNM' + f('.Post-NormalMain') +
' PC' + f('.Post-content') + ' PRC' + f('.Post-Row-Content') +
' SAct' + f('.Post-SideActions') + ' ztext' + f('.ztext');
var chain = [], el = root, i;
for (i = 0; i < 6 && el && el.tagName !== 'BODY'; i++) {
var w = Math.round(el.getBoundingClientRect().width);
var cls = String(el.className || '').split(/\s+/)[0] || '-';
chain.push(el.tagName.toLowerCase() + '.' + cls + '[' + w + ']');
el = el.parentNode;
}
var line1 = 'zhx ' + VERSION + ' | 视口' + win.innerWidth +
' 正文宽' + Math.round(r.width) + ' 左' + Math.round(r.left) +
' 应为' + Math.round((win.innerWidth - r.width) / 2) + ' | ' + marks;
var line2 = '祖先: ' + chain.join(' > ');
var d = doc.getElementById(DIAG_ID);
if (!d) {
d = doc.createElement('div');
d.id = DIAG_ID;
d.setAttribute('style', 'position:fixed;left:0;right:0;top:0;z-index:2147483003;' +
'background:rgba(13,17,23,.94);color:#e6edf3;border-bottom:1px solid #30363d;' +
'font:11px/16px ui-monospace,Consolas,monospace;padding:3px 8px;' +
'white-space:nowrap;overflow-x:auto;');
var la = doc.createElement('div'); la.textContent = line1;
var lb = doc.createElement('div'); lb.textContent = line2;
d.appendChild(la); d.appendChild(lb);
(doc.body || doc.documentElement).appendChild(d);
} else {
if (d.children[0]) d.children[0].textContent = line1;
if (d.children[1]) d.children[1].textContent = line2;
}
}
// 节流:Watcher 每次心跳都会触发 dynRun,诊断只需在布局稳定后判定一次
var diagPending = false;
function scheduleDiag(doc) {
if (diagPending) return;
diagPending = true;
setTimeout(function () { diagPending = false; runDiag(doc); }, 1500);
}
function toggleNight(on) {
document.documentElement.setAttribute('data-theme', on ? 'dark' : 'light');
watchNight(on);
}
// ======================================================================
// L6 UI 层 · 设置面板(ghb 设计系统,zhx- 前缀,懒挂载)+ GM 菜单 + Toast
// ======================================================================
var UI_CSS = `
.zhx-scope {
--zhx-bg:#0d1117; --zhx-bg-2:#161b22; --zhx-bg-3:#21262d;
--zhx-bd:#30363d; --zhx-bd-2:#21262d;
--zhx-fg:#e6edf3; --zhx-fg-2:#8b949e;
--zhx-accent:#2da44e; --zhx-accent-2:#1a7f37; --zhx-accent-fg:#ffffff;
--zhx-shadow:0 16px 44px rgba(0,0,0,.5);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
color:var(--zhx-fg); font-size:13px; line-height:1.5;
}
#zhx-overlay { position:fixed; top:0; right:0; bottom:0; left:0; z-index:2147483001; background:rgba(0,0,0,.5); opacity:0; visibility:hidden; pointer-events:none; transition:opacity .2s, visibility .2s; }
#zhx-overlay.zhx-open { opacity:1; visibility:visible; pointer-events:auto; }
#zhx-panel { position:fixed; left:50%; top:50%; z-index:2147483002; width:460px; max-width:calc(100vw - 32px); max-height:84vh;
background:var(--zhx-bg); border:1px solid var(--zhx-bd); border-radius:14px; box-shadow:var(--zhx-shadow);
display:flex; flex-direction:column; overflow:hidden; opacity:0; visibility:hidden; transform:translate(-50%,-46%) scale(.97); pointer-events:none;
transition:opacity .22s, transform .22s cubic-bezier(.4,0,.2,1), visibility .22s; }
#zhx-panel.zhx-open { opacity:1; visibility:visible; transform:translate(-50%,-50%) scale(1); pointer-events:auto; }
.zhx-head { display:flex; align-items:center; gap:10px; padding:14px 16px; border-bottom:1px solid var(--zhx-bd-2); flex:none; }
.zhx-brand { width:28px; height:28px; display:inline-flex; align-items:center; justify-content:center; border-radius:8px; background:var(--zhx-accent); color:var(--zhx-accent-fg); flex:none; }
.zhx-brand svg { width:16px; height:16px; }
.zhx-head h2 { margin:0; font-size:15px; font-weight:600; color:var(--zhx-fg); }
.zhx-ver { font-size:11px; color:var(--zhx-fg-2); border:1px solid var(--zhx-bd); border-radius:999px; padding:1px 7px; }
.zhx-icon-btn { margin-left:auto; width:28px; height:28px; display:flex; align-items:center; justify-content:center; border:none; border-radius:6px;
background:transparent; color:var(--zhx-fg-2); cursor:pointer; font-size:16px; transition:background .15s, color .15s; }
.zhx-icon-btn:hover { background:var(--zhx-bg-3); color:var(--zhx-fg); }
#zhx-panel :focus-visible, #zhx-overlay:focus-visible { outline:2px solid var(--zhx-accent); outline-offset:2px; }
@media (prefers-color-scheme: light) {
.zhx-scope { --zhx-bg:#f7faf8; --zhx-bg-2:#ffffff; --zhx-bg-3:#eef4f1; --zhx-bd:#d5e0da; --zhx-bd-2:#e4ece7; --zhx-fg:#101820; --zhx-fg-2:#4d5f68; --zhx-accent:#18794e; --zhx-accent-2:#11623e; --zhx-accent-fg:#ffffff; --zhx-shadow:0 16px 44px rgba(16,24,32,.16); }
}
@media (prefers-reduced-motion: reduce) { #zhx-overlay,#zhx-panel,.zhx-switch i,.zhx-switch i::after,.zhx-toast,.zhx-range::-webkit-slider-thumb{animation-duration:.01ms !important;transition-duration:.01ms !important;} }
.zhx-body { flex:1; overflow-y:auto; min-height:180px; padding:6px 0 12px; }
.zhx-body::-webkit-scrollbar { width:8px; }
.zhx-body::-webkit-scrollbar-thumb { background:var(--zhx-bd); border-radius:4px; }
.zhx-group-title { padding:12px 16px 4px; font-size:11px; font-weight:600; letter-spacing:.05em; color:var(--zhx-fg-2); text-transform:uppercase; }
.zhx-row { display:flex; align-items:center; gap:10px; padding:8px 16px; transition:background .12s; }
.zhx-row:hover { background:var(--zhx-bg-2); }
.zhx-row-text { flex:1; min-width:0; }
.zhx-row-label { font-size:13px; color:var(--zhx-fg); }
.zhx-row-tip { font-size:11px; color:var(--zhx-fg-2); margin-top:1px; }
.zhx-switch { position:relative; width:40px; height:22px; flex:none; cursor:pointer; }
.zhx-switch input { position:absolute; top:0; left:0; width:100%; height:100%; margin:0; opacity:0; cursor:pointer; z-index:1; }
.zhx-switch i { display:block; width:40px; height:22px; border-radius:11px; background:var(--zhx-bd); transition:background .22s; position:relative; }
.zhx-switch i::after { content:''; position:absolute; top:3px; left:3px; width:16px; height:16px; border-radius:50%; background:#fff;
transition:transform .22s cubic-bezier(.4,0,.2,1); }
.zhx-switch input:checked + i { background:var(--zhx-accent); }
.zhx-switch input:checked + i::after { transform:translateX(18px); }
/* —— 数值行(滑块):设置面板里唯一非开关控件 —— */
.zhx-row-stack { flex-direction:column; align-items:stretch; gap:9px; padding-bottom:12px; }
.zhx-row-stack .zhx-row-label { display:flex; align-items:center; gap:8px; }
.zhx-val { margin-left:auto; flex:none; padding:1px 8px; border-radius:999px; font-size:11px; font-weight:600;
color:var(--zhx-accent); background:rgba(45,164,78,.12); border:1px solid rgba(45,164,78,.35);
font-variant-numeric:tabular-nums; transition:color .15s, background .15s, border-color .15s; }
.zhx-range { -webkit-appearance:none; appearance:none; display:block; width:100%; height:4px; margin:0; padding:0;
border-radius:2px; outline:none; cursor:pointer;
background:linear-gradient(to right, var(--zhx-accent) 0 var(--zhx-fill,0%), var(--zhx-bd) var(--zhx-fill,0%) 100%); }
.zhx-range::-webkit-slider-thumb { -webkit-appearance:none; appearance:none; width:14px; height:14px; border-radius:50%;
background:var(--zhx-accent); border:2px solid var(--zhx-bg); box-shadow:0 0 0 1px var(--zhx-bd);
transition:transform .15s; }
.zhx-range:hover::-webkit-slider-thumb { transform:scale(1.12); }
.zhx-range:focus-visible { box-shadow:0 0 0 3px rgba(45,164,78,.28); }
.zhx-range::-moz-range-thumb { width:12px; height:12px; border-radius:50%; background:var(--zhx-accent);
border:2px solid var(--zhx-bg); box-shadow:0 0 0 1px var(--zhx-bd); cursor:pointer; }
.zhx-scale { display:flex; justify-content:space-between; font-size:11px; color:var(--zhx-fg-2); font-variant-numeric:tabular-nums; }
.zhx-dep { display:none; margin-top:2px; font-size:11px; color:#d29922; }
.zhx-row.zhx-off .zhx-dep { display:block; }
.zhx-row.zhx-off .zhx-range { opacity:.35; pointer-events:none; }
.zhx-row.zhx-off .zhx-val { color:var(--zhx-fg-2); background:transparent; border-color:var(--zhx-bd); }
.zhx-foot { padding:8px 16px; border-top:1px solid var(--zhx-bd-2); font-size:11px; color:var(--zhx-fg-2); flex:none; }
#zhx-toasts { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); z-index:2147483004; display:flex;
flex-direction:column; gap:8px; align-items:center; pointer-events:none; }
.zhx-toast { padding:9px 14px; border-radius:8px; font-family:inherit; font-size:13px; color:#fff;
background:#1f6feb; box-shadow:0 6px 20px rgba(0,0,0,.35); opacity:0; transform:translateY(12px);
transition:opacity .22s, transform .22s; }
.zhx-toast.zhx-show { opacity:1; transform:none; }
.zhx-toast.zhx-ok { background:var(--zhx-accent); }
`;
var els = {}; // 懒挂载的 DOM 引用
// Toast 容器启动即挂载(不可见空容器):菜单切换开关时无需先打开面板也有反馈
function ensureToasts() {
if (document.getElementById('zhx-toasts')) return;
var toasts = document.createElement('div');
toasts.id = 'zhx-toasts';
toasts.setAttribute('role', 'status');
toasts.setAttribute('aria-live', 'polite');
toasts.setAttribute('aria-atomic', 'false');
document.body.appendChild(toasts);
}
function mountUI() {
if (els.panel) return;
var style = document.createElement('style');
style.textContent = UI_CSS;
document.head.appendChild(style);
var overlay = document.createElement('div');
overlay.id = 'zhx-overlay';
var panel = document.createElement('div');
panel.id = 'zhx-panel';
panel.className = 'zhx-scope';
panel.setAttribute('role', 'dialog');
panel.setAttribute('aria-modal', 'true');
panel.setAttribute('aria-label', '知乎阅读增强助手设置');
panel.setAttribute('aria-hidden', 'true');
panel.tabIndex = -1;
panel.innerHTML =
'' + SCRIPT_ICON + '
知乎阅读增强
v' + VERSION + '' +
'' +
'' +
'';
var body = panel.querySelector('.zhx-body');
GROUPS.forEach(function (g) {
var gt = document.createElement('div');
gt.className = 'zhx-group-title';
gt.textContent = g;
body.appendChild(gt);
Object.keys(OPT_DEFS).forEach(function (name) {
var def = OPT_DEFS[name];
if (def.group !== g) return;
if (def.type === 'range') { mountRangeRow(body, name, def); return; }
var row = document.createElement('div');
row.className = 'zhx-row';
row.innerHTML =
'' +
'';
row.querySelector('.zhx-row-label').textContent = def.label;
row.querySelector('.zhx-row-tip').textContent = def.tip;
var cb = row.querySelector('input');
cb.checked = !!OPT[name];
cb.addEventListener('change', function () { applyOpt(name, cb.checked); });
body.appendChild(row);
});
});
ensureToasts();
document.body.appendChild(overlay);
document.body.appendChild(panel);
els = { overlay: overlay, panel: panel };
overlay.addEventListener('click', closePanel);
panel.querySelector('.zhx-icon-btn').addEventListener('click', closePanel);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && els.panel.classList.contains('zhx-open')) closePanel();
});
}
// 数值行(滑块):拖动中只改内存做即时预览,松手(change)才落盘 —— 高频 input 不写存储、
// 不弹提示;拖动期间面板上就能看到宽度变化,符合「改动即时生效」的一致体验。
function mountRangeRow(body, name, def) {
var row = document.createElement('div');
row.className = 'zhx-row zhx-row-stack';
row.setAttribute('data-zhx-opt', name);
row.innerHTML =
'' +
'' +
'
';
row.querySelector('.zhx-name').textContent = def.label;
row.querySelector('.zhx-row-tip').textContent = def.tip;
if (def.dep && OPT_DEFS[def.dep]) {
row.querySelector('.zhx-dep').textContent = '需先开启「' + OPT_DEFS[def.dep].label + '」后生效';
}
var unit = def.unit || '';
var scale = row.querySelectorAll('.zhx-scale span');
scale[0].textContent = def.min + unit;
scale[1].textContent = def.max + unit;
var r = row.querySelector('.zhx-range');
r.min = def.min;
r.max = def.max;
r.step = def.step;
r.value = OPT[name];
r.setAttribute('aria-label', def.label);
function paint(v) {
row.querySelector('.zhx-val').textContent = v + unit;
r.style.setProperty('--zhx-fill', Math.round((v - def.min) / (def.max - def.min) * 100) + '%');
}
paint(OPT[name]);
row.classList.toggle('zhx-off', !!(def.dep && !OPT[def.dep]));
r.addEventListener('input', function () {
var v = clampRange(r.value, def);
OPT[name] = v; // 仅内存预览,不写存储
paint(v);
rebuildStyle();
fixPostLayout(document);
});
r.addEventListener('change', function () {
var v = clampRange(r.value, def);
r.value = v;
applyOpt(name, v); // 落盘走唯一应用路径
toast(def.label + '已设为 ' + v + unit, 'ok');
});
body.appendChild(row);
}
// 依赖开关变化时同步数值行的可用态(置灰 + 显示依赖提示)
function refreshRangeRows() {
if (!els.panel) return;
var rows = els.panel.querySelectorAll('.zhx-row-stack');
for (var i = 0; i < rows.length; i++) {
var def = OPT_DEFS[rows[i].getAttribute('data-zhx-opt')];
if (def && def.dep) rows[i].classList.toggle('zhx-off', !OPT[def.dep]);
}
}
function openPanel() {
mountUI();
els.overlay.classList.add('zhx-open');
els.panel.classList.add('zhx-open');
els.panel.setAttribute('aria-hidden', 'false');
els.panel.focus();
}
function closePanel() {
els.overlay.classList.remove('zhx-open');
els.panel.classList.remove('zhx-open');
els.panel.setAttribute('aria-hidden', 'true');
}
function toast(msg, kind) {
if (!document.body) return;
ensureToasts(); // 自给自足:无论面板/启动时序如何,反馈都可达
var box = document.getElementById('zhx-toasts');
if (!box) return;
var t = document.createElement('div');
t.className = 'zhx-toast' + (kind ? ' zhx-' + kind : '');
t.textContent = msg;
box.appendChild(t);
requestAnimationFrame(function () { t.classList.add('zhx-show'); });
setTimeout(function () {
t.classList.remove('zhx-show');
setTimeout(function () { t.remove(); }, 250);
}, 2200);
}
// 开关 / 数值变更的唯一应用路径:归一 → 存储 → 对应生效手段 → 菜单与面板状态刷新
function applyOpt(name, value) {
var def = OPT_DEFS[name];
var v = saveOpt(name, value); // 归一后的真实值(数值项可能被夹进区间)
if (name === 'nightMode') { toggleNight(v); registerMenu(); return; }
if (name === 'autoHideHeader') { watchScroll(v); rebuildStyle(); return; }
if (def) rebuildStyle();
if (name === 'directLink') applyLink(document);
if (name === 'timeTop') applyTime(document);
if (name === 'picOriginal') applyImg(document);
if (name === 'gifPlay' && v) playGifs(document);
if (name === 'hideSidebar') {
cleanSticky(document);
fixPostLayout(document);
scheduleDiag(document);
refreshRangeRows(); // 依赖它的数值行同步置灰 / 恢复
// 关闭净化时若启动标记还在(极早期切换),立即解除,避免页脚被长期遮挡
if (!v) bootUnmark();
}
if (name === 'readWidth') { fixPostLayout(document); scheduleDiag(document); }
}
// 全脚本唯一的样式表元素。改写一律原地换 textContent —— 不删不留空档,
// 否则会出现「样式表空一帧」(宽度回落到站点默认再变回来,正是要治的那种闪)。
var styleEl = null;
// 样式表归位。「同权重同选择器,后出现者胜」—— document-start 时 可能还不存在,
// 只能先挂到 documentElement(位于 head 之前,等于排在站点全部样式之前而落败),
// 故 一出现就移入其末尾。幂等,可随任意 DOM 变更重复调用(只做一次 parentNode 比较)。
function placeStyle() {
if (!styleEl) return;
var t = document.head || document.documentElement;
if (t && styleEl.parentNode !== t) t.appendChild(styleEl);
}
function rebuildStyle() {
if (styleEl) styleEl.textContent = buildCSS(OPT);
}
var menuIds = []; // 已注册菜单句柄,重注册前先摘除,避免菜单项堆积
function registerMenu() {
if (typeof GM_unregisterMenuCommand === 'function') {
for (var i = 0; i < menuIds.length; i++) {
try { GM_unregisterMenuCommand(menuIds[i]); } catch (e) { /* 忽略 */ }
}
}
menuIds = [];
menuIds.push(GM_registerMenuCommand('⚙ 设置面板', openPanel));
menuIds.push(GM_registerMenuCommand((OPT.nightMode ? '🌙' : '☀️') + ' 夜间模式:' + (OPT.nightMode ? '开' : '关'), function () {
applyOpt('nightMode', !OPT.nightMode);
toast(OPT.nightMode ? '夜间模式已开启' : '夜间模式已关闭', 'ok');
}));
}
// ======================================================================
// L7 Watcher 层 · 唯一的监听者(MutationObserver / scroll / data-theme 守护)
// ======================================================================
function debounce(fn, wait) {
var timer = null;
return function () {
if (timer) return;
timer = setTimeout(function () { timer = null; fn(); }, wait);
};
}
function dynRun() {
applyLink(document);
applyTime(document);
applyImg(document);
cleanSticky(document);
fixPostLayout(document);
scheduleDiag(document);
}
var observer = null;
var runSoon = debounce(dynRun, 200);
var syncRoot = null; // 已做过同步校正的正文根,用来识别「换了一篇文章」
var syncDone = false;
// 首帧同步校正(v1.5.1):
// 「打开文章闪一下、宽度由小变大」的成因是**时序**,不是 CSS 过渡 —— 页面先按站点默认的
// 窄列绘制了一帧到若干帧,随后才轮到本脚本改写宽度。要消掉它只能赶在**绘制之前**落地:
// MutationObserver 的回调执行于 DOM 变更之后、渲染之前,在回调里同步改写,中间态就根本
// 进不了绘制队列。
// 又因为知乎是 SPA,切页会重建正文 DOM,所以判据不是「第一次」而是「每换一个正文根都
// 同步一次」:旧根被移除(isConnected 转 false)即视为换篇,重新接管。
// 稳态下本函数只做一次 O(1) 的 isConnected 判定,查询开销为零。
function syncPass() {
if (syncDone && syncRoot && syncRoot.isConnected) return false; // 仍是同一篇,交给 debounce
if (!isPostDoc(document)) return false; // 问题页等:评论区的 .ztext 不构成「正文根出现」
var root = document.querySelector(POST_BODY_SEL);
if (!root || root === syncRoot) return false;
syncRoot = root;
syncDone = true;
dynRun(); // 同步完成几何校正(内联 !important,同帧生效,不入绘制队列)
bootUnmark(); // 同帧解除首屏遮蔽:用户第一眼看到的就是最终宽度
compensatePass(); // 正文随后异步再设宽的情形,由两次有界补偿兜住
return true;
}
// 首屏补偿:正文就绪后再补两次校正,覆盖「首帧只拿到骨架、真内容稍后替换」的情形。
// 有界(两次固定延时)而非轮询;非文章页不触发(选择器不命中即直接返回)。
function compensatePass() {
setTimeout(function () { if (document.querySelector(POST_BODY_SEL)) dynRun(); }, 150);
setTimeout(function () { if (document.querySelector(POST_BODY_SEL)) dynRun(); }, 600);
}
function startObserver() {
if (observer) return;
observer = new MutationObserver(function () {
placeStyle(); // 幂等: 一出现就把样式表排到站点样式之后
if (syncPass()) return; // 正文根出现 / 更换 → 同步校正,不进 debounce
runSoon();
});
// 观察 document 而非 body:document-start 时 body 可能尚未创建,只观察 body 会漏掉
// 「body 被插入」那一刻;从根上观察,树里的一切都覆盖得到。
observer.observe(document, { childList: true, subtree: true });
}
// scroll 监听(autoHideHeader 专用,随开关挂载/卸载)
var scrollHandler = null, lastY = 0;
function watchScroll(on) {
if (on && !scrollHandler) {
var tick = false;
scrollHandler = function () {
if (tick) return;
tick = true;
setTimeout(function () {
tick = false;
var header = document.querySelector('header.AppHeader');
if (!header) return;
var y = window.scrollY || 0;
if (y > lastY && y > 80) header.classList.add('is-hidden');
else header.classList.remove('is-hidden');
lastY = y;
}, 120);
};
window.addEventListener('scroll', scrollHandler, { passive: true });
} else if (!on && scrollHandler) {
window.removeEventListener('scroll', scrollHandler);
scrollHandler = null;
var header = document.querySelector('header.AppHeader');
if (header) header.classList.remove('is-hidden');
}
}
// data-theme 守护:夜间模式开启时,站点重置主题则立即写回
var nightGuard = null;
function watchNight(on) {
if (on && !nightGuard) {
nightGuard = new MutationObserver(function () {
if (OPT.nightMode && document.documentElement.getAttribute('data-theme') !== 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
}
});
nightGuard.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
} else if (!on && nightGuard) {
nightGuard.disconnect();
nightGuard = null;
}
}
// GIF 自动播放:第一次用户点击后触发一次(capture 一次性监听)
function watchGifTrigger() {
var handler = function () {
document.removeEventListener('click', handler, true);
if (OPT.gifPlay) setTimeout(function () { playGifs(document); }, 300);
};
document.addEventListener('click', handler, true);
}
// 首屏防闪现:document-start 先打标记藏住页脚(v1.5.1 起还包含文章页正文容器),
// 主内容出现后立即解除。知乎 SPA 在正文水合前会先渲染页脚(帮助/举报/备案),
// 表现为「打开时闪一下」;文章页正文容器则会在宽度校正落地前闪一下窄列。
// 两者共用一个标记与一个解除时机:校正与解除同帧完成,中间态不进绘制队列。
var bootUnmarker = null;
var bootMarked = false;
// 解除首屏遮蔽(幂等)。可被首帧同步路径随时调用 —— 这正是「校正与解除同帧」的落点。
function bootUnmark() {
if (!bootMarked) return;
bootMarked = false;
document.documentElement.removeAttribute('data-zhx-booting');
if (bootUnmarker) { bootUnmarker.disconnect(); bootUnmarker = null; }
}
// 首屏遮蔽的解除判据。
// 文章页刻意「更严」:必须等正文实体(POST_BODY_SEL)出现,而不是容器一有子节点就算就绪 ——
// 骨架阶段就放行会让站点默认的窄列露出来,正是本版要治的那个闪。
// 非文章页(首页/问题页/搜索页)不涉及宽度校正,主内容一出现即解除,不必等正文实体。
function bootReady() {
if (document.querySelector(POST_BODY_SEL)) return true;
var pc = document.querySelector('.Post-content');
if (pc) {
// 文章页的判据刻意比「容器有子节点」更严:骨架/占位先到时若放行,站点默认的窄列
// 就露出来了。但也不能只认某几个类名(正文容器可能改名),故取两条充分条件的**或**:
// 正文实体命中(最快最准),或容器里已有成段正文(>40 字 —— 空骨架不可能有)。
// 两条都没命中就继续等,由 4 秒兜底保证不会长期空白。
return (pc.textContent || '').replace(/\s+/g, '').length > 40;
}
var el = document.querySelector('.Topstory-container, .Question-mainColumn, .Search-container, .App-main > *');
return !!(el && el.children.length > 0);
}
function watchBootMark() {
if (!OPT.hideSidebar) return; // 与侧栏净化同组:未开启则不介入
bootMarked = true;
document.documentElement.setAttribute('data-zhx-booting', '1');
// 主路径:主内容一出现就解除(MutationObserver,不做轮询)
bootUnmarker = new MutationObserver(function () { if (bootReady()) bootUnmark(); });
bootUnmarker.observe(document.documentElement, { childList: true, subtree: true });
// 兜底:最多观察 4 秒,无论锚点是否命中都解除,绝不长期遮挡页脚
setTimeout(bootUnmark, 4000);
if (bootReady()) bootUnmark();
}
// ======================================================================
// 启动 · document-start 注入样式防闪烁,DOMContentLoaded 后挂监听
// ======================================================================
function boot() {
loadOpts();
styleEl = document.createElement('style');
styleEl.id = 'zhx-style';
styleEl.textContent = buildCSS(OPT);
placeStyle();
watchBootMark(); // 越早越好:紧贴样式注入,抢在页脚渲染之前
startObserver(); // 同样尽早:首帧的宽度校正要靠它同步执行,越早挂上越早接手
if (OPT.nightMode) {
document.documentElement.setAttribute('data-theme', 'dark');
watchNight(true);
} else {
document.documentElement.setAttribute('data-theme', 'light');
}
registerMenu();
function start() {
placeStyle(); // 就绪后归位:静态规则层叠优先于站点样式
watchScroll(OPT.autoHideHeader);
dynRun();
watchGifTrigger();
ensureToasts();
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
else start();
}
// ======================================================================
// UMD 导出 · 测试 require 真实代码;浏览器环境照常启动
// ======================================================================
var API = {
VERSION: VERSION, GROUPS: GROUPS, OPT_DEFS: OPT_DEFS,
buildCSS: buildCSS, resolveLink: resolveLink, safeDecode: safeDecode, isForeign: isForeign,
normalizeImg: normalizeImg, pickOriginal: pickOriginal, pickTime: pickTime,
applyLink: applyLink, applyTime: applyTime, applyImg: applyImg, cleanSticky: cleanSticky,
fixPostLayout: fixPostLayout, hideColumn: hideColumn, hideNarrowCols: hideNarrowCols,
POST_BODY_SEL: POST_BODY_SEL, POST_TEXT_SEL: POST_TEXT_SEL,
syncPass: syncPass, bootReady: bootReady, bootUnmark: bootUnmark,
isPostDoc: isPostDoc, pickPostRoot: pickPostRoot,
layoutVerdict: layoutVerdict, runDiag: runDiag, scheduleDiag: scheduleDiag,
DIAG_ID: DIAG_ID, READ_W: READ_W, readCap: readCap,
clampRange: clampRange, readOpt: readOpt, widthCap: widthCap,
mountRangeRow: mountRangeRow, refreshRangeRows: refreshRangeRows,
__setOpt: function (name, value) { OPT[name] = value; } // 测试注入开关用
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = API;
} else {
boot();
}
})();