Skip to content

Commit b46e5c2

Browse files
authored
Merge pull request #1036 from XMOJ-Script-dev/codex/fix-navbar-listener-leak
2 parents 973262c + 8758133 commit b46e5c2

5 files changed

Lines changed: 334 additions & 33 deletions

File tree

‎Update.json‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3817,6 +3817,17 @@
38173817
}
38183818
],
38193819
"Notes": "<p>本次正式版整合自 3.7.0 以来的修复,恢复因页面结构变化而异常的脚本功能,并兼容新版比赛页面。旧版比赛入口会转到新版页面;题目与提交状态显示得到修复,页面加载时的闪烁和布局偏移减少。</p>\n<p>题目复制支持按章节、样例或完整题面生成 Markdown,并保留公式、代码语言、表格、链接与样例换行,便于直接使用复制结果。</p>"
3820+
},
3821+
"3.8.1": {
3822+
"UpdateDate": 1791033862020,
3823+
"Prerelease": true,
3824+
"UpdateContents": [
3825+
{
3826+
"PR": 1036,
3827+
"Description": "fix: navbar listener leaks, download overlap, and web fonts"
3828+
}
3829+
],
3830+
"Notes": "<p>修复新版比赛页面和旧版界面顶部导航栏持续增加窗口缩放监听器的问题,减少长时间打开页面后的内存占用和缩放卡顿;页面导航栏被替换时会清理旧监听器。修复下载页面的卡片被插入导航栏占位元素、导致首行被顶部导航栏遮挡的问题。新版 /web 页面与旧版页面共享黑白主题字体加载,避免菜单栏使用不同字体。</p>"
38203831
}
38213832
}
38223833
}

‎XMOJ.user.js‎

Lines changed: 90 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// ==UserScript==
22
// @name XMOJ
3-
// @version 3.8.0
3+
// @version 3.8.1
44
// @description XMOJ增强脚本
55
// @author @XMOJ-Script-dev, @langningchen and the community
66
// @namespace https://github/langningchen
@@ -572,6 +572,17 @@ const ThemeCanvasCSS = `
572572
html[data-bs-theme='light'] { background: var(--mono-white, var(--bs-body-bg, #fff)); color-scheme: light; }
573573
`;
574574

575+
// Both UI initializers use this link; loading only in legacy main() leaves /web
576+
// on the fallback fonts even though it applies the same monochrome font stack.
577+
function LoadMonochromeFonts() {
578+
if (document.getElementById("xmoj-monochrome-fonts")) return;
579+
const link = document.createElement("link");
580+
link.id = "xmoj-monochrome-fonts";
581+
link.rel = "stylesheet";
582+
link.href = "https://fonts.loli.net/css2?family=Playfair+Display:wght@400;700&family=Source+Serif+4:wght@400;600;700&family=JetBrains+Mono:wght@400;500&display=swap";
583+
(document.head || document.documentElement).appendChild(link);
584+
}
585+
575586
// Set to true by the early block if Bootstrap CSS was injected from the @resource
576587
// cache. Checked in the IIFE to decide whether a CDN fallback is needed.
577588
let _earlyBootstrapInjected = false;
@@ -616,6 +627,7 @@ let _earlyObs = null;
616627
document.documentElement.setAttribute("data-bs-theme", dark ? "dark" : "light");
617628

618629
let head = document.head || document.documentElement;
630+
if (get("MonochromeUI")) LoadMonochromeFonts();
619631

620632
let bootstrapCSS = GM_getResourceText("BootstrapCSS");
621633
if (!bootstrapCSS) {
@@ -2325,6 +2337,7 @@ async function InitializeContestWebApp() {
23252337
bootstrap.href = "https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css";
23262338
document.head.appendChild(bootstrap);
23272339
const mono = UtilityEnabled("MonochromeUI");
2340+
if (mono) LoadMonochromeFonts();
23282341
const skin = document.createElement("style");
23292342
skin.textContent = mono ? MonochromeSkinCSS : NewBootstrapSkinCSS;
23302343
if (UtilityEnabled("AddAnimation")) skin.textContent += `.status, .test-case { transition: ${mono ? "100ms ease" : "0.5s"} !important; }`;
@@ -2736,7 +2749,7 @@ async function InitializeContestWebApp() {
27362749
if (!revealed && root.querySelector(".navbar")) {
27372750
// As on the legacy pages: top bar first, then show the page.
27382751
revealed = true;
2739-
if (UtilityEnabled("NewTopBar")) new NavbarStyler();
2752+
UpdateNavbarStyler();
27402753
RevealPage();
27412754
}
27422755
if (!route) return;
@@ -2763,7 +2776,7 @@ async function InitializeContestWebApp() {
27632776
window.addEventListener("popstate", ScheduleEnhance);
27642777
setInterval(() => {
27652778
UpdateCountdowns();
2766-
if (UtilityEnabled("NewTopBar")) new NavbarStyler();
2779+
UpdateNavbarStyler();
27672780
}, 1000);
27682781
window.addEventListener("focus", () => {
27692782
if (!UtilityEnabled("AutoRefresh") || !["list", "contest", "rank"].includes(route?.page)) return;
@@ -2789,13 +2802,37 @@ async function InitializeContestWebApp() {
27892802
} catch (error) { console.error("[XMOJ-Script] Navigation API:", error); }
27902803
}
27912804

2805+
let navbarStyler = null;
2806+
2807+
function UpdateNavbarStyler() {
2808+
const navbar = document.querySelector('.navbar.navbar-expand-lg.bg-body-tertiary');
2809+
// Both UI refresh timers share one listener. Release the old navbar when Vue
2810+
// replaces it, or when the top bar is disabled or removed.
2811+
if (navbarStyler && (navbarStyler.navbar !== navbar || !UtilityEnabled("NewTopBar"))) {
2812+
navbarStyler.destroy();
2813+
navbarStyler = null;
2814+
}
2815+
if (!navbar || !UtilityEnabled("NewTopBar")) return;
2816+
if (!navbarStyler) navbarStyler = new NavbarStyler(navbar);
2817+
else navbarStyler.init();
2818+
}
2819+
27922820
class NavbarStyler {
2793-
constructor() {
2821+
constructor(navbar) {
27942822
try {
2795-
this.navbar = document.querySelector('.navbar.navbar-expand-lg.bg-body-tertiary');
2796-
if (this.navbar && UtilityEnabled("NewTopBar")) {
2797-
this.init();
2798-
}
2823+
this.navbar = navbar;
2824+
this.addedClasses = ['fixed-top', 'container', 'ml-auto'].filter(name => !navbar.classList.contains(name));
2825+
this.restoreNavbarStyles = this.preserveStyles(navbar, [
2826+
'position', 'border-top-left-radius', 'border-top-right-radius',
2827+
'border-bottom-left-radius', 'border-bottom-right-radius', 'box-shadow',
2828+
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
2829+
'max-width', 'background-color', 'opacity', 'z-index'
2830+
]);
2831+
this.resizeHandler = () => {
2832+
if (this.navbar?.isConnected) this.updateBlurOverlay();
2833+
};
2834+
window.addEventListener('resize', this.resizeHandler);
2835+
this.init();
27992836
} catch (e) {
28002837
console.error(e);
28012838
if (UtilityEnabled("DebugMode")) {
@@ -2804,12 +2841,34 @@ class NavbarStyler {
28042841
}
28052842
}
28062843

2844+
preserveStyles(element, properties) {
2845+
const original = properties.map(property => [property, element.style.getPropertyValue(property), element.style.getPropertyPriority(property)]);
2846+
return () => {
2847+
for (const [property, value, priority] of original) {
2848+
if (value) element.style.setProperty(property, value, priority);
2849+
else element.style.removeProperty(property);
2850+
}
2851+
};
2852+
}
2853+
2854+
destroy() {
2855+
window.removeEventListener('resize', this.resizeHandler);
2856+
// Restore only properties/classes we changed, and remove only our own DOM.
2857+
this.navbar.classList.remove(...this.addedClasses);
2858+
this.restoreNavbarStyles();
2859+
this.restoreOverlayStyles?.();
2860+
this.restoreSpacerStyles?.();
2861+
this.overlay?.remove();
2862+
this.overlayStyle?.remove();
2863+
this.spacer?.remove();
2864+
this.navbar = null;
2865+
}
2866+
28072867
init() {
28082868
try {
28092869
this.applyStyles();
28102870
this.createOverlay();
28112871
this.createSpacer();
2812-
window.addEventListener('resize', () => this.updateBlurOverlay());
28132872
this.updateBlurOverlay();
28142873
} catch (e) {
28152874
console.error(e);
@@ -2859,8 +2918,11 @@ class NavbarStyler {
28592918
let overlay = document.createElement('div');
28602919
overlay.id = 'blur-overlay';
28612920
document.body.appendChild(overlay);
2921+
this.overlay = overlay;
28622922

28632923
let style = document.createElement('style');
2924+
this.overlayStyle?.remove();
2925+
this.overlayStyle = style;
28642926
style.textContent = UtilityEnabled("MonochromeUI") ? `
28652927
#blur-overlay {
28662928
display: none !important;
@@ -2876,6 +2938,11 @@ class NavbarStyler {
28762938
`;
28772939
document.head.appendChild(style);
28782940
}
2941+
const overlay = document.getElementById('blur-overlay');
2942+
if (overlay !== this.overlay && overlay !== this.borrowedOverlay) {
2943+
this.borrowedOverlay = overlay;
2944+
this.restoreOverlayStyles = this.preserveStyles(overlay, ['top', 'left', 'width', 'height']);
2945+
}
28792946
} catch (e) {
28802947
console.error(e);
28812948
if (UtilityEnabled("DebugMode")) {
@@ -2907,22 +2974,21 @@ class NavbarStyler {
29072974
let spacer = document.getElementById('navbar-spacer');
29082975
let newHeight = this.navbar.offsetHeight + 24;
29092976
if (!spacer) {
2910-
spacer = document.createElement('div');
2977+
// Legacy page handlers use body > div for the content container.
2978+
// A block span reserves space without becoming their first match.
2979+
spacer = document.createElement('span');
29112980
spacer.id = 'navbar-spacer';
2912-
spacer.style.height = `${newHeight}px`;
2981+
spacer.setAttribute('aria-hidden', 'true');
2982+
spacer.style.display = 'block';
29132983
spacer.style.width = '100%';
29142984
document.body.insertBefore(spacer, document.body.firstChild);
2915-
} else {
2916-
let currentHeight = parseInt(spacer.style.height, 10);
2917-
if (currentHeight !== newHeight) {
2918-
document.body.removeChild(spacer);
2919-
spacer = document.createElement('div');
2920-
spacer.id = 'navbar-spacer';
2921-
spacer.style.height = `${newHeight}px`;
2922-
spacer.style.width = '100%';
2923-
document.body.insertBefore(spacer, document.body.firstChild);
2924-
}
2985+
this.spacer = spacer;
2986+
} else if (spacer !== this.spacer && spacer !== this.borrowedSpacer) {
2987+
this.borrowedSpacer = spacer;
2988+
this.restoreSpacerStyles = this.preserveStyles(spacer, ['height']);
29252989
}
2990+
// Update in place so an existing page-owned spacer is never replaced.
2991+
if (spacer.style.height !== `${newHeight}px`) spacer.style.height = `${newHeight}px`;
29262992
} catch (e) {
29272993
console.error(e);
29282994
if (UtilityEnabled("DebugMode")) {
@@ -3077,12 +3143,7 @@ async function main() {
30773143
Temp[i].remove();
30783144
}
30793145
}
3080-
if (UtilityEnabled("MonochromeUI")) {
3081-
let fontLink = document.createElement("link");
3082-
fontLink.rel = "stylesheet";
3083-
fontLink.href = "https://fonts.loli.net/css2?family=Playfair+Display:wght@400;700&family=Source+Serif+4:wght@400;600;700&family=JetBrains+Mono:wght@400;500&display=swap";
3084-
document.head.appendChild(fontLink);
3085-
}
3146+
if (UtilityEnabled("MonochromeUI")) LoadMonochromeFonts();
30863147
var resources = [{
30873148
type: 'link',
30883149
href: 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css',
@@ -3153,7 +3214,7 @@ async function main() {
31533214
if (document.querySelector("#navbar > ul.nav.navbar-nav.navbar-right > li > a") != null) document.querySelector("#navbar > ul.nav.navbar-nav.navbar-right > li > a").removeAttribute("data-toggle");
31543215
// The navbar is in its final state: apply the top bar now rather than on
31553216
// the first interval tick, then show the page.
3156-
if (UtilityEnabled("NewTopBar")) new NavbarStyler();
3217+
UpdateNavbarStyler();
31573218
RevealPage();
31583219
}
31593220
if (UtilityEnabled("RemoveUseless") && document.getElementsByTagName("marquee")[0] != undefined) {
@@ -3219,9 +3280,7 @@ async function main() {
32193280
document.getElementById("nowdate").innerHTML = Year + "-" + (Month < 10 ? "0" : "") + Month + "-" + (_Date < 10 ? "0" : "") + _Date + " " + (Hours < 10 ? "0" : "") + Hours + ":" + (Minutes < 10 ? "0" : "") + Minutes + ":" + (Seconds < 10 ? "0" : "") + Seconds;
32203281
} catch (Error) {
32213282
}
3222-
if (UtilityEnabled("NewTopBar")) {
3223-
new NavbarStyler();
3224-
}
3283+
UpdateNavbarStyler();
32253284
if (UtilityEnabled("ResetType")) {
32263285
if (document.querySelector("#profile") != undefined && document.querySelector("#profile").innerHTML == "登录") {
32273286
let PopupUL = document.querySelector("#navbar > ul.nav.navbar-nav.navbar-right > li > ul");

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
{
22
"name": "xmoj-script",
3-
"version": "3.8.0",
3+
"version": "3.8.1",
44
"description": "an improvement script for xmoj.tech",
55
"main": "AddonScript.js",
66
"scripts": {
7-
"test": "node --test tests/contest-web.test.cjs tests/markdown-copy.test.cjs"
7+
"test": "node --test tests/contest-web.test.cjs tests/markdown-copy.test.cjs tests/navbar-styler.test.cjs"
88
},
99
"devDependencies": {
1010
"playwright": "1.59.1"

‎tests/contest-web.test.cjs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,46 @@ test('the load-time hide keeps innerText readable for the page handlers', () =>
176176
assert.match(hide, /body \{ opacity: 0 !important; \}/);
177177
assert.doesNotMatch(hide, /visibility/);
178178
});
179+
180+
test('web and classic pages load the same monochrome fonts before either Bootstrap path', () => {
181+
const early = between('// Set to true by the early block', 'const CaptchaSiteKey');
182+
const fontURLs = new Set();
183+
for (const pathname of ['/web/contest', '/problem.php?id=1000']) {
184+
for (const cachedBootstrap of [false, true]) {
185+
for (const headReady of [false, true]) {
186+
const errors = [];
187+
const {scope, styles} = context({
188+
location: new URL('https://www.xmoj.tech' + pathname),
189+
GM_getResourceText: () => cachedBootstrap ? 'body { color: black; }' : '',
190+
MutationObserver: class { observe() {} },
191+
console: {error: (...args) => errors.push(args)}
192+
});
193+
if (headReady) scope.document.head = {appendChild: node => styles.push(node)};
194+
scope.document.querySelectorAll = () => [];
195+
vm.runInContext(early, scope);
196+
const fonts = styles.filter(node => node.id === 'xmoj-monochrome-fonts');
197+
assert.equal(fonts.length, 1, pathname + ': font loading must not depend on the Bootstrap cache or head readiness');
198+
assert.equal(fonts[0].rel, 'stylesheet');
199+
fontURLs.add(fonts[0].href);
200+
scope.LoadMonochromeFonts();
201+
scope.LoadMonochromeFonts();
202+
assert.equal(styles.filter(node => node.id === 'xmoj-monochrome-fonts').length, 1, 'late initializers must reuse the early font link');
203+
assert.deepEqual(errors, []);
204+
}
205+
}
206+
}
207+
assert.equal(fontURLs.size, 1);
208+
const url = [...fontURLs][0];
209+
assert.match(url, /Source\+Serif\+4/);
210+
assert.match(url, /Playfair\+Display/);
211+
assert.match(url, /JetBrains\+Mono/);
212+
for (const disabled of ['NewBootstrap', 'MonochromeUI']) {
213+
const {scope, storage, styles} = context({
214+
GM_getResourceText: () => '',
215+
location: new URL('https://www.xmoj.tech/web/contest')
216+
});
217+
storage.set('UserScript-Setting-' + disabled, 'false');
218+
vm.runInContext(early, scope);
219+
assert.equal(styles.filter(node => node.id === 'xmoj-monochrome-fonts').length, 0, 'do not load fonts for a disabled skin');
220+
}
221+
});

0 commit comments

Comments
 (0)