正文
增加 3050 行删除 882 行
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849503 行未改动5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512617 行未改动14414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219317 行未改动21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825918 行未改动2782792802812822832842852862879 行未改动2972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428435 行未改动84985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310549 行未改动1064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811297 行未改动11371138113911401141114211431144114514 行未改动116011611162116311641165116611671168116911701171117211733 行未改动117711781179118011811182118311841185118611871188118911901191119211931194119511961197119830 行未改动122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212636 行未改动1270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414857 行未改动14931494149514961497149814991500150115021503150415051506150715081509151015111512151318 行未改动15321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116822 行未改动1685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796配置异常简单,下载油猴插件,谷歌浏览器开fq或者下载[安装包](https://pan.quark.cn/s/1ac7209c3f94#/list/share)\点击油猴-->添加新脚本->ctrl+a再ctrl+v然后ctrl+s就行了```js// ==UserScript==// @name 网页字体更换器// @namespace https://github.com/font-switcher// @version 6.1.0// @description 为任意网站更换字体,边缘吸附按钮自动收起,每个网站独立配置,支持字号/加粗设置,支持自定义字体,支持更多外观设置// @author FontSwitcher// @match *://*/*// @grant GM_addStyle// @grant GM_getValue// @grant GM_setValue// @run-at document-idle// @license MIT// ==/UserScript==(function () {'use strict';// ==================== 默认常量 ====================const DEFAULT_BTN_SIZE = 42;const COLLAPSED_VISIBLE = 6;const HOVER_ZONE = 10;const DEFAULT_IDLE_MS = 5000;const DRAG_THRESHOLD = 4;const PANEL_W = 360;const PANEL_MAX_H = 560;const MARGIN = 8;// ==================== 存储 ====================const STORAGE_KEY_CUSTOM_FONTS = 'fontSwitcher_customFonts';const STORAGE_KEY_GLOBAL_SETTINGS = 'fontSwitcher_globalSettings';const CURRENT_HOST = location.hostname;function siteKey(base) { return `${base}@${CURRENT_HOST}`; }const STORAGE_KEY_ACTIVE_FONT = siteKey('fontSwitcher_activeFont');const STORAGE_KEY_ENABLED = siteKey('fontSwitcher_enabled');const STORAGE_KEY_BTN_POS = siteKey('fontSwitcher_btnPos');const STORAGE_KEY_FONT_SETTINGS = siteKey('fontSwitcher_fontSettings');function loadFromStorage(key, fallback) {try {if (typeof GM_getValue === 'function') {const v = GM_getValue(key, null);if (v !== null && v !== undefined) return v;3 行未改动} catch (e) { /* 忽略 */ }return fallback;}function saveToStorage(key, value) {try {if (typeof GM_setValue === 'function') GM_setValue(key, value);localStorage.setItem(key, JSON.stringify(value));} catch (e) { /* 忽略 */ }}function saveBtnPosition() {saveToStorage(STORAGE_KEY_BTN_POS, { side: btnSide, y: btnY });}// ==================== 全局设置 ====================const DEFAULT_GLOBAL_SETTINGS = {btnSize: 42, // 按钮大小 28~60autoCollapse: true, // 自动吸附收起idleMs: 5000, // 收起延迟excludeInputs: false, // 排除输入框toastDuration: 2000, // Toast 显示时长};let globalSettings = Object.assign({}, DEFAULT_GLOBAL_SETTINGS, loadFromStorage(STORAGE_KEY_GLOBAL_SETTINGS, {}));function saveGlobalSettings() {saveToStorage(STORAGE_KEY_GLOBAL_SETTINGS, globalSettings);}// 派生变量(从设置中读取)let BTN_SIZE = globalSettings.btnSize || DEFAULT_BTN_SIZE;let IDLE_MS = globalSettings.autoCollapse ? (globalSettings.idleMs || DEFAULT_IDLE_MS) : Infinity;let COLLAPSED_SHIFT = BTN_SIZE - COLLAPSED_VISIBLE;function refreshDerivedSettings() {BTN_SIZE = globalSettings.btnSize || DEFAULT_BTN_SIZE;IDLE_MS = globalSettings.autoCollapse ? (globalSettings.idleMs || DEFAULT_IDLE_MS) : Infinity;COLLAPSED_SHIFT = BTN_SIZE - COLLAPSED_VISIBLE;}// ==================== 状态 ====================let customFonts = loadFromStorage(STORAGE_KEY_CUSTOM_FONTS, []);let activeFontValue = loadFromStorage(STORAGE_KEY_ACTIVE_FONT, '');let isEnabled = loadFromStorage(STORAGE_KEY_ENABLED, true);let fontSettings = loadFromStorage(STORAGE_KEY_FONT_SETTINGS, {});const savedPos = loadFromStorage(STORAGE_KEY_BTN_POS, null);let btnSide = (savedPos && savedPos.side) ? savedPos.side : 'right';let btnY = (savedPos && typeof savedPos.y === 'number') ? savedPos.y : 60;let panelVisible = false;let btnCollapsed = false;let idleTimer = null;let isDragging = false;let hasDragged = false;let dragStartX = 0, dragStartY = 0;let btnStartLeft = 0, btnStartTop = 0;let previewStyleEl = null;let expandedSettingsSet = new Set();let settingsViewActive = false; // 设置视图是否激活// ==================== 预置字体 ====================const PRESET_FONTS = [{ name: '默认(不替换)', value: '' },{ name: '微软雅黑', value: '"Microsoft YaHei", "微软雅黑", sans-serif' },{ name: '苹方', value: '"PingFang SC", "Helvetica Neue", sans-serif' },{ name: '宋体', value: 'SimSun, "宋体", serif' },17 行未改动{ name: 'Trebuchet MS', value: '"Trebuchet MS", Helvetica, sans-serif' },{ name: 'Verdana', value: 'Verdana, Geneva, sans-serif' },];// ==================== 字体设置工具 ====================function getFontSettings(fontValue) {if (!fontValue) return null;return fontSettings[fontValue] || null;}function setFontSettings(fontValue, settings) {if (!fontValue) return;fontSettings[fontValue] = settings;saveToStorage(STORAGE_KEY_FONT_SETTINGS, fontSettings);}function removeFontSettings(fontValue) {if (!fontValue) return;delete fontSettings[fontValue];saveToStorage(STORAGE_KEY_FONT_SETTINGS, fontSettings);}function hasNonDefaultSettings(fontValue) {if (!fontValue) return false;const s = fontSettings[fontValue];if (!s) return false;if (s.size) return true;if (s.weight && s.weight !== '' && s.weight !== 'normal') return true;return false;}// ==================== 样式注入 ====================function buildStyles() {return `/* ========== 按钮 ========== */#fs-trigger-btn {position: fixed;z-index: 2147483647;width: ${BTN_SIZE}px;height: ${BTN_SIZE}px;border: none;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: #fff;font-size: ${Math.round(BTN_SIZE * 0.43)}px;font-weight: bold;cursor: pointer;box-shadow: 0 4px 15px rgba(102, 126, 234, 0.45);display: flex;17 行未改动}#fs-trigger-btn .fs-btn-icon {pointer-events: none;line-height: 1;font-size: ${Math.round(BTN_SIZE * 0.48)}px;transition: opacity 0.2s;}/* 右侧吸附 */#fs-trigger-btn.fs-side-right {right: 0;left: auto;border-radius: ${BTN_SIZE / 2}px 0 0 ${BTN_SIZE / 2}px;}#fs-trigger-btn.fs-side-right.fs-collapsed {transform: translateX(${COLLAPSED_SHIFT}px);border-radius: 8px 0 0 8px;pointer-events: none;opacity: 0.5;}#fs-trigger-btn.fs-side-right.fs-collapsed .fs-btn-icon { opacity: 0; }/* 左侧吸附 */#fs-trigger-btn.fs-side-left {left: 0;right: auto;border-radius: 0 ${BTN_SIZE / 2}px ${BTN_SIZE / 2}px 0;}#fs-trigger-btn.fs-side-left.fs-collapsed {transform: translateX(-${COLLAPSED_SHIFT}px);border-radius: 0 8px 8px 0;pointer-events: none;opacity: 0.5;}#fs-trigger-btn.fs-side-left.fs-collapsed .fs-btn-icon { opacity: 0; }/* 拖拽中 */#fs-trigger-btn.fs-dragging {cursor: grabbing !important;opacity: 1;box-shadow: 0 8px 30px rgba(118, 75, 162, 0.7);transform: scale(1.08) !important;border-radius: 50% !important;transition: box-shadow 0.15s, opacity 0.15s;}#fs-trigger-btn.fs-active {opacity: 1;box-shadow: 0 6px 24px rgba(118, 75, 162, 0.7);}18 行未改动/* ========== 面板 ========== */#fs-panel {position: fixed;z-index: 2147483647;width: ${PANEL_W}px;max-height: ${PANEL_MAX_H}px;background: #ffffff;border-radius: 16px;box-shadow: 0 12px 48px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.08);font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;9 行未改动from { opacity: 0; transform: translateY(-12px) scale(0.96); }to { opacity: 1; transform: translateY(0) scale(1); }}/* 面板头部 */#fs-panel .fs-header {padding: 16px 18px 12px;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: #fff;display: flex;align-items: center;justify-content: space-between;flex-shrink: 0;}#fs-panel .fs-header-left {display: flex;flex-direction: column;gap: 2px;}#fs-panel .fs-header-title {font-size: 15px;font-weight: 600;letter-spacing: 0.5px;}#fs-panel .fs-header-host {font-size: 10px;opacity: 0.7;font-weight: 400;}#fs-panel .fs-header-actions {display: flex;align-items: center;gap: 6px;}#fs-panel .fs-header-gear,#fs-panel .fs-header-close {width: 28px; height: 28px;border-radius: 50%;border: none;background: rgba(255,255,255,0.2);color: #fff;font-size: 16px;cursor: pointer;display: flex;align-items: center;justify-content: center;transition: background 0.15s;line-height: 1;}#fs-panel .fs-header-gear:hover,#fs-panel .fs-header-close:hover { background: rgba(255,255,255,0.35); }#fs-panel .fs-header-gear.fs-gear-active { background: rgba(255,255,255,0.45); }/* 开关 */#fs-panel .fs-toggle-row {display: flex;align-items: center;justify-content: space-between;padding: 10px 18px;background: #f8f8ff;border-bottom: 1px solid #eee;flex-shrink: 0;}#fs-panel .fs-toggle-label { font-size: 13px; color: #666; }#fs-panel .fs-toggle-switch { position: relative; width: 44px; height: 24px; cursor: pointer; }#fs-panel .fs-toggle-switch input { opacity: 0; width: 0; height: 0; }#fs-panel .fs-toggle-slider {position: absolute;top: 0; left: 0; right: 0; bottom: 0;background: #ccc;border-radius: 24px;transition: background 0.25s;}#fs-panel .fs-toggle-slider::before {content: '';position: absolute;width: 18px; height: 18px;left: 3px; bottom: 3px;background: #fff;border-radius: 50%;transition: transform 0.25s;}#fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider { background: #667eea; }#fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider::before { transform: translateX(20px); }/* 字体列表 */#fs-panel .fs-list-container {flex: 1;overflow-y: auto;padding: 4px 0;scrollbar-width: thin;scrollbar-color: #d0d0d0 transparent;}#fs-panel .fs-list-container::-webkit-scrollbar { width: 5px; }#fs-panel .fs-list-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }/* 分组标题 */#fs-panel .fs-group-title {padding: 8px 18px 4px;font-size: 11px;font-weight: 600;color: #999;text-transform: uppercase;letter-spacing: 1px;user-select: none;}/* 字体项 */#fs-panel .fs-font-item {display: flex;align-items: center;padding: 7px 12px 7px 18px;cursor: pointer;transition: background 0.12s;gap: 8px;}#fs-panel .fs-font-item:hover { background: #f0f0ff; }#fs-panel .fs-font-item.fs-active { background: #eef0ff; }#fs-panel .fs-font-item .fs-radio {width: 16px; height: 16px;border-radius: 50%;border: 2px solid #ccc;flex-shrink: 0;display: flex;align-items: center;justify-content: center;transition: border-color 0.15s;}#fs-panel .fs-font-item.fs-active .fs-radio { border-color: #667eea; }#fs-panel .fs-font-item.fs-active .fs-radio::after {content: '';width: 8px; height: 8px;border-radius: 50%;background: #667eea;}#fs-panel .fs-font-item .fs-font-info {flex: 1;min-width: 0;}#fs-panel .fs-font-item .fs-font-name {font-size: 13px;color: #333;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}#fs-panel .fs-font-item .fs-font-preview {font-size: 12px;color: #888;margin-top: 1px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}#fs-panel .fs-font-item .fs-has-settings {font-size: 9px;color: #667eea;margin-left: 4px;font-weight: 600;}/* 设置齿轮按钮(字体项) */#fs-panel .fs-font-item .fs-settings-btn {width: 22px; height: 22px;border-radius: 4px;border: none;background: transparent;color: #bbb;font-size: 13px;cursor: pointer;display: flex;align-items: center;justify-content: center;transition: all 0.15s;flex-shrink: 0;opacity: 0;}#fs-panel .fs-font-item:hover .fs-settings-btn { opacity: 1; }#fs-panel .fs-font-item .fs-settings-btn:hover { background: #e8e8ff; color: #667eea; }#fs-panel .fs-font-item .fs-settings-btn.fs-settings-active { opacity: 1; color: #667eea; }/* 删除按钮 */#fs-panel .fs-font-item .fs-delete-btn {width: 22px; height: 22px;border-radius: 4px;border: none;background: transparent;color: #bbb;font-size: 14px;cursor: pointer;display: flex;align-items: center;justify-content: center;transition: all 0.15s;flex-shrink: 0;opacity: 0;}#fs-panel .fs-font-item:hover .fs-delete-btn { opacity: 1; }#fs-panel .fs-font-item .fs-delete-btn:hover { background: #ffe0e0; color: #e55; }/* 字体设置面板 */#fs-panel .fs-font-settings {background: #f5f5ff;border-bottom: 1px solid #e0e0ee;padding: 10px 18px;display: none;}#fs-panel .fs-font-settings.fs-show { display: block; }#fs-panel .fs-font-settings .fs-settings-row {display: flex;align-items: center;gap: 8px;margin-bottom: 6px;}#fs-panel .fs-font-settings .fs-settings-row:last-child { margin-bottom: 0; }#fs-panel .fs-font-settings .fs-settings-label {font-size: 11px;color: #777;width: 42px;flex-shrink: 0;}#fs-panel .fs-font-settings .fs-settings-input {flex: 1;height: 28px;border: 1px solid #d8d8e8;border-radius: 6px;padding: 0 8px;font-size: 12px;font-family: inherit;outline: none;background: #fff;color: #333;transition: border-color 0.15s;}#fs-panel .fs-font-settings .fs-settings-input:focus { border-color: #667eea; }#fs-panel .fs-font-settings .fs-settings-select {flex: 1;height: 28px;border: 1px solid #d8d8e8;border-radius: 6px;padding: 0 6px;font-size: 12px;font-family: inherit;outline: none;background: #fff;color: #333;cursor: pointer;}#fs-panel .fs-font-settings .fs-settings-hint {font-size: 10px;color: #aaa;margin-top: 4px;}/* ========== 设置视图 ========== */#fs-panel .fs-settings-view {flex: 1;overflow-y: auto;padding: 0;scrollbar-width: thin;scrollbar-color: #d0d0d0 transparent;}#fs-panel .fs-settings-view::-webkit-scrollbar { width: 5px; }#fs-panel .fs-settings-view::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }#fs-panel .fs-sv-section {padding: 12px 18px;border-bottom: 1px solid #f0f0f0;}#fs-panel .fs-sv-section:last-child { border-bottom: none; }#fs-panel .fs-sv-section-title {font-size: 12px;font-weight: 600;color: #888;margin-bottom: 10px;text-transform: uppercase;letter-spacing: 0.5px;}#fs-panel .fs-sv-row {display: flex;align-items: center;justify-content: space-between;padding: 6px 0;min-height: 32px;}#fs-panel .fs-sv-row-label {font-size: 13px;color: #444;flex-shrink: 0;}#fs-panel .fs-sv-row-label small {display: block;font-size: 10px;color: #aaa;font-weight: 400;margin-top: 1px;}#fs-panel .fs-sv-row-right {display: flex;align-items: center;gap: 6px;}/* 设置页的 select */#fs-panel .fs-sv-select {height: 30px;border: 1px solid #d8d8e8;border-radius: 6px;padding: 0 8px;font-size: 12px;font-family: inherit;outline: none;background: #fff;color: #333;cursor: pointer;min-width: 100px;}#fs-panel .fs-sv-select:focus { border-color: #667eea; }/* ========== 按钮大小滑块 ========== */#fs-panel .fs-sv-range-wrapper {display: flex;align-items: center;gap: 10px;}#fs-panel .fs-sv-range {-webkit-appearance: none;appearance: none;width: 110px;height: 6px;border-radius: 3px;background: linear-gradient(to right, #667eea 0%, #667eea var(--range-pct, 50%), #ddd var(--range-pct, 50%), #ddd 100%);outline: none;cursor: pointer;transition: background 0.1s;}#fs-panel .fs-sv-range::-webkit-slider-thumb {-webkit-appearance: none;appearance: none;width: 18px;height: 18px;border-radius: 50%;background: #fff;border: 3px solid #667eea;cursor: pointer;box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);transition: transform 0.15s, box-shadow 0.15s;}#fs-panel .fs-sv-range::-webkit-slider-thumb:hover {transform: scale(1.15);box-shadow: 0 2px 8px rgba(102, 126, 234, 0.5);}#fs-panel .fs-sv-range::-moz-range-thumb {width: 18px;height: 18px;border-radius: 50%;background: #fff;border: 3px solid #667eea;cursor: pointer;box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);}#fs-panel .fs-sv-range::-moz-range-track {height: 6px;border-radius: 3px;background: #ddd;}#fs-panel .fs-sv-range::-moz-range-progress {height: 6px;border-radius: 3px;background: #667eea;}#fs-panel .fs-sv-range-value {font-size: 12px;color: #667eea;font-weight: 700;min-width: 38px;text-align: right;font-variant-numeric: tabular-nums;}/* 按钮大小预览小圆点 */#fs-panel .fs-sv-btn-preview {border-radius: 50%;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);transition: width 0.2s ease, height 0.2s ease;flex-shrink: 0;}/* 设置页的开关(复用 toggle 样式) */#fs-panel .fs-sv-toggle { position: relative; width: 44px; height: 24px; cursor: pointer; }#fs-panel .fs-sv-toggle input { opacity: 0; width: 0; height: 0; }#fs-panel .fs-sv-toggle-slider {position: absolute;top: 0; left: 0; right: 0; bottom: 0;background: #ccc;border-radius: 24px;transition: background 0.25s;}#fs-panel .fs-sv-toggle-slider::before {content: '';position: absolute;width: 18px; height: 18px;left: 3px; bottom: 3px;background: #fff;border-radius: 50%;transition: transform 0.25s;}#fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider { background: #667eea; }#fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider::before { transform: translateX(20px); }/* 设置页按钮 */#fs-panel .fs-sv-btn {height: 32px;border: 1px solid #d8d8e8;border-radius: 8px;padding: 0 14px;font-size: 12px;font-family: inherit;cursor: pointer;background: #fff;color: #555;transition: all 0.15s;}#fs-panel .fs-sv-btn:hover { border-color: #667eea; color: #667eea; background: #f5f5ff; }#fs-panel .fs-sv-btn-danger { color: #e55; }#fs-panel .fs-sv-btn-danger:hover { border-color: #e55; color: #e55; background: #fff5f5; }/* 上传字体区域(设置页内) */#fs-panel .fs-sv-upload-btn {flex: 1;height: 36px;border: 1.5px dashed #bbb;border-radius: 8px;background: #fff;color: #667eea;font-size: 13px;font-weight: 500;cursor: pointer;transition: border-color 0.15s, background 0.15s;white-space: nowrap;display: flex;align-items: center;justify-content: center;gap: 6px;}#fs-panel .fs-sv-upload-btn:hover {border-color: #667eea;background: #f0f0ff;}#fs-panel .fs-sv-upload-hint {font-size: 10px;color: #aaa;margin-top: 6px;}/* Toast - 屏幕顶部居中 */#fs-toast {position: fixed;z-index: 2147483647;padding: 10px 24px;border-radius: 10px;font-size: 13px;font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;color: #fff;pointer-events: none;display: none;left: 50%;transform: translateX(-50%);top: 24px;white-space: nowrap;}#fs-toast.fs-toast-show { display: block; }#fs-toast.fs-toast-success { background: #4caf50; }#fs-toast.fs-toast-error { background: #f44336; }#fs-toast.fs-toast-info { background: #667eea; }`;}let mainStyleEl = null;function injectStyles() {if (mainStyleEl) mainStyleEl.remove();if (typeof GM_addStyle === 'function') {// GM_addStyle 无法更新,用 style 标签替代mainStyleEl = document.createElement('style');mainStyleEl.id = 'fs-main-styles';mainStyleEl.textContent = buildStyles();document.head.appendChild(mainStyleEl);} else {mainStyleEl = document.createElement('style');mainStyleEl.id = 'fs-main-styles';mainStyleEl.textContent = buildStyles();document.head.appendChild(mainStyleEl);}}function updateStyles() {if (mainStyleEl) {mainStyleEl.textContent = buildStyles();}// 更新按钮实际尺寸triggerBtn.style.width = BTN_SIZE + 'px';triggerBtn.style.height = BTN_SIZE + 'px';}injectStyles();previewStyleEl = document.createElement('style');previewStyleEl.id = 'fs-preview-styles';document.head.appendChild(previewStyleEl);const uiRecoveryStyleEl = document.createElement('style');uiRecoveryStyleEl.id = 'fs-ui-recovery';uiRecoveryStyleEl.textContent = `#fs-trigger-btn, #fs-trigger-btn *,#fs-overlay,#fs-panel, #fs-panel *,#fs-toast, #fs-toast * {font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;}`;document.head.appendChild(uiRecoveryStyleEl);// ==================== DOM 构建 ====================const triggerBtn = document.createElement('button');triggerBtn.id = 'fs-trigger-btn';triggerBtn.title = '字体更换器(可拖拽移动)';triggerBtn.innerHTML = '<span class="fs-btn-icon">Aa</span>';triggerBtn.classList.add('fs-side-' + btnSide, 'fs-entering');document.body.appendChild(triggerBtn);const overlay = document.createElement('div');overlay.id = 'fs-overlay';document.body.appendChild(overlay);const panel = document.createElement('div');panel.id = 'fs-panel';panel.innerHTML = `<div class="fs-header"><div class="fs-header-left"><span class="fs-header-title">字体更换器</span><span class="fs-header-host">${CURRENT_HOST}</span></div><div class="fs-header-actions"><button class="fs-header-gear" id="fs-header-gear-btn" title="设置">⚙</button><button class="fs-header-close" title="关闭">×</button>5 行未改动<input type="checkbox" id="fs-enabled-toggle"><span class="fs-toggle-slider"></span></label></div><!-- 字体列表视图 --><div class="fs-list-container" id="fs-font-list"></div><!-- 设置视图 --><div class="fs-settings-view" id="fs-settings-view" style="display:none;"></div>`;document.body.appendChild(panel);const toast = document.createElement('div');toast.id = 'fs-toast';document.body.appendChild(toast);// 隐藏的文件 input(全局共用)const fontFileInput = document.createElement('input');fontFileInput.type = 'file';fontFileInput.id = 'fs-font-file-input';fontFileInput.accept = '.woff2,.woff,.ttf,.otf,.eot';fontFileInput.multiple = true;fontFileInput.style.display = 'none';document.body.appendChild(fontFileInput);// ==================== 按钮位置管理 ====================function applyBtnPosition() {triggerBtn.style.top = btnY + 'px';triggerBtn.style.left = '';triggerBtn.style.right = '';triggerBtn.classList.remove('fs-side-left', 'fs-side-right');triggerBtn.classList.add('fs-side-' + btnSide);if (!btnCollapsed) triggerBtn.style.transform = '';}function clampBtnY() {btnY = Math.max(0, Math.min(btnY, window.innerHeight - BTN_SIZE));}// ==================== 收缩 / 展开 ====================function collapseBtn() {if (btnCollapsed || panelVisible) return;if (!globalSettings.autoCollapse) return;btnCollapsed = true;triggerBtn.classList.add('fs-collapsed');}function expandBtn() {if (!btnCollapsed) return;btnCollapsed = false;triggerBtn.classList.remove('fs-collapsed');resetIdleTimer();}function resetIdleTimer() {if (idleTimer) clearTimeout(idleTimer);if (!panelVisible && globalSettings.autoCollapse) {idleTimer = setTimeout(collapseBtn, IDLE_MS);}}document.addEventListener('mousemove', (e) => {if (!btnCollapsed) return;const vx = window.innerWidth;const nearEdge = (btnSide === 'right' && e.clientX > vx - HOVER_ZONE) ||(btnSide === 'left' && e.clientX < HOVER_ZONE);const nearBtnY = e.clientY >= btnY - HOVER_ZONE &&e.clientY <= btnY + BTN_SIZE + HOVER_ZONE;if (nearEdge && nearBtnY) {expandBtn();}});triggerBtn.addEventListener('mouseenter', () => {if (!btnCollapsed) resetIdleTimer();});// ==================== 拖拽逻辑 ====================function onPointerDown(e) {if (btnCollapsed) return;if (e.button && e.button !== 0) return;const clientX = e.touches ? e.touches[0].clientX : e.clientX;const clientY = e.touches ? e.touches[0].clientY : e.clientY;isDragging = true;hasDragged = false;dragStartX = clientX;dragStartY = clientY;const rect = triggerBtn.getBoundingClientRect();btnStartLeft = rect.left;btnStartTop = rect.top;e.preventDefault();}function onPointerMove(e) {if (!isDragging) return;const clientX = e.touches ? e.touches[0].clientX : e.clientX;const clientY = e.touches ? e.touches[0].clientY : e.clientY;const dx = clientX - dragStartX;const dy = clientY - dragStartY;if (!hasDragged && Math.abs(dx) < DRAG_THRESHOLD && Math.abs(dy) < DRAG_THRESHOLD) return;if (!hasDragged) { hasDragged = true; closePanel(); }triggerBtn.style.right = 'auto';triggerBtn.style.left = (btnStartLeft + dx) + 'px';triggerBtn.style.top = (btnStartTop + dy) + 'px';triggerBtn.classList.remove('fs-collapsed');triggerBtn.classList.add('fs-dragging');btnCollapsed = false;e.preventDefault();}function onPointerUp(e) {if (!isDragging) return;isDragging = false;triggerBtn.classList.remove('fs-dragging');if (hasDragged) {const rect = triggerBtn.getBoundingClientRect();btnSide = (rect.left + rect.width / 2) < window.innerWidth / 2 ? 'left' : 'right';btnY = rect.top;clampBtnY();saveBtnPosition();applyBtnPosition();resetIdleTimer();setTimeout(() => { hasDragged = false; }, 50);}}triggerBtn.addEventListener('mousedown', onPointerDown);document.addEventListener('mousemove', onPointerMove);document.addEventListener('mouseup', onPointerUp);triggerBtn.addEventListener('touchstart', onPointerDown, { passive: false });document.addEventListener('touchmove', onPointerMove, { passive: false });document.addEventListener('touchend', onPointerUp);triggerBtn.addEventListener('click', (e) => {if (hasDragged || btnCollapsed) return;togglePanel();});window.addEventListener('resize', () => {clampBtnY();applyBtnPosition();if (panelVisible) positionPanel();});// ==================== 面板定位 ====================function positionPanel() {const btnRect = triggerBtn.getBoundingClientRect();const vw = window.innerWidth;const vh = window.innerHeight;const gap = 10;const inwardOffset = BTN_SIZE + 12;let left, top;if (btnSide === 'right') {left = btnRect.left - PANEL_W - gap;if (left < MARGIN) {left = btnRect.right - PANEL_W + inwardOffset;}} else {left = btnRect.right + gap;if (left + PANEL_W > vw - MARGIN) {left = btnRect.left - inwardOffset;}}left = Math.max(MARGIN, Math.min(left, vw - PANEL_W - MARGIN));top = btnRect.top;if (top + PANEL_MAX_H > vh - MARGIN) top = vh - PANEL_MAX_H - MARGIN;if (top < MARGIN) top = MARGIN;panel.style.left = left + 'px';panel.style.top = top + 'px';}// ==================== 字体应用(核心) ====================let injectedStyleEl = null;function applyFont(fontValue) {if (injectedStyleEl) {injectedStyleEl.remove();injectedStyleEl = null;}if (!fontValue || !isEnabled) return;const settings = getFontSettings(fontValue);const fontSize = (settings && settings.size) ? settings.size : '';const fontWeight = (settings && settings.weight) ? settings.weight : '';let extraProps = '';if (fontSize) extraProps += `font-size: ${fontSize} !important;\n`;if (fontWeight) extraProps += `font-weight: ${fontWeight} !important;\n`;const excludeInputs = globalSettings.excludeInputs;const inputSelector = excludeInputs ? '' : `, input, textarea, select, button`;injectedStyleEl = document.createElement('style');injectedStyleEl.id = 'fs-injected-font';injectedStyleEl.textContent = `html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp,9 行未改动font-family: ${fontValue} !important;${extraProps}}`;document.head.appendChild(injectedStyleEl);}function loadCustomFontFace(name, url, format) {const id = 'fs-fontface-' + CSS.escape(name.replace(/\s+/g, '-'));if (document.getElementById(id)) return;const styleEl = document.createElement('style');styleEl.id = id;const srcStr = format? `url("${url}") format("${format}")`: `url("${url}")`;styleEl.textContent = `@font-face { font-family: "${name}"; src: ${srcStr}; }`;document.head.appendChild(styleEl);}// ==================== 预览样式更新 ====================function updatePreviewStyles() {const allFonts = [...PRESET_FONTS, ...customFonts];let css = '';allFonts.forEach((font, i) => {if (font.value) {css += `#fs-panel #fs-preview-${i} { font-family: ${font.value} !important; }\n`;}});previewStyleEl.textContent = css;}// ==================== 渲染字体列表 ====================function renderFontList() {const listContainer = document.getElementById('fs-font-list');listContainer.innerHTML = '';let idx = 0;const presetGroup = document.createElement('div');presetGroup.className = 'fs-group-title';presetGroup.textContent = '预置字体';listContainer.appendChild(presetGroup);PRESET_FONTS.forEach(font => {presetGroup.appendChild(createFontItem(font, false, idx++));});if (customFonts.length > 0) {const customGroup = document.createElement('div');customGroup.className = 'fs-group-title';customGroup.textContent = '自定义字体(全局)';listContainer.appendChild(customGroup);customFonts.forEach(font => {customGroup.appendChild(createFontItem(font, true, idx++));});}updatePreviewStyles();}function createFontItem(font, isCustom, index) {const isActive = activeFontValue === font.value;const wrapper = document.createElement('div');const item = document.createElement('div');item.className = 'fs-font-item' + (isActive ? ' fs-active' : '');7 行未改动const nameEl = document.createElement('div');nameEl.className = 'fs-font-name';nameEl.textContent = font.name;const settings = getFontSettings(font.value);if (settings && (settings.size || settings.weight) && font.value) {const badge = document.createElement('span');badge.className = 'fs-has-settings';let label = '';14 行未改动item.appendChild(info);if (font.value) {const settingsBtn = document.createElement('button');settingsBtn.className = 'fs-settings-btn' + (expandedSettingsSet.has(font.value) ? ' fs-settings-active' : '');settingsBtn.innerHTML = '⚙';settingsBtn.title = '字号/加粗设置';settingsBtn.addEventListener('click', (e) => {e.stopPropagation();toggleSettings(font.value, wrapper);});item.appendChild(settingsBtn);}3 行未改动delBtn.innerHTML = '×';delBtn.title = '删除此字体';delBtn.addEventListener('click', (e) => {e.stopPropagation();deleteCustomFont(font);});item.appendChild(delBtn);}item.addEventListener('click', () => selectFont(font));wrapper.appendChild(item);if (font.value) {const settingsPanel = document.createElement('div');settingsPanel.className = 'fs-font-settings' + (expandedSettingsSet.has(font.value) ? ' fs-show' : '');settingsPanel.id = 'fs-settings-' + index;const current = getFontSettings(font.value) || {};settingsPanel.innerHTML = `<div class="fs-settings-row"><span class="fs-settings-label">字号</span>30 行未改动const handler = () => {const fv = input.dataset.fontValue;const field = input.dataset.field;const val = input.value.trim();const s = getFontSettings(fv) || {};if (val) {s[field] = val;} else {delete s[field];}if (Object.keys(s).length === 0) {removeFontSettings(fv);} else {setFontSettings(fv, s);}if (fv === activeFontValue) {applyFont(activeFontValue);}const settingsPanelEl = input.closest('.fs-font-settings');if (hasNonDefaultSettings(fv)) {expandedSettingsSet.add(fv);if (settingsPanelEl) settingsPanelEl.classList.add('fs-show');} else {expandedSettingsSet.delete(fv);if (settingsPanelEl) settingsPanelEl.classList.remove('fs-show');}const wrapperEl = settingsPanelEl ? settingsPanelEl.previousElementSibling : null;if (wrapperEl) {const gearBtn = wrapperEl.querySelector('.fs-settings-btn');if (gearBtn) {if (expandedSettingsSet.has(fv)) gearBtn.classList.add('fs-settings-active');else gearBtn.classList.remove('fs-settings-active');}}};6 行未改动return wrapper;}function toggleSettings(fontValue, wrapper) {if (expandedSettingsSet.has(fontValue)) {expandedSettingsSet.delete(fontValue);} else {expandedSettingsSet.add(fontValue);}renderFontList();}// ==================== 字体选择 ====================function selectFont(font) {activeFontValue = font.value;saveToStorage(STORAGE_KEY_ACTIVE_FONT, activeFontValue);if (font.value && isEnabled) {applyFont(font.value);} else {applyFont('');}renderFontList();showToast(`已切换为:${font.name}`, 'success');}function deleteCustomFont(font) {customFonts = customFonts.filter(f => f.value !== font.value);saveToStorage(STORAGE_KEY_CUSTOM_FONTS, customFonts);removeFontSettings(font.value);if (activeFontValue === font.value) {activeFontValue = '';saveToStorage(STORAGE_KEY_ACTIVE_FONT, activeFontValue);applyFont('');}const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));const faceEl = document.getElementById(faceId);if (faceEl) faceEl.remove();renderFontList();showToast(`已删除:${font.name}`, 'info');}// ==================== 添加自定义字体 ====================function addUploadedFont(name, dataUrl, format) {const value = `"${name}", sans-serif`;if (customFonts.some(f => f.name === name)) {showToast('该字体名称已存在', 'error');return;}loadCustomFontFace(name, dataUrl, format);customFonts.push({ name, value, dataUrl, format });saveToStorage(STORAGE_KEY_CUSTOM_FONTS, customFonts);renderFontList();showToast(`已添加字体:${name}`, 'success');}function handleFontFileUpload(files) {if (!files || files.length === 0) return;const validExts = ['.woff2', '.woff', '.ttf', '.otf', '.eot'];const formatMap = {'woff2': 'woff2','woff': 'woff','ttf': 'truetype','otf': 'opentype','eot': 'embedded-opentype',};Array.from(files).forEach(file => {const ext = '.' + file.name.split('.').pop().toLowerCase();if (!validExts.includes(ext)) {showToast(`不支持的格式:${file.name}`, 'error');return;}const fontName = file.name.replace(/\.[^.]+$/, '');const format = formatMap[ext.replace('.', '')] || 'truetype';if (customFonts.some(f => f.name === fontName)) {showToast(`字体已存在:${fontName}`, 'error');return;}const reader = new FileReader();reader.onload = function(e) {const dataUrl = e.target.result;addUploadedFont(fontName, dataUrl, format);};reader.onerror = function() {showToast(`读取失败:${file.name}`, 'error');};reader.readAsDataURL(file);});}function reloadCustomFonts() {customFonts.forEach(font => {const url = font.dataUrl || font.url;if (url) loadCustomFontFace(font.name, url, font.format || null);});}// ==================== 滑块进度更新工具 ====================function updateRangeProgress(rangeEl) {const min = parseFloat(rangeEl.min) || 0;const max = parseFloat(rangeEl.max) || 100;const val = parseFloat(rangeEl.value) || min;const pct = ((val - min) / (max - min)) * 100;rangeEl.style.setProperty('--range-pct', pct + '%');}// ==================== 设置视图渲染 ====================function renderSettingsView() {const view = document.getElementById('fs-settings-view');view.innerHTML = '';// --- 外观 ---const secAppearance = document.createElement('div');secAppearance.className = 'fs-sv-section';secAppearance.innerHTML = `<div class="fs-sv-section-title">外观</div>`;// 按钮大小(滑块 + 预览)const rowBtnSize = document.createElement('div');rowBtnSize.className = 'fs-sv-row';const btnPreviewSize = Math.max(12, Math.round(BTN_SIZE * 0.42));rowBtnSize.innerHTML = `<span class="fs-sv-row-label">按钮大小<small>拖动滑块调整悬浮按钮尺寸</small></span><div class="fs-sv-row-right"><div class="fs-sv-btn-preview" id="fs-sv-btnPreview" style="width:${btnPreviewSize}px;height:${btnPreviewSize}px;"></div><div class="fs-sv-range-wrapper"><input type="range" class="fs-sv-range" id="fs-sv-btnSize"min="28" max="60" step="2" value="${BTN_SIZE}"><span class="fs-sv-range-value" id="fs-sv-btnSize-val">${BTN_SIZE}px</span></div></div>`;secAppearance.appendChild(rowBtnSize);// 排除输入框const rowExcludeInputs = document.createElement('div');rowExcludeInputs.className = 'fs-sv-row';rowExcludeInputs.innerHTML = `<span class="fs-sv-row-label">排除输入框<small>不对 input / textarea / select 应用字体</small></span><div class="fs-sv-row-right"><label class="fs-sv-toggle"><input type="checkbox" id="fs-sv-excludeInputs" ${globalSettings.excludeInputs ? 'checked' : ''}><span class="fs-sv-toggle-slider"></span></label></div>`;secAppearance.appendChild(rowExcludeInputs);view.appendChild(secAppearance);// --- 行为 ---const secBehavior = document.createElement('div');secBehavior.className = 'fs-sv-section';secBehavior.innerHTML = `<div class="fs-sv-section-title">行为</div>`;// 自动吸附收起const rowAutoCollapse = document.createElement('div');rowAutoCollapse.className = 'fs-sv-row';rowAutoCollapse.innerHTML = `<span class="fs-sv-row-label">自动吸附收起<small>闲置后按钮收缩至屏幕边缘</small></span><div class="fs-sv-row-right"><label class="fs-sv-toggle"><input type="checkbox" id="fs-sv-autoCollapse" ${globalSettings.autoCollapse ? 'checked' : ''}><span class="fs-sv-toggle-slider"></span></label></div>`;secBehavior.appendChild(rowAutoCollapse);// 收起延迟const rowIdleMs = document.createElement('div');rowIdleMs.className = 'fs-sv-row';rowIdleMs.innerHTML = `<span class="fs-sv-row-label">收起延迟<small>闲置多久后自动收起</small></span><div class="fs-sv-row-right"><select class="fs-sv-select" id="fs-sv-idleMs"><option value="3000" ${globalSettings.idleMs === 3000 ? 'selected' : ''}>3 秒</option><option value="5000" ${globalSettings.idleMs === 5000 ? 'selected' : ''}>5 秒</option><option value="10000" ${globalSettings.idleMs === 10000 ? 'selected' : ''}>10 秒</option><option value="15000" ${globalSettings.idleMs === 15000 ? 'selected' : ''}>15 秒</option><option value="30000" ${globalSettings.idleMs === 30000 ? 'selected' : ''}>30 秒</option></select></div>`;secBehavior.appendChild(rowIdleMs);// Toast 时长const rowToast = document.createElement('div');rowToast.className = 'fs-sv-row';rowToast.innerHTML = `<span class="fs-sv-row-label">提示显示时长<small>操作反馈提示的持续时间</small></span><div class="fs-sv-row-right"><select class="fs-sv-select" id="fs-sv-toastDuration"><option value="1000" ${globalSettings.toastDuration === 1000 ? 'selected' : ''}>1 秒</option><option value="2000" ${globalSettings.toastDuration === 2000 ? 'selected' : ''}>2 秒</option><option value="3000" ${globalSettings.toastDuration === 3000 ? 'selected' : ''}>3 秒</option></select></div>`;secBehavior.appendChild(rowToast);view.appendChild(secBehavior);// --- 字体管理 ---const secFonts = document.createElement('div');7 行未改动<div class="fs-sv-upload-hint">支持 .woff2 / .woff / .ttf / .otf 格式,全局共享</div>`;secFonts.appendChild(rowUpload);// 已导入字体数量if (customFonts.length > 0) {const rowFontCount = document.createElement('div');rowFontCount.className = 'fs-sv-row';rowFontCount.innerHTML = `<span class="fs-sv-row-label">已导入 ${customFonts.length} 个自定义字体</span><div class="fs-sv-row-right"><button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-clearFonts">全部清除</button></div>`;secFonts.appendChild(rowFontCount);}view.appendChild(secFonts);// --- 数据 ---const secData = document.createElement('div');18 行未改动<button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-resetSite">重置</button></div>`;secData.appendChild(rowResetSite);view.appendChild(secData);// ========== 绑定设置事件 ==========// 按钮大小 — 滑块实时拖动预览const btnSizeRange = document.getElementById('fs-sv-btnSize');const btnSizeVal = document.getElementById('fs-sv-btnSize-val');const btnPreview = document.getElementById('fs-sv-btnPreview');// 初始化滑块进度updateRangeProgress(btnSizeRange);btnSizeRange.addEventListener('input', function() {const val = parseInt(this.value);btnSizeVal.textContent = val + 'px';// 更新滑块进度条颜色updateRangeProgress(this);// 更新预览小圆点const previewPx = Math.max(12, Math.round(val * 0.42));btnPreview.style.width = previewPx + 'px';btnPreview.style.height = previewPx + 'px';// 实时更新实际按钮大小globalSettings.btnSize = val;saveGlobalSettings();refreshDerivedSettings();updateStyles();clampBtnY();applyBtnPosition();});btnSizeRange.addEventListener('change', function() {showToast(`按钮大小已更新为 ${this.value}px`, 'info');});// 排除输入框document.getElementById('fs-sv-excludeInputs').addEventListener('change', function() {globalSettings.excludeInputs = this.checked;saveGlobalSettings();if (activeFontValue && isEnabled) applyFont(activeFontValue);showToast(this.checked ? '已排除输入框' : '输入框将应用字体', 'info');});// 自动吸附收起document.getElementById('fs-sv-autoCollapse').addEventListener('change', function() {globalSettings.autoCollapse = this.checked;saveGlobalSettings();refreshDerivedSettings();if (this.checked) {resetIdleTimer();} else {if (idleTimer) clearTimeout(idleTimer);if (btnCollapsed) expandBtn();}showToast(this.checked ? '已开启自动收起' : '已关闭自动收起', 'info');});// 收起延迟document.getElementById('fs-sv-idleMs').addEventListener('change', function() {globalSettings.idleMs = parseInt(this.value);saveGlobalSettings();refreshDerivedSettings();resetIdleTimer();showToast(`收起延迟已更新`, 'info');});// Toast 时长document.getElementById('fs-sv-toastDuration').addEventListener('change', function() {globalSettings.toastDuration = parseInt(this.value);saveGlobalSettings();showToast(`提示时长已更新`, 'info');});// 上传字体document.getElementById('fs-sv-upload-btn').addEventListener('click', () => {fontFileInput.click();});// 全部清除自定义字体const clearBtn = document.getElementById('fs-sv-clearFonts');if (clearBtn) {clearBtn.addEventListener('click', () => {if (!confirm('确认清除所有自定义字体?此操作不可撤销。')) return;// 移除所有 font-facecustomFonts.forEach(font => {const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));const faceEl = document.getElementById(faceId);if (faceEl) faceEl.remove();removeFontSettings(font.value);});// 如果当前激活的是自定义字体,重置if (customFonts.some(f => f.value === activeFontValue)) {activeFontValue = '';saveToStorage(STORAGE_KEY_ACTIVE_FONT, activeFontValue);applyFont('');}customFonts = [];saveToStorage(STORAGE_KEY_CUSTOM_FONTS, customFonts);renderSettingsView();showToast('已清除所有自定义字体', 'info');});}// 重置按钮位置document.getElementById('fs-sv-resetPos').addEventListener('click', () => {btnSide = 'right';btnY = 60;saveBtnPosition();applyBtnPosition();showToast('按钮位置已重置', 'info');});// 重置当前站点设置document.getElementById('fs-sv-resetSite').addEventListener('click', () => {if (!confirm('确认重置当前站点的所有字体设置?')) return;activeFontValue = '';isEnabled = true;fontSettings = {};saveToStorage(STORAGE_KEY_ACTIVE_FONT, '');saveToStorage(STORAGE_KEY_ENABLED, true);saveToStorage(STORAGE_KEY_FONT_SETTINGS, {});applyFont('');document.getElementById('fs-enabled-toggle').checked = true;expandedSettingsSet.clear();renderFontList();showToast('当前站点设置已重置', 'info');});}// ==================== 设置视图切换 ====================function toggleSettingsView() {settingsViewActive = !settingsViewActive;const listContainer = document.getElementById('fs-font-list');const settingsView = document.getElementById('fs-settings-view');const gearBtn = document.getElementById('fs-header-gear-btn');const toggleRow = panel.querySelector('.fs-toggle-row');if (settingsViewActive) {listContainer.style.display = 'none';toggleRow.style.display = 'none';settingsView.style.display = 'block';gearBtn.classList.add('fs-gear-active');renderSettingsView();} else {listContainer.style.display = '';toggleRow.style.display = '';settingsView.style.display = 'none';2 行未改动}// ==================== 面板控制 ====================function togglePanel() {panelVisible = !panelVisible;if (panelVisible) {// 打开面板时回到字体列表视图if (settingsViewActive) toggleSettingsView();positionPanel();panel.classList.add('fs-show');overlay.classList.add('fs-show');triggerBtn.classList.add('fs-active');if (idleTimer) clearTimeout(idleTimer);} else {panel.classList.remove('fs-show');overlay.classList.remove('fs-show');triggerBtn.classList.remove('fs-active');// 关闭面板时退出设置视图if (settingsViewActive) {settingsViewActive = false;document.getElementById('fs-font-list').style.display = '';panel.querySelector('.fs-toggle-row').style.display = '';document.getElementById('fs-settings-view').style.display = 'none';document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');}resetIdleTimer();}}function closePanel() {if (!panelVisible) return;panelVisible = false;panel.classList.remove('fs-show');overlay.classList.remove('fs-show');triggerBtn.classList.remove('fs-active');if (settingsViewActive) {settingsViewActive = false;document.getElementById('fs-font-list').style.display = '';panel.querySelector('.fs-toggle-row').style.display = '';document.getElementById('fs-settings-view').style.display = 'none';document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');}resetIdleTimer();}// ==================== Toast ====================let toastTimer = null;function showToast(msg, type = 'info') {toast.textContent = msg;toast.className = 'fs-toast-' + type + ' fs-toast-show';if (toastTimer) clearTimeout(toastTimer);toastTimer = setTimeout(() => { toast.classList.remove('fs-toast-show'); }, globalSettings.toastDuration || 2000);}// ==================== 事件绑定 ====================overlay.addEventListener('click', closePanel);panel.querySelector('.fs-header-close').addEventListener('click', closePanel);document.getElementById('fs-header-gear-btn').addEventListener('click', (e) => {e.stopPropagation();toggleSettingsView();});const enabledToggle = document.getElementById('fs-enabled-toggle');enabledToggle.checked = isEnabled;enabledToggle.addEventListener('change', () => {isEnabled = enabledToggle.checked;saveToStorage(STORAGE_KEY_ENABLED, isEnabled);if (isEnabled && activeFontValue) applyFont(activeFontValue);else applyFont('');showToast(isEnabled ? `字体替换已启用(${CURRENT_HOST})` : `字体替换已关闭(${CURRENT_HOST})`, 'info');});fontFileInput.addEventListener('change', (e) => {handleFontFileUpload(e.target.files);e.target.value = '';// 如果设置视图打开着,刷新它if (settingsViewActive) renderSettingsView();});// ==================== 初始化 ====================function initExpandedSettings() {const allFonts = [...PRESET_FONTS, ...customFonts];allFonts.forEach(font => {if (font.value && hasNonDefaultSettings(font.value)) {expandedSettingsSet.add(font.value);}});}function init() {reloadCustomFonts();initExpandedSettings();renderFontList();clampBtnY();applyBtnPosition();if (isEnabled && activeFontValue) applyFont(activeFontValue);setTimeout(() => { triggerBtn.classList.remove('fs-entering'); }, 500);resetIdleTimer();}if (document.readyState === 'complete' || document.readyState === 'interactive') {init();} else {document.addEventListener('DOMContentLoaded', init);}})();```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623073 行未改动231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238017 行未改动2398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248917 行未改动2507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257118 行未改动25902591259225932594259525962597259825999 行未改动260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329045 行未改动291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531669 行未改动3176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432657 行未改动3273327432753276327732783279328032813282328332843285328632873288328932903291329214 行未改动330733083309331033113312331333143315331633173318331933203 行未改动332433253326332733283329333033313332333333343335333633373338333933403341334233433344334530 行未改动33763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934006 行未改动3407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936107 行未改动361836193620362136223623362436253626362736283629363036313632363336343635363618 行未改动365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638272 行未改动383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964配置:下载油猴插件,谷歌浏览器开fq或者下载[安装包](https://pan.quark.cn/s/1ac7209c3f94#/list/share)\点击油猴-->添加新脚本->ctrl+a再ctrl+v然后ctrl+s就行了```js// ==UserScript==// @name Hydro OJ 增强工具 + 网页字体更换器// @namespace https://bzoj.org/// @version 2.5.3// @description 整合 Hydro OJ 测试点大方块(自动轮询、完成通知、亮暗模式适配、总分数垂直对齐,兼容所有 Hydro 系 OJ)、全站网页字体更换器、题目 Markdown 块内查看/复制功能(右上角按钮,可撤销,兼容所有 Hydro 系 OJ,支持在线编程模式)、题目列表「提交」快捷列(仅在题库/比赛/作业/训练列表页显示)、以及比赛/作业成绩表增强(黄色高亮当前用户 + 详细状态方块)// @author bzoj-enhancer & FontSwitcher// @match *://*/*// @grant GM_notification// @grant GM_addStyle// @grant GM_getValue// @grant GM_setValue// @grant GM_setClipboard// @run-at document-idle// @license MIT// ==/UserScript==(function () {'use strict';// ================================================================// 模块一:BZOJ 测试点大方块(仅 bzoj.org 站点下运行)// ================================================================const BZOJ_TestcaseModule = {LIGHT_STATUS_MAP: {'accepted': { bg: '#f6ffed', text: 'AC', display: 'Accepted', color: '#389e0d', border: '#b7eb8f' },'wrong answer': { bg: '#fff2f0', text: 'WA', display: 'Wrong Answer', color: '#cf1322', border: '#ffccc7' },'time limit exceeded': { bg: '#e6f7ff', text: 'TLE', display: 'Time Limit Exceeded', color: '#0958d9', border: '#91d5ff' },'memory limit exceeded': { bg: '#e6f7ff', text: 'MLE', display: 'Memory Limit Exceeded', color: '#0958d9', border: '#91d5ff' },'runtime error': { bg: '#f9f0ff', text: 'RE', display: 'Runtime Error', color: '#722ed1', border: '#d3adf7' },'compile error': { bg: '#fffbe6', text: 'CE', display: 'Compile Error', color: '#d48806', border: '#ffe58f' },'output limit exceeded': { bg: '#e6f7ff', text: 'OLE', display: 'Output Limit Exceeded', color: '#0958d9', border: '#91d5ff' },'system error': { bg: '#f5f5f5', text: 'SE', display: 'System Error', color: '#434343', border: '#d9d9d9' },'judging': { bg: '#e6f7ff', text: '⟳', display: 'Judging', color: '#0958d9', border: '#91d5ff', spin: true },'compiling': { bg: '#e6f7ff', text: '⟳', display: 'Compiling', color: '#0958d9', border: '#91d5ff', spin: true },'waiting': { bg: '#e6f7ff', text: '⟳', display: 'Waiting', color: '#0958d9', border: '#91d5ff', spin: true },'running': { bg: '#e6f7ff', text: '⟳', display: 'Running', color: '#0958d9', border: '#91d5ff', spin: true },'fetched': { bg: '#fff7e6', text: 'FET', display: 'Fetched', color: '#d46b08', border: '#ffd591' },},DARK_STATUS_MAP: {'accepted': { bg: '#1e3a1e', text: 'AC', display: 'Accepted', color: '#95de64', border: '#389e0d' },'wrong answer': { bg: '#3d1f22', text: 'WA', display: 'Wrong Answer', color: '#ff9c9c', border: '#a8071a' },'time limit exceeded': { bg: '#1a2d42', text: 'TLE', display: 'Time Limit Exceeded', color: '#69c0ff', border: '#003a8c' },'memory limit exceeded': { bg: '#1a2d42', text: 'MLE', display: 'Memory Limit Exceeded', color: '#69c0ff', border: '#003a8c' },'runtime error': { bg: '#2d1f3d', text: 'RE', display: 'Runtime Error', color: '#c9a0f5', border: '#531dab' },'compile error': { bg: '#3d321e', text: 'CE', display: 'Compile Error', color: '#ffd666', border: '#ad6800' },'output limit exceeded': { bg: '#1a2d42', text: 'OLE', display: 'Output Limit Exceeded', color: '#69c0ff', border: '#003a8c' },'system error': { bg: '#2e2e2e', text: 'SE', display: 'System Error', color: '#d9d9d9', border: '#434343' },'judging': { bg: '#1a2d42', text: '⟳', display: 'Judging', color: '#69c0ff', border: '#003a8c', spin: true },'compiling': { bg: '#1a2d42', text: '⟳', display: 'Compiling', color: '#69c0ff', border: '#003a8c', spin: true },'waiting': { bg: '#1a2d42', text: '⟳', display: 'Waiting', color: '#69c0ff', border: '#003a8c', spin: true },'running': { bg: '#1a2d42', text: '⟳', display: 'Running', color: '#69c0ff', border: '#003a8c', spin: true },'fetched': { bg: '#3d321e', text: 'FET', display: 'Fetched', color: '#ffc069', border: '#ad4e00' },},ALIAS_MAP: {'time exceeded': 'time limit exceeded', 'memory exceeded': 'memory limit exceeded','ac': 'accepted', 'wa': 'wrong answer', 'tle': 'time limit exceeded','mle': 'memory limit exceeded', 're': 'runtime error', 'ce': 'compile error','ole': 'output limit exceeded', 'se': 'system error',},PENDING_STATES: new Set(['waiting', 'compiling', 'running', 'judging', 'pending', 'queueing', 'fetched']),POLL_INTERVAL: 1.5,lastBannerKey: '',pollTimer: null,lastOverallStatus: '',observer: null,_isDarkCache: false,_observerDebounce: null,_verifyTimer: null,_lastResult: null,isDarkMode: function () {const bgColor = getComputedStyle(document.body).backgroundColor;const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if (match) {const r = parseInt(match[1]);const g = parseInt(match[2]);const b = parseInt(match[3]);const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;return luminance < 0.5;}return false;},normalizeStatus: function (raw) {if (!raw) return '';let text = raw.trim().toLowerCase();if (text.length > 40) {for (const kw of Object.keys(this.ALIAS_MAP).concat(Object.keys(this.LIGHT_STATUS_MAP))) {if (text.includes(kw)) { text = kw; break; }}}if (this.ALIAS_MAP[text]) return this.ALIAS_MAP[text];if (this.LIGHT_STATUS_MAP[text]) return text;for (const key of Object.keys(this.LIGHT_STATUS_MAP)) {if (text.includes(key)) return key;}return text.substring(0, 30);},getStatusInfo: function (key) {const map = this._isDarkCache ? this.DARK_STATUS_MAP : this.LIGHT_STATUS_MAP;return map[key] || {bg: this._isDarkCache ? '#1f1f1f' : '#f5f5f5',text: key.substring(0, 3).toUpperCase(), display: key,color: this._isDarkCache ? '#bfbfbf' : '#434343',border: this._isDarkCache ? '#434343' : '#d9d9d9'};},isFinished: function (key) { return key && !this.PENDING_STATES.has(key); },getOverallStatusKey: function (doc = document) {const primary = doc.querySelector('.record-status--text');if (primary) { const raw = primary.textContent.trim(); if (raw) return this.normalizeStatus(raw); }const dataEl = doc.querySelector('[data-status]');if (dataEl) { const ds = dataEl.getAttribute('data-status'); if (ds) return this.normalizeStatus(ds); }const cells = doc.querySelectorAll('.detail-status, td[class*="status"]');for (const cell of cells) {const text = cell.textContent.trim();if (text.includes('#') && text.includes('ms')) continue;if (text.length < 40 && text.length > 0) return this.normalizeStatus(text);}const bodyText = doc.body.innerText.toLowerCase();for (const kw of ['accepted', 'wrong answer', 'time limit exceeded', 'memory limit exceeded', 'runtime error', 'compile error', 'output limit exceeded', 'system error', 'judging', 'compiling', 'waiting', 'running', 'fetched']) {if (bodyText.includes(kw)) return kw;}return '';},getWorstStatus: function (testcases) {const severity = { 'system error': 10, 'runtime error': 9, 'memory limit exceeded': 8, 'time limit exceeded': 7, 'output limit exceeded': 6, 'wrong answer': 5, 'compile error': 4, 'accepted': 3 };let worst = 'accepted', worstScore = 0;for (const tc of testcases) { const s = severity[tc.key] || 0; if (s > worstScore) { worstScore = s; worst = tc.key; } }return worst;},notifyAndBanner: function (statusKey) {// 仅记录状态,不弹出任何横幅if (statusKey === this.lastBannerKey) return;this.lastBannerKey = statusKey;},getColumnMap: function (table) {const ths = table.querySelectorAll('thead th, thead td');const map = { status: -1, score: -1, time: -1, memory: -1 };if (ths.length > 0) {for (let i = 0; i < ths.length; i++) {const text = ths[i].textContent.trim().toLowerCase();if (text.includes('状态') || text.includes('status')) map.status = i;if (text.includes('分数') || text.includes('score') || text.includes('point')) map.score = i;if (text.includes('耗时') || text.includes('时间') || text.includes('time')) map.time = i;if (text.includes('内存') || text.includes('memory') || text.includes('空间')) map.memory = i;}}const rows = table.querySelectorAll('tbody tr');for (const row of rows) {const cells = row.cells;for (let i = 0; i < cells.length; i++) {const t = cells[i].textContent.trim().toLowerCase();if (map.time < 0 && /\d\s*(ms|sec|秒)/i.test(t) && !/(mib|kib|mb|kb)/i.test(t)) map.time = i;if (map.memory < 0 && /\d\s*(mib|kib|mb|kb)/i.test(t)) map.memory = i;}if (map.time >= 0 && map.memory >= 0) break;}if (map.status < 0) map.status = 1; if (map.score < 0) map.score = 2;if (map.time < 0) map.time = 3; if (map.memory < 0) map.memory = 4;return map;},/** 将分组结果展平为一维测试点数组(用于 getWorstStatus 等旧接口) */flattenResult: function (result) {if (!result) return [];const all = [];for (const g of result.groups) {for (const tc of g.cases) all.push(tc);}return all;},/** 检查分组结果中是否所有测试点均已完成 */isAllFinished: function (result) {if (!result) return true;for (const g of result.groups) {for (const tc of g.cases) {if (!this.isFinished(tc.key)) return false;}}return true;},/** 获取分组结果中第一个测试点的 key(用于 fetched 判断等) */firstCaseKey: function (result) {if (!result || !result.groups.length) return '';const g = result.groups[0];if (g.cases.length > 0) return g.cases[0].key;return g.key;},extractTestCases: function (doc) {const self = this;const isTimeLike = (val) => /\d\s*(ms|sec|秒)/i.test(val) && !/(mib|kib|mb|kb)/i.test(val);const isMemLike = (val) => /\d/.test(val) && /(mib|kib|mb|kb)/i.test(val);const rows = doc.querySelectorAll('table tbody tr');if (rows.length === 0) return null;// ========== 检测是否存在 subtask 分组 ==========// 方式1:通过 CSS class 检测(Hydro OJ 标准 HTML)let hasSubtaskClass = false;for (const row of rows) {if (row.classList && (row.classList.contains('subtask') || row.classList.contains('case') || row.classList.contains('subtask-case'))) {hasSubtaskClass = true;break;}}// 方式2:通过模式检测(#N 行无耗时内存 + #N-M 行有耗时内存 → 有分组)let hasSubtaskPattern = false;if (!hasSubtaskClass) {let subtaskHeaderCount = 0;let caseRowCount = 0;for (const row of rows) {const first = row.cells[0]?.textContent.trim() || '';if (/^#\d+$/.test(first)) {// 检测该行是否缺少 time/memory(即它是 subtask 标题行而非独立测试点)const timeCell = row.cells[3]?.textContent.trim() || '';const memCell = row.cells[4]?.textContent.trim() || '';const rowText = row.textContent;if (!isTimeLike(timeCell) && !isMemLike(memCell) &&!/\d\s*(ms|sec|秒)/i.test(rowText)) {subtaskHeaderCount++;}}if (/^#\d+-\d+$/.test(first)) caseRowCount++;}if (subtaskHeaderCount > 0 && caseRowCount > 0) hasSubtaskPattern = true;}const hasGroups = hasSubtaskClass || hasSubtaskPattern;// ========== 分组提取 ==========if (hasGroups) {return self.extractGroupedRows(rows, hasSubtaskClass, isTimeLike, isMemLike, doc);}// ========== 平铺提取(兼容无分组的页面) ==========let testRows = [];for (const row of rows) { const first = row.cells[0]?.textContent.trim(); if (/^#\d+-\d+$/.test(first)) testRows.push(row); }for (const row of rows) {const first = row.cells[0]?.textContent.trim();if (/^#\d+$/.test(first) && /\d\s*(ms|sec|秒|mib|kib|mb|kb)/i.test(row.textContent)) testRows.push(row);}if (testRows.length === 0) return null;const table = testRows[0].closest('table');const colMap = this.getColumnMap(table);const cases = [];for (const row of testRows) {const cells = row.cells;const id = cells[0]?.textContent.trim() || '?';const statusCell = cells[colMap.status];// 智能提取状态文本:优先从 .record-status--text span 获取(排除 .float-right 的分数)let rawStatus = '';const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)');if (statusSpan) rawStatus = statusSpan.textContent.trim();else rawStatus = statusCell?.textContent.trim() || '';// 智能提取分数:优先从 .float-right span 获取let score = '0';const scoreSpan = statusCell?.querySelector('.float-right');if (scoreSpan) score = scoreSpan.textContent.trim();else {const m = rawStatus.match(/(\d+)\s*$/);if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); }}let time = cells[colMap.time]?.textContent.trim() || '';let memory = cells[colMap.memory]?.textContent.trim() || '';if (!isTimeLike(time)) {for (let i = 1; i < cells.length; i++) {if (i === colMap.status) continue;const t = cells[i]?.textContent.trim() || '';if (isTimeLike(t)) { time = t; break; }}}if (!isMemLike(memory)) {for (let i = 1; i < cells.length; i++) {if (i === colMap.status) continue;const t = cells[i]?.textContent.trim() || '';if (isMemLike(t)) { memory = t; break; }}}cases.push({ id, key: self.normalizeStatus(rawStatus), score, time, memory });}return { hasGroups: false, groups: [{ id: '', key: '', score: '', cases: cases }] };},/** 从含有 subtask 分组的表格行中提取分组数据 */extractGroupedRows: function (rows, useClassNames, isTimeLike, isMemLike, doc) {const self = this;const groups = [];let currentGroup = null;// 尝试获取 colMap:找到含有数据的 tablelet dataTable = null;for (const row of rows) {const t = row.closest('table');if (t) { dataTable = t; break; }}// 也尝试找含 thead 的 table(header table)const root = doc || document;const allTables = root.querySelectorAll('table');let headerTable = null;for (const t of allTables) {if (t.querySelector('thead') && t.querySelector('thead tr')) { headerTable = t; break; }}const colMap = headerTable ? self.getColumnMap(headerTable) : (dataTable ? self.getColumnMap(dataTable) : { status: 1, score: 2, time: 3, memory: 4 });for (const row of rows) {const cells = row.cells;const first = cells[0]?.textContent.trim() || '';const isSubtaskRow = useClassNames? (row.classList && row.classList.contains('subtask')): (/^#\d+$/.test(first) && !isTimeLike(cells[colMap.time]?.textContent.trim() || '') && !isMemLike(cells[colMap.memory]?.textContent.trim() || ''));const isCaseRow = useClassNames? (row.classList && (row.classList.contains('case') || row.classList.contains('subtask-case'))): /^#\d+-\d+$/.test(first);if (isSubtaskRow) {// 提取 subtask 状态和分数const id = first || '?';const statusCell = cells[colMap.status];// 优先从 record-status--text span 获取状态(排除 float-right 的分数)let rawStatus = '';const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)');if (statusSpan) rawStatus = statusSpan.textContent.trim();else rawStatus = statusCell?.textContent.trim() || '';// 提取分数:从 float-right span 或 status 文本末尾数字let score = '';const scoreSpan = statusCell?.querySelector('.float-right');if (scoreSpan) score = scoreSpan.textContent.trim();else {const m = rawStatus.match(/(\d+)\s*$/);if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); }}currentGroup = { id, key: self.normalizeStatus(rawStatus), score, cases: [] };groups.push(currentGroup);} else if (isCaseRow) {const id = first || '?';const statusCell = cells[colMap.status];let rawStatus = '';const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)');if (statusSpan) rawStatus = statusSpan.textContent.trim();else rawStatus = statusCell?.textContent.trim() || '';let score = '';const scoreSpan = statusCell?.querySelector('.float-right');if (scoreSpan) score = scoreSpan.textContent.trim();else {const m = rawStatus.match(/(\d+)\s*$/);if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); }}let time = cells[colMap.time]?.textContent.trim() || '';let memory = cells[colMap.memory]?.textContent.trim() || '';// 校验 time/memoryif (!isTimeLike(time)) {for (let i = 1; i < cells.length; i++) {if (i === colMap.status) continue;const t = cells[i]?.textContent.trim() || '';if (isTimeLike(t)) { time = t; break; }}}if (!isMemLike(memory)) {for (let i = 1; i < cells.length; i++) {if (i === colMap.status) continue;const t = cells[i]?.textContent.trim() || '';if (isMemLike(t)) { memory = t; break; }}}const tc = { id, key: self.normalizeStatus(rawStatus), score, time, memory };// 如果没有当前分组,创建一个默认分组if (!currentGroup) {currentGroup = { id: '', key: '', score: '', cases: [] };groups.push(currentGroup);}currentGroup.cases.push(tc);}}if (groups.length === 0) return null;return { hasGroups: groups.length > 1 || (groups.length === 1 && groups[0].id !== ''), groups: groups };},updateBlocks: function (result) {const self = this;// ========== 隐藏原始表格 ==========self._hideTables();self._isDarkCache = self.isDarkMode();const isDark = self._isDarkCache;// ========== 创建/更新容器 ==========let container = document.getElementById('bzoj-testcase-blocks');if (!container) {container = document.createElement('div');container.id = 'bzoj-testcase-blocks';container.style.cssText = `margin: 16px 0; padding: 14px; border-radius: 12px; background: ${isDark ? '#323334' : '#ffffff'}; border: none;`;const statusEl = document.querySelector('.record-status--text') || document.querySelector('[data-status]');const statusSection = statusEl?.closest('.section');const testCaseTable = Array.from(document.querySelectorAll('table')).find(t => {const rows = t.querySelectorAll('tbody tr');for (const row of rows) {const first = row.cells[0]?.textContent.trim();if (first && /^#\d+(-\d+)?$/.test(first)) return true;}return false;});let inserted = false;// 策略1:插入到状态 section 之后if (statusSection && statusSection.parentElement) {if (statusSection.nextElementSibling) {statusSection.parentElement.insertBefore(container, statusSection.nextElementSibling);} else {statusSection.parentElement.appendChild(container);}inserted = true;}// 策略2:插入到测试点表格的 section 级祖先之前if (!inserted && testCaseTable) {const sectionAncestor = testCaseTable.closest('.section') ||testCaseTable.closest('[class*="section"]') ||testCaseTable.closest('.section__table-container')?.parentElement;if (sectionAncestor && sectionAncestor.parentElement) {sectionAncestor.parentElement.insertBefore(container, sectionAncestor);inserted = true;}}if (!inserted) {const recordContainer = document.querySelector('.record-container');if (recordContainer && recordContainer.parentElement) {recordContainer.parentElement.insertBefore(container, recordContainer);} else {(document.querySelector('.page-content') || document.querySelector('main') || document.body).prepend(container);}}} else {container.style.background = isDark ? '#323334' : '#ffffff';}container.innerHTML = '';let allFinished = true;// ========== 渲染分组 ==========for (let gi = 0; gi < result.groups.length; gi++) {const group = result.groups[gi];// 分组区块const groupSection = document.createElement('div');groupSection.className = 'bzoj-group-section';groupSection.style.cssText = gi < result.groups.length - 1? 'margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid ' + (isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)') + ';': 'margin-bottom: 0;';// 分组标题(仅在有分组时显示)if (result.hasGroups && group.id) {const groupInfo = self.getStatusInfo(group.key);const header = document.createElement('div');header.className = 'bzoj-group-header';header.style.cssText = `display: flex; align-items: center; gap: 8px; padding: 6px 10px; margin-bottom: 10px; border-radius: 8px; font-size: 13px; font-weight: 600; font-family: system-ui, -apple-system, sans-serif; background: ${isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.025)'}; color: ${groupInfo.color}; border-left: 3px solid ${groupInfo.border};`;const idSpan = document.createElement('span');idSpan.textContent = group.id;header.appendChild(idSpan);if (group.score) {const scoreSpan = document.createElement('span');scoreSpan.style.cssText = `opacity: 0.65; font-weight: 500;`;scoreSpan.textContent = '\u00B7 ' + group.score + ' \u5206';header.appendChild(scoreSpan);}const statusSpan = document.createElement('span');statusSpan.style.cssText = `font-weight: 500; opacity: 0.8; margin-left: auto;`;statusSpan.textContent = groupInfo.display;header.appendChild(statusSpan);groupSection.appendChild(header);}// 测试点方块容器const casesRow = document.createElement('div');casesRow.style.cssText = 'display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-start;';for (const tc of group.cases) {if (!self.isFinished(tc.key)) allFinished = false;const info = self.getStatusInfo(tc.key);const block = document.createElement('div');block.className = 'bzoj-testcase-block';block.style.cssText = `display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100px; height: 100px; font-weight: bold; background: ${info.bg}; color: ${info.color}; border: 1px solid ${info.border}; border-radius: 10px; cursor: default; font-family: system-ui, -apple-system, sans-serif; position: relative; overflow: hidden;`;const num = document.createElement('span');num.style.cssText = `position: absolute; top: 6px; left: 8px; font-size: 11px; font-weight: 500; color: ${isDark ? 'rgba(255,255,255,0.65)' : 'rgba(0,0,0,0.45)'}; line-height: 1; max-width: calc(100% - 12px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;`;num.textContent = tc.id;block.appendChild(num);// 得分标签(右上角,包括 0 分也显示)if (tc.score !== undefined && tc.score !== null && tc.score !== '') {const scoreTag = document.createElement('span');scoreTag.style.cssText = `position: absolute; top: 5px; right: 7px; font-size: 11px; font-weight: 600; color: ${info.color}; opacity: 0.75; line-height: 1;`;scoreTag.textContent = tc.score;block.appendChild(scoreTag);}const statusSpan = document.createElement('span');statusSpan.style.cssText = 'font-size:24px; font-weight:normal; margin-bottom:4px;';if (info.spin) { statusSpan.textContent = info.text; statusSpan.style.animation = 'bzoj-spin 1.5s linear infinite'; }else statusSpan.textContent = info.text;block.appendChild(statusSpan);// 详细信息行:耗时 / 内存,始终显示const detail = document.createElement('span');detail.style.cssText = `font-size:11px; font-weight:normal; text-align:center; white-space:normal; word-break:break-all; color: ${isDark ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.45)'}; line-height: 1.3; max-width: 90px;`;let dt = '';if (tc.time && tc.memory) dt = `${tc.time} / ${tc.memory}`;else if (tc.time) dt = tc.time;else if (tc.memory) dt = tc.memory;else if (info.spin) dt = 'waiting...';detail.textContent = dt;block.appendChild(detail);casesRow.appendChild(block);}groupSection.appendChild(casesRow);container.appendChild(groupSection);}// 评测中提示if (!allFinished) {const hint = document.createElement('div');hint.textContent = '\u23F3 评测进行中...';hint.style.cssText = `margin-top: 10px; color:${isDark ? '#69b1ff' : '#0958d9'}; font-size:14px; font-family: system-ui, -apple-system, sans-serif;`;container.appendChild(hint);}return allFinished;},pollStatus: async function () {const self = this;try {const resp = await fetch(window.location.href, { credentials: 'same-origin' });const html = await resp.text();const doc = new DOMParser().parseFromString(html, 'text/html');const newResult = self.extractTestCases(doc);if (newResult) {// 数据没变就不重建,避免鬼畜const changed = !self._resultEquals(newResult, self._lastResult);self._lastResult = newResult;const allDone = changed ? self.updateBlocks(newResult) : self.isAllFinished(newResult);const flatCases = self.flattenResult(newResult);if (allDone && flatCases.length > 0) { clearInterval(self.pollTimer); self.pollTimer = null; self.notifyAndBanner(self.getOverallStatusKey(doc) || self.getWorstStatus(flatCases)); }else { if (self.firstCaseKey(newResult) === 'fetched') self.notifyAndBanner('fetched'); }} else {const overall = self.getOverallStatusKey(doc);if (overall) {if (self.isFinished(overall)) { clearInterval(self.pollTimer); self.pollTimer = null; self.notifyAndBanner(overall); }else if (overall !== self.lastOverallStatus) { self.notifyAndBanner(overall); self.lastOverallStatus = overall; }}}} catch (e) { console.error('[BZOJ轮询] 网络错误', e); }},startPolling: function () {if (this.pollTimer) return;this.pollTimer = setInterval(() => this.pollStatus(), this.POLL_INTERVAL * 1000);},/** 处理 MutationObserver 回调(防抖后调用) */_handleMutation: function () {const self = this;const container = document.getElementById('bzoj-testcase-blocks');if (!container) {// 容器被 Hydro 重建 DOM 时销毁了,需要重新提取并渲染const result = self.extractTestCases(document);if (result) {self._lastResult = result;self.updateBlocks(result);} else if (self._lastResult) {setTimeout(() => {const retry = self.extractTestCases(document);if (retry) { self._lastResult = retry; self.updateBlocks(retry); }else { self.updateBlocks(self._lastResult); }}, 500);}} else {// 容器还在,只需确保表格隐藏self._hideTables();// 只有当数据真的变化了才重建方块,避免反复重建导致鬼畜const result = self.extractTestCases(document);if (result && !self._resultEquals(result, self._lastResult)) {self._lastResult = result;self.updateBlocks(result);}}},/** 比较两次提取结果是否相同,避免无意义的重建 */_resultEquals: function (a, b) {if (!a || !b) return false;if (a.hasGroups !== b.hasGroups) return false;if (a.groups.length !== b.groups.length) return false;for (let i = 0; i < a.groups.length; i++) {const ga = a.groups[i], gb = b.groups[i];if (ga.id !== gb.id || ga.key !== gb.key || ga.score !== gb.score) return false;if (ga.cases.length !== gb.cases.length) return false;for (let j = 0; j < ga.cases.length; j++) {const ca = ga.cases[j], cb = gb.cases[j];if (ca.id !== cb.id || ca.key !== cb.key || ca.score !== cb.score ||ca.time !== cb.time || ca.memory !== cb.memory) return false;}}return true;},/** 隐藏原始测试点表格及相关容器(使用 CSS class,配合 !important 规则) */_hideTables: function () {const tables = document.querySelectorAll('table');for (const t of tables) {const rows = t.querySelectorAll('tbody tr');for (const row of rows) {const first = row.cells[0]?.textContent.trim();if (first && /^#\d+(-\d+)?$/.test(first)) {t.classList.add('bzoj-hide-table');break;}}}// 隐藏粘性表头表格(Hydro OJ 会在数据表上方生成一个 position:sticky 的表头表)const headerTables = document.querySelectorAll('table.section__table-header');for (const t of headerTables) { t.classList.add('bzoj-hide-table'); }const tableContainers = document.querySelectorAll('.section__table-container');for (const tc of tableContainers) { tc.classList.add('bzoj-hide-container'); }// 隐藏包含测试点表格的 .section__body.no-padding(避免空表格留下空白)const noPaddingBodies = document.querySelectorAll('.section__body.no-padding');for (const body of noPaddingBodies) {if (body.querySelector('table') || body.querySelector('.section__table-container')) {body.classList.add('bzoj-hide-section-body');}}},/** 周期性验证容器是否仍然存在(兜底机制) */_startVerifyTimer: function () {const self = this;if (self._verifyTimer) return;self._verifyTimer = setInterval(() => {const container = document.getElementById('bzoj-testcase-blocks');if (!container) {// 容器被销毁了,尝试重建const result = self.extractTestCases(document);if (result) {self._lastResult = result;self.updateBlocks(result);} else if (self._lastResult) {self.updateBlocks(self._lastResult);}} else {// 容器还在,确保表格仍然隐藏self._hideTables();}}, 2000);},installObserver: function () {const self = this;if (this.observer) return;this.observer = new MutationObserver(() => {// 立即隐藏表格(不防抖,避免闪烁)self._hideTables();// 重建方块需要防抖,等 DOM 稳定后再处理clearTimeout(self._observerDebounce);self._observerDebounce = setTimeout(() => {self._handleMutation();}, 300);});this.observer.observe(document.body, { attributes: true, attributeFilter: ['style'] });this.observer.observe(document.head, { childList: true });this.observer.observe(document.body, { childList: true, subtree: true });// 启动周期性验证作为兜底self._startVerifyTimer();},init: function () {// 自动检测 Hydro OJ 记录详情页(兼容 bzoj.org / hydro.ac 及所有 Hydro 系 OJ)// 1. 路径匹配:/record/[id] 或 /d/[domain]/record/[id]if (!/\/record\/\w+/.test(window.location.pathname)) return;// 2. 结构检测:页面是否有 Hydro 特征元素const hasHydroElements = document.querySelector('.record-status--text') ||document.querySelector('[data-status]') ||document.querySelector('.record-container');if (!hasHydroElements) return;const self = this;GM_addStyle(`@keyframes bzoj-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }.bzoj-testcase-block { transition: box-shadow 0.2s, background 0.3s, color 0.3s, border-color 0.3s; }.bzoj-testcase-block:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.18); }table thead { display: none !important; }/* 用 CSS !important 强制隐藏测试点表格及容器,即使 Hydro 重建 DOM 也立即生效,避免闪烁 */.bzoj-hide-table { display: none !important; }.bzoj-hide-container { display: none !important; }.bzoj-hide-section-body { display: none !important; }/* ============ 修复 record 状态栏框太扁的问题 ============ *//* Hydro 的 record 状态栏 <h1 class="section__title"> 内有图标、分数、状态文本,默认 section__header 的 padding 不足,导致框太扁、内容显得没居中。策略:增加 section__header 的上下 padding,让框变高,内容自然垂直居中。 *//* 1. 增加 section__header 的上下 padding,让框变高 */#status > .section__header,.section[data-status] > .section__header {padding-top: 14px !important;padding-bottom: 14px !important;}/* 2. 让状态栏 h1 使用 flex 居中 */#status .section__title,.section[data-status] > .section__header > .section__title {display: flex !important;align-items: center !important;gap: 8px !important;line-height: 1.4 !important;margin: 0 !important;}/* 3. 所有子元素统一为 inline-block + 垂直居中 */#status .section__title > *,.section[data-status] > .section__header > .section__title > * {display: inline-block !important;vertical-align: middle !important;align-self: center !important;line-height: 1.4 !important;margin-top: 0 !important;margin-bottom: 0 !important;}/* 4. 图标保留 Hydro 原有尺寸 */#status .section__title .record-status--icon,.section[data-status] .section__title .record-status--icon {flex-shrink: 0 !important;line-height: 1 !important;}`);const initialResult = self.extractTestCases(document);if (initialResult) {self._lastResult = initialResult;const allDone = self.updateBlocks(initialResult);const flatCases = self.flattenResult(initialResult);if (!allDone) { self.startPolling(); if (self.firstCaseKey(initialResult) === 'fetched') self.notifyAndBanner('fetched'); }else self.notifyAndBanner(self.getOverallStatusKey() || self.getWorstStatus(flatCases));} else {const overall = self.getOverallStatusKey();if (overall) {if (self.isFinished(overall)) self.notifyAndBanner(overall);else { self.notifyAndBanner(overall); self.startPolling(); }} else {setTimeout(() => {const retry = self.getOverallStatusKey();if (retry) { if (self.isFinished(retry)) self.notifyAndBanner(retry); else { self.notifyAndBanner(retry); self.startPolling(); } }}, 1000);}}self.installObserver();}};// ================================================================// 模块二:BZOJ 题目 Markdown 查看/复制(仅题目详情页运行)// 适用页面:// - https://bzoj.org/p/<id> (独立题目页,<id> 可为 P06668 或 1576 等形式)// - https://bzoj.org/p/<id>?tid=<hex>(比赛题目页,例如 ?tid=69e2d8fe07068fa389942a8a)// 在题目页面右侧菜单注入「查看 / 复制 Markdown」入口;// 点击后弹出模态框显示题面 HTML 转换得到的 Markdown 源码,// 支持「复制到剪贴板」「下载 .md」「在线编辑」。// ================================================================const BZOJ_ProblemMarkdownModule = {_modal: null,_lastMarkdown: '',init: function () {// 自动检测 Hydro OJ 题目详情页(兼容 bzoj.org / hydro.ac 及所有 Hydro 系 OJ)// 1. 路径匹配:/p/[id] 或 /d/[domain]/p/[id](排除 /p/[id]/submit、/p/[id]/solution 等子路径)const path = window.location.pathname;const match = path.match(/\/p\/([^\/]+)$/);if (!match) return;// 2. 结构检测:页面是否有 Hydro 题目特征元素const hasHydroElements = document.querySelector('.problem-content') ||document.querySelector('[data-fragment-id="problem-description"]') ||document.querySelector('.problem-content-container');if (!hasHydroElements) return;// 3. 排除 iframe 等嵌套文档if (window.top !== window.self) return;const self = this;GM_addStyle(`.bzoj-md-fab {position: fixed; right: 24px; bottom: 96px; z-index: 9999;padding: 10px 18px; border: none; border-radius: 22px;background: #56758f; color: #fff; font-size: 13px; font-weight: 600;cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.2);transition: transform .15s, box-shadow .15s, background .15s;font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;letter-spacing: .3px;}.bzoj-md-fab:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0,0,0,0.3); background: #46637a; }.bzoj-md-modal-backdrop {position: fixed; inset: 0; z-index: 10000;background: rgba(0,0,0,0.55); display: flex; align-items: center; justify-content: center;opacity: 0; transition: opacity .2s ease; padding: 24px 16px;}.bzoj-md-modal-backdrop.bzoj-show { opacity: 1; }.bzoj-md-modal {background: #fff; color: #333; width: min(960px, 100%); height: min(82vh, 760px);border-radius: 12px; display: flex; flex-direction: column; overflow: hidden;box-shadow: 0 24px 60px rgba(0,0,0,0.35);transform: translateY(8px); transition: transform .2s ease;}.bzoj-md-modal-backdrop.bzoj-show .bzoj-md-modal { transform: translateY(0); }.bzoj-md-modal-header {padding: 14px 18px; border-bottom: 1px solid #eee;display: flex; align-items: center; justify-content: space-between;background: #fafafa; flex-shrink: 0;}.bzoj-md-modal-title { font-size: 15px; font-weight: 600; color: #333; display: flex; align-items: center; gap: 8px; }.bzoj-md-modal-title .bzoj-md-title-tag {display: inline-block; padding: 1px 8px; border-radius: 4px;background: #56758f; color: #fff; font-size: 11px; font-weight: 600; letter-spacing: .5px;}.bzoj-md-modal-subtitle { font-size: 12px; color: #888; font-weight: 400; margin-left: 6px; }.bzoj-md-modal-close {background: transparent; border: none; cursor: pointer; font-size: 22px;color: #999; line-height: 1; padding: 4px 8px; border-radius: 6px;font-family: inherit;}.bzoj-md-modal-close:hover { background: #eee; color: #333; }.bzoj-md-modal-toolbar {padding: 10px 14px; border-bottom: 1px solid #f0f0f0;display: flex; gap: 8px; background: #fafafa; flex-wrap: wrap; align-items: center; flex-shrink: 0;}.bzoj-md-btn {padding: 6px 14px; border: 1px solid #d9d9d9; border-radius: 6px;background: #fff; color: #333; font-size: 13px; cursor: pointer;transition: all .15s; font-family: inherit; line-height: 1.4;}.bzoj-md-btn:hover { border-color: #56758f; color: #56758f; }.bzoj-md-btn--primary { background: #56758f; color: #fff; border-color: #56758f; }.bzoj-md-btn--primary:hover { background: #46637a; color: #fff; border-color: #46637a; }.bzoj-md-btn--ghost { background: transparent; }.bzoj-md-modal-toolbar .bzoj-md-spacer { flex: 1; }.bzoj-md-modal-toolbar .bzoj-md-meta { font-size: 12px; color: #888; }.bzoj-md-modal-body { flex: 1; overflow: auto; padding: 0; min-height: 0; }.bzoj-md-textarea {width: 100%; height: 100%; border: none; outline: none; resize: none;padding: 16px 18px; font-family: "JetBrains Mono", "Cascadia Code", Consolas, "Source Code Pro", "Microsoft YaHei", monospace;font-size: 13px; line-height: 1.6; color: #333; background: #fff;white-space: pre; overflow-wrap: normal; tab-size: 4;}.bzoj-md-toast {position: fixed; bottom: 32px; left: 50%; transform: translateX(-50%) translateY(20px);background: #333; color: #fff; padding: 10px 20px; border-radius: 24px;font-size: 13px; z-index: 10001; opacity: 0; transition: all .25s ease;box-shadow: 0 6px 20px rgba(0,0,0,0.25); pointer-events: none;font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;}.bzoj-md-toast.bzoj-show { opacity: 1; transform: translateX(-50%) translateY(0); }/* 暗色模式适配 —— Hydro 使用 .theme--dark 或 data-mantine-color-scheme="dark" */.theme--dark .bzoj-md-modal,html[data-mantine-color-scheme="dark"] .bzoj-md-modal,.theme--dark.bzoj-md-modal {background: #1f1f1f; color: #ddd; box-shadow: 0 24px 60px rgba(0,0,0,0.6);}.theme--dark .bzoj-md-modal-header,html[data-mantine-color-scheme="dark"] .bzoj-md-modal-header,.theme--dark .bzoj-md-modal-toolbar {background: #262626; border-color: #333;}.theme--dark .bzoj-md-modal-title,html[data-mantine-color-scheme="dark"] .bzoj-md-modal-title { color: #eee; }.theme--dark .bzoj-md-modal-subtitle,html[data-mantine-color-scheme="dark"] .bzoj-md-modal-subtitle { color: #999; }.theme--dark .bzoj-md-textarea,html[data-mantine-color-scheme="dark"] .bzoj-md-textarea {background: #1f1f1f; color: #ddd;}.theme--dark .bzoj-md-btn,html[data-mantine-color-scheme="dark"] .bzoj-md-btn {background: #333; color: #ddd; border-color: #444;}.theme--dark .bzoj-md-btn:hover,html[data-mantine-color-scheme="dark"] .bzoj-md-btn:hover {border-color: #56758f; color: #8eb3d0;}.theme--dark .bzoj-md-btn--primary,html[data-mantine-color-scheme="dark"] .bzoj-md-btn--primary {background: #56758f; color: #fff; border-color: #56758f;}.theme--dark .bzoj-md-btn--primary:hover,html[data-mantine-color-scheme="dark"] .bzoj-md-btn--primary:hover {background: #46637a; color: #fff; border-color: #46637a;}.theme--dark .bzoj-md-modal-close,html[data-mantine-color-scheme="dark"] .bzoj-md-modal-close { color: #888; }.theme--dark .bzoj-md-modal-close:hover,html[data-mantine-color-scheme="dark"] .bzoj-md-modal-close:hover { background: #333; color: #ddd; }.theme--dark .bzoj-md-toast,html[data-mantine-color-scheme="dark"] .bzoj-md-toast {background: #ddd; color: #222;}/* ============ 题目块右上角浮动按钮组 ============ */.bzoj-md-actions {position: absolute; top: 8px; right: 10px; z-index: 50;display: flex; gap: 6px; align-items: center;font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;}.bzoj-md-action-btn {display: inline-flex; align-items: center; gap: 4px;padding: 4px 10px; border: 1px solid rgba(86,117,143,0.35);border-radius: 5px; background: rgba(255,255,255,0.92);color: #56758f; font-size: 12px; font-weight: 600;cursor: pointer; transition: all .15s; font-family: inherit;line-height: 1.4; backdrop-filter: blur(4px);box-shadow: 0 1px 3px rgba(0,0,0,0.08);}.bzoj-md-action-btn:hover {background: #56758f; color: #fff; border-color: #56758f;box-shadow: 0 2px 6px rgba(86,117,143,0.3);}.bzoj-md-action-btn--active {background: #56758f; color: #fff; border-color: #56758f;}.bzoj-md-action-btn .bzoj-md-action-icon {display: inline-flex; align-items: center; justify-content: center;width: 12px; height: 12px; font-size: 11px; font-weight: 700; line-height: 1;}/* 暗色模式适配 */.theme--dark .bzoj-md-action-btn,html[data-mantine-color-scheme="dark"] .bzoj-md-action-btn {background: rgba(42,42,42,0.92); color: #8eb3d0;border-color: rgba(142,179,208,0.35);}.theme--dark .bzoj-md-action-btn:hover,html[data-mantine-color-scheme="dark"] .bzoj-md-action-btn:hover,.theme--dark .bzoj-md-action-btn--active,html[data-mantine-color-scheme="dark"] .bzoj-md-action-btn--active {background: #56758f; color: #fff; border-color: #56758f;}/* ============ 块内 MD 源码视图(替换题面 HTML) ============ *//* 透明背景 + 继承字号,直接融入题目块容器,不出现单独的「灰色框」 */.bzoj-md-inline-view {padding: 0; margin: 0;font-family: "JetBrains Mono", "Cascadia Code", Consolas, "Source Code Pro", "Microsoft YaHei", monospace;font-size: inherit; line-height: inherit;white-space: pre-wrap; word-break: break-word; overflow-wrap: anywhere;background: transparent; border: none; border-radius: 0;color: inherit;overflow: visible;}.theme--dark .bzoj-md-inline-view,html[data-mantine-color-scheme="dark"] .bzoj-md-inline-view {background: transparent; color: inherit;}.bzoj-md-restored-banner {display: flex; align-items: center; gap: 8px;padding: 8px 14px; margin-bottom: 10px;background: rgba(86,117,143,0.08); border-radius: 6px;font-size: 12px; color: #56758f; font-weight: 500;font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;}.theme--dark .bzoj-md-restored-banner,html[data-mantine-color-scheme="dark"] .bzoj-md-restored-banner {background: rgba(255,255,255,0.06); color: #8eb3d0;}`);// 在题目块右上角注入两个浮动按钮self.addActionButtons();// 在题目右侧菜单注入入口;若没有侧边栏则降级为悬浮按钮const menu = document.querySelector('.section--problem-sidebar .menu');if (menu) {self.addSidebarButton(menu);} else {self.addFloatingButton();}// 监听 DOM 变化:用户进入/退出在线编程模式(scratchpad)时重新注入按钮self._installModeObserver();},/** 在题目块右上角注入两个浮动按钮:「显示 MD」「复制 MD」 */addActionButtons: function () {const self = this;// 移除已存在但已失效的按钮(如 scratchpad 模式切换导致旧按钮在隐藏容器中)const existing = document.querySelector('.bzoj-md-actions');if (existing) {const parent = existing.parentElement;if (parent) {const cs = getComputedStyle(parent);const invisible = cs.display === 'none' || parseFloat(cs.opacity) < 0.1;if (invisible) existing.remove();else return; // 已有可见按钮,不重复注入}}// 定位题目内容容器:优先 scratchpad 模式下的可见 .problem-content,// 其次普通模式的 .problem-content-containerconst scratchpadContent = document.querySelector('.scratchpad__problem .problem-content, .scratchpad__problem [data-fragment-id="problem-description"]');const anchor =scratchpadContent ||document.querySelector('.problem-content-container') ||(document.querySelector('.problem-content')?.closest('.section')) ||document.querySelector('.problem-content');if (!anchor) return;// 确保锚点容器支持相对定位(让按钮的 absolute 生效)const computedPos = getComputedStyle(anchor).position;if (computedPos === 'static' || !computedPos) {anchor.style.position = 'relative';}const actions = document.createElement('div');actions.className = 'bzoj-md-actions';// 按钮 1:显示 MD —— 在块内切换显示 Markdown 源码(可撤销)const viewBtn = document.createElement('button');viewBtn.type = 'button';viewBtn.className = 'bzoj-md-action-btn';viewBtn.innerHTML = '<span class="bzoj-md-action-icon">M</span> 显示 MD';viewBtn.title = '在题面块内直接显示 Markdown 源码(再次点击恢复原题面)';viewBtn.addEventListener('click', function () { self.toggleInlineMd(viewBtn); });actions.appendChild(viewBtn);// 按钮 2:复制 MD —— 直接复制到剪贴板const copyBtn = document.createElement('button');copyBtn.type = 'button';copyBtn.className = 'bzoj-md-action-btn';copyBtn.innerHTML = '<span class="bzoj-md-action-icon">\u2398</span> 复制 MD';copyBtn.title = '将题目的 Markdown 源码复制到剪贴板';copyBtn.addEventListener('click', function () { self.copyMarkdownDirectly(); });actions.appendChild(copyBtn);anchor.appendChild(actions);},/** 安装模式切换监听器:scratchpad 模式切换时重新注入按钮 */_installModeObserver: function () {const self = this;if (self._mdObserver) return;self._mdObserver = new MutationObserver(function () {clearTimeout(self._mdObserverDebounce);self._mdObserverDebounce = setTimeout(function () {self.addActionButtons();}, 200);});self._mdObserver.observe(document.body, { attributes: true, attributeFilter: ['class'] });self._mdObserver.observe(document.body, { childList: true, subtree: true });},/*** 在题面块内切换 Markdown 源码视图(可撤销)。* - 首次点击:保存原始 HTML,将题面正文替换为 <pre class="bzoj-md-inline-view"> 显示 MD 源码* - 再次点击:恢复原始 HTML*/_inlineMdState: null, // { originalHtml, viewEl, anchor }toggleInlineMd: function (btn) {const self = this;// 定位题面正文容器(优先 scratchpad 模式下的可见题面)const fragment =document.querySelector('.scratchpad__problem [data-fragment-id="problem-description"]') ||document.querySelector('.scratchpad__problem .problem-content .section__body') ||document.querySelector('.scratchpad__problem .problem-content') ||document.querySelector('[data-fragment-id="problem-description"]') ||document.querySelector('.problem-content .section__body') ||document.querySelector('.problem-content');if (!fragment) {self.showToast('未找到题面内容', 'error');return;}// 如果当前已是 MD 视图,则恢复原题面if (self._inlineMdState && self._inlineMdState.active) {self._restoreInlineMd(btn);return;}// 生成 Markdown 源码const md = self.getProblemMarkdown();if (!md || !md.trim()) {self.showToast('未提取到题面内容', 'error');return;}// 保存原始 HTML,用于撤销self._inlineMdState = {active: true,originalHtml: fragment.innerHTML,fragment: fragment,};// 用 MD 源码替换题面内容fragment.innerHTML = '';const pre = document.createElement('pre');pre.className = 'bzoj-md-inline-view';pre.textContent = md;fragment.appendChild(pre);// 按钮状态切换btn.classList.add('bzoj-md-action-btn--active');btn.innerHTML = '<span class="bzoj-md-action-icon">\u21BA</span> 恢复原题';btn.title = '恢复题面原始 HTML 渲染';self.showToast('已切换为 Markdown 源码视图');},/** 恢复题面原始 HTML */_restoreInlineMd: function (btn) {const self = this;if (!self._inlineMdState || !self._inlineMdState.active) return;const state = self._inlineMdState;try {state.fragment.innerHTML = state.originalHtml;} catch (e) {console.error('[BZOJ-MD] 恢复题面失败', e);}self._inlineMdState = null;// 按钮状态切换回「显示 MD」btn.classList.remove('bzoj-md-action-btn--active');btn.innerHTML = '<span class="bzoj-md-action-icon">M</span> 显示 MD';btn.title = '在题面块内直接显示 Markdown 源码(再次点击恢复原题面)';self.showToast('已恢复题面原始渲染');},/** 暗色模式检测:优先检查 Hydro 的 theme class,再回退到 body 背景亮度判断 */_detectDarkMode: function () {// 1. 优先检查 Hydro 的显式 class / 属性(最可靠,且在首帧即可用)const html = document.documentElement;if (html.classList.contains('theme--dark')) return true;if (html.classList.contains('theme--light')) return false;if (html.getAttribute('data-mantine-color-scheme') === 'dark') return true;if (html.getAttribute('data-mantine-color-scheme') === 'light') return false;if (document.body.classList.contains('theme--dark')) return true;// 2. 兜底:通过 body 背景亮度判断try {const bgColor = getComputedStyle(document.body).backgroundColor;const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if (match) {const r = parseInt(match[1]);const g = parseInt(match[2]);const b = parseInt(match[3]);const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;return luminance < 0.5;}} catch (e) { /* ignore */ }return false;},/** 直接复制 Markdown 到剪贴板(不弹模态框) */copyMarkdownDirectly: function () {const self = this;const md = self.getProblemMarkdown();if (!md || !md.trim()) {self.showToast('未提取到题面内容', 'error');return;}self.copyToClipboard(md, null);},addSidebarButton: function (menu) {const self = this;if (menu.querySelector('[data-bzoj-md-btn]')) return; // 防止重复注入const li = document.createElement('li');li.className = 'menu__item scratchpad--hide';const a = document.createElement('a');a.className = 'menu__link';a.href = 'javascript:;';a.setAttribute('data-bzoj-md-btn', '1');a.title = '查看题目正文的 Markdown 源码,并复制到剪贴板';a.innerHTML = '<span class="icon" style="display:inline-block;width:14px;text-align:center;font-weight:700;font-size:12px;">M</span> 查看 / 复制 Markdown';a.addEventListener('click', function (e) { e.preventDefault(); self.showModal(); });li.appendChild(a);menu.appendChild(li);},addFloatingButton: function () {const self = this;if (document.querySelector('.bzoj-md-fab')) return;const btn = document.createElement('button');btn.type = 'button';btn.className = 'bzoj-md-fab';btn.textContent = '查看 MD';btn.addEventListener('click', function () { self.showModal(); });document.body.appendChild(btn);},/** 提取题面 HTML 并转换为 Markdown */getProblemMarkdown: function () {// 优先 scratchpad 模式下的可见题面,其次普通模式const fragment =document.querySelector('.scratchpad__problem [data-fragment-id="problem-description"]') ||document.querySelector('.scratchpad__problem .problem-content .section__body') ||document.querySelector('.scratchpad__problem .problem-content') ||document.querySelector('[data-fragment-id="problem-description"]') ||document.querySelector('.problem-content .section__body') ||document.querySelector('.problem-content');if (!fragment) return '';// 克隆后剔除工具栏(Copy / 填充到自测 等按钮)以及 KaTeX 渲染层,只保留源 LaTeXconst clone = fragment.cloneNode(true);clone.querySelectorAll('.toolbar, .scratchpad-fill-button, .toolbar-item').forEach(function (el) { el.remove(); });// 让 KaTeX 保留原始 LaTeX:把 <annotation> 的文本塞入 katex 容器,并移除其余渲染节点clone.querySelectorAll('.katex').forEach(function (katex) {const anno = katex.querySelector('annotation[encoding="application/x-tex"]');if (anno) {const tex = anno.textContent;katex.innerHTML = '';katex.textContent = tex;}});// MathJax 类似的处理:保留 <script type="math/tex"> 内容clone.querySelectorAll('script[type="math/tex"], script[type="math/tex; mode=display"]').forEach(function (s) {const txt = s.textContent;const span = document.createElement('span');span.textContent = txt;s.parentNode.replaceChild(span, s);});return this.htmlToMarkdown(clone).trim() + '\n';},/** 简易 HTML→Markdown 转换器,覆盖 Hydro 题面常见元素 */htmlToMarkdown: function (root) {const self = this;function absolutize(url) {try { return new URL(url, location.href).href; } catch (e) { return url; }}function convertNode(node) {if (node.nodeType === Node.TEXT_NODE) {const text = node.textContent;// 块级元素之间的 HTML 缩进(仅含空白且含换行)应当忽略,// 避免出现「# 标题\n\n 正文」这样被 Markdown 误判为代码块的输出。// <pre> 不走此分支(PRE 分支直接取 textContent),所以代码块缩进安全。if (!text.trim() && text.indexOf('\n') !== -1) return '';return text;}if (node.nodeType !== Node.ELEMENT_NODE) return '';const tag = node.tagName.toUpperCase();const kids = function () { return Array.from(node.childNodes).map(convertNode).join(''); };switch (tag) {case 'H1': return '\n# ' + kids().trim() + '\n\n';case 'H2': return '\n## ' + kids().trim() + '\n\n';case 'H3': return '\n### ' + kids().trim() + '\n\n';case 'H4': return '\n#### ' + kids().trim() + '\n\n';case 'H5': return '\n##### ' + kids().trim() + '\n\n';case 'H6': return '\n###### ' + kids().trim() + '\n\n';case 'P': return kids().trim() + '\n\n';case 'BR': return ' \n';case 'STRONG': case 'B': return '**' + kids() + '**';case 'EM': case 'I': return '*' + kids() + '*';case 'DEL': case 'S': case 'STRIKE': return '~~' + kids() + '~~';case 'SUB': return '~' + kids() + '~';case 'SUP': return '^' + kids() + '^';case 'U': return kids();case 'CODE': {const text = node.textContent;// 行内 code 不允许跨行;若出现换行则交由 PRE 处理if (text.indexOf('\n') !== -1) return '``' + text + '``';if (text.indexOf('`') !== -1) return '`` ' + text + ' ``';return '`' + text + '`';}case 'PRE': {const code = node.querySelector('code');const raw = code ? code.textContent : node.textContent;const text = raw.replace(/\n+$/, '');const cls = code ? (code.className || '') : '';const m = cls.match(/language-([\w-]+)/);const lang = m ? m[1] : '';return '\n```' + lang + '\n' + text + '\n```\n\n';}case 'UL': {let out = '\n';Array.from(node.children).forEach(function (li) {if (li.tagName === 'LI') {out += '- ' + convertNode(li).trim() + '\n';}});return out + '\n';}case 'OL': {let out = '\n';let i = 1;Array.from(node.children).forEach(function (li) {if (li.tagName === 'LI') {out += i + '. ' + convertNode(li).trim() + '\n';i++;}});return out + '\n';}case 'LI': return kids();case 'A': {const href = node.getAttribute('href') || '';const text = kids().trim() || href;if (!href || href === 'javascript:;' || href === '#') return text;return '[' + text + '](' + absolutize(href) + ')';}case 'IMG': {const src = node.getAttribute('src') || '';const alt = node.getAttribute('alt') || '';return ' + ')';}case 'BLOCKQUOTE': {const inner = kids().trim();return inner.split('\n').map(function (l) { return '> ' + l; }).join('\n') + '\n\n';}case 'HR': return '\n---\n\n';case 'TABLE': return self.convertTable(node);case 'INPUT': {if (node.type === 'checkbox') return node.checked ? '[x] ' : '[ ] ';return '';}case 'DETAILS': {const summary = node.querySelector('summary');const sumText = summary ? summary.textContent.trim() : '';const inner = kids().replace(/^[\s\S]*?<\/summary>/i, '');return '\n<details>\n<summary>' + sumText + '</summary>\n\n' + inner.trim() + '\n\n</details>\n\n';}case 'SCRIPT': case 'STYLE': case 'NOSCRIPT': return '';case 'SPAN': {// KaTeX/MathJax 已被预处理为纯文本;这里只透传return kids();}default: return kids();}}let md = convertNode(root);md = md.replace(/\r\n/g, '\n').replace(/\u00a0/g, ' ') // -> space.replace(/[ \t]+\n/g, '\n') // 行尾空格(保留 Markdown 强制换行的两个空格会损失,但更干净).replace(/\n{3,}/g, '\n\n') // 折叠多余空行.trim();return md + '\n';},convertTable: function (table) {const self = this;const rows = Array.from(table.querySelectorAll('tr'));if (!rows.length) return '';const cellNodes = rows.map(function (r) {return Array.from(r.querySelectorAll('th,td')).map(function (c) {return self._convertNodeForTable(c).trim().replace(/\|/g, '\\|').replace(/\n+/g, ' ');});});const colCount = Math.max.apply(null, cellNodes.map(function (r) { return r.length; }));if (!colCount) return '';// 补齐每行列数const aligned = cellNodes.map(function (r) {while (r.length < colCount) r.push('');return r;});const header = aligned[0];const sep = Array(colCount).fill('---');const body = aligned.slice(1);let out = '\n';out += '| ' + header.join(' | ') + ' |\n';out += '| ' + sep.join(' | ') + ' |\n';body.forEach(function (r) { out += '| ' + r.join(' | ') + ' |\n'; });return out + '\n';},/** 表格单元格内转换器(与 htmlToMarkdown 内部的 convertNode 行为一致) */_convertNodeForTable: function (node) {const self = this;function rec(n) {if (n.nodeType === Node.TEXT_NODE) return n.textContent;if (n.nodeType !== Node.ELEMENT_NODE) return '';const tag = n.tagName.toUpperCase();const kids = function () { return Array.from(n.childNodes).map(rec).join(''); };switch (tag) {case 'BR': return ' ';case 'STRONG': case 'B': return '**' + kids() + '**';case 'EM': case 'I': return '*' + kids() + '*';case 'CODE': return '`' + n.textContent + '`';case 'A': {const href = n.getAttribute('href') || '';const text = kids().trim() || href;if (!href || href === 'javascript:;' || href === '#') return text;return '[' + text + '](' + href + ')';}case 'SCRIPT': case 'STYLE': case 'NOSCRIPT': return '';default: return kids();}}return rec(node);},showModal: function () {const self = this;const md = self.getProblemMarkdown();self._lastMarkdown = md;// 题目 ID 与标题,用于显示与下载文件名const titleEl = document.querySelector('.problem-content .section__title, .problem-content-container .section__title');const titleText = titleEl ? titleEl.textContent.trim() : 'problem';const pid = (location.pathname.match(/^\/p\/([^\/]+)$/) || [])[1] || 'problem';const tid = new URLSearchParams(location.search).get('tid') || '';const safeName = (titleText || pid).replace(/[\\/:*?"<>|]/g, '_').slice(0, 80);// 清理已存在的旧模态框if (self._modal) { self._modal.remove(); self._modal = null; }const backdrop = document.createElement('div');backdrop.className = 'bzoj-md-modal-backdrop';backdrop.innerHTML ='<div class="bzoj-md-modal" role="dialog" aria-modal="true" aria-label="题目 Markdown">' +'<div class="bzoj-md-modal-header">' +'<div class="bzoj-md-modal-title">' +'<span class="bzoj-md-title-tag">MD</span>' +'<span>题目 Markdown</span>' +'<span class="bzoj-md-modal-subtitle">' + self._escapeHtml(pid + (tid ? ' · tid=' + tid : '')) + '</span>' +'</div>' +'<button type="button" class="bzoj-md-modal-close" aria-label="关闭">×</button>' +'</div>' +'<div class="bzoj-md-modal-toolbar">' +'<button type="button" class="bzoj-md-btn bzoj-md-btn--primary" data-act="copy">复制到剪贴板</button>' +'<button type="button" class="bzoj-md-btn" data-act="download">下载 .md</button>' +'<button type="button" class="bzoj-md-btn bzoj-md-btn--ghost" data-act="select">全选</button>' +'<span class="bzoj-md-spacer"></span>' +'<span class="bzoj-md-meta">' + md.length + ' 字符</span>' +'</div>' +'<div class="bzoj-md-modal-body">' +'<textarea class="bzoj-md-textarea" spellcheck="false" readonly></textarea>' +'</div>' +'</div>';document.body.appendChild(backdrop);self._modal = backdrop;const textarea = backdrop.querySelector('.bzoj-md-textarea');textarea.value = md;// 打开动效requestAnimationFrame(function () { backdrop.classList.add('bzoj-show'); });setTimeout(function () { textarea.focus(); textarea.setSelectionRange(0, 0); textarea.scrollTop = 0; }, 60);// 关闭逻辑function close() {backdrop.classList.remove('bzoj-show');setTimeout(function () { if (backdrop.parentNode) backdrop.remove(); self._modal = null; }, 220);}backdrop.querySelector('.bzoj-md-modal-close').addEventListener('click', close);backdrop.addEventListener('click', function (e) { if (e.target === backdrop) close(); });document.addEventListener('keydown', function onKey(e) {if (e.key === 'Escape' && self._modal === backdrop) {close();document.removeEventListener('keydown', onKey);}});// 工具栏按钮backdrop.querySelector('[data-act="copy"]').addEventListener('click', function () {self.copyToClipboard(textarea.value, close);});backdrop.querySelector('[data-act="download"]').addEventListener('click', function () {self.downloadFile(safeName + '.md', textarea.value);});backdrop.querySelector('[data-act="select"]').addEventListener('click', function () {textarea.focus(); textarea.select();});},copyToClipboard: function (text, onClose) {const self = this;let done = false;function succeed() { if (done) return; done = true; self.showToast('已复制 Markdown 到剪贴板'); if (onClose) onClose(); }function fail(msg) { if (done) return; done = true; self.showToast('复制失败:' + (msg || '请手动全选复制'), 'error'); }try {if (typeof GM_setClipboard === 'function') {GM_setClipboard(text, 'text');succeed();return;}} catch (e) { /* fall through */ }if (navigator.clipboard && navigator.clipboard.writeText) {navigator.clipboard.writeText(text).then(succeed).catch(function () { fallbackExec(); });} else {fallbackExec();}function fallbackExec() {try {const ta = document.createElement('textarea');ta.value = text;ta.style.position = 'fixed'; ta.style.opacity = '0'; ta.style.top = '0'; ta.style.left = '0';document.body.appendChild(ta); ta.focus(); ta.select();const ok = document.execCommand('copy');document.body.removeChild(ta);if (ok) succeed(); else fail('execCommand 返回 false');} catch (e) { fail(e && e.message); }}},downloadFile: function (filename, content) {try {const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url; a.download = filename;document.body.appendChild(a); a.click();document.body.removeChild(a);setTimeout(function () { URL.revokeObjectURL(url); }, 200);this.showToast('已开始下载 ' + filename);} catch (e) {this.showToast('下载失败:' + (e && e.message ? e.message : ''), 'error');}},_toastEl: null,_toastTimer: null,showToast: function (msg, type) {const self = this;if (self._toastTimer) clearTimeout(self._toastTimer);if (!self._toastEl) {self._toastEl = document.createElement('div');self._toastEl.className = 'bzoj-md-toast';document.body.appendChild(self._toastEl);}self._toastEl.textContent = msg;if (type === 'error') self._toastEl.style.background = '#b03a3a';else self._toastEl.style.background = '';// 强制重排以重启动效void self._toastEl.offsetWidth;self._toastEl.classList.add('bzoj-show');self._toastTimer = setTimeout(function () { self._toastEl.classList.remove('bzoj-show'); }, 2200);},_escapeHtml: function (s) {return String(s).replace(/[&<>"']/g, function (c) {return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];});}};// ================================================================// 模块三:题目列表「提交」快捷列// 仅在以下页面运行:// - /contest/<hex>/problems (比赛题目列表)// - /p (题库)// - /p?page=<num> (题库分页)// - /homework/<hex> (作业题目列表)// - /training/<hex> (训练题目列表)// 在题目列表表格中新增一列「提交」,显示指向 /p/<id>/submit 的链接。// 兼容所有 Hydro 系 OJ。// ================================================================const BZOJ_SubmitLinkModule = {/** 判断当前页面是否应该启用此模块 */shouldRun: function () {const path = window.location.pathname;// /contest/<hex>/problemsif (/\/contest\/[^\/]+\/problems\/?$/.test(path)) return true;// /p 或 /p?page=<num>(精确匹配 /p 结尾,排除 /p/<id> 详情页)if (/^\/p\/?$/.test(path)) return true;// /homework/<hex>if (/\/homework\/[^\/]+\/?$/.test(path)) return true;// /training/<hex>if (/\/training\/[^\/]+\/?$/.test(path)) return true;return false;},init: function () {const self = this;if (!self.shouldRun()) return;GM_addStyle(`.bzoj-submit-col-link {display: inline-block;padding: 2px 12px;border-radius: 4px;background: rgba(86,117,143,0.1);color: #56758f;font-size: 13px;font-weight: 600;text-decoration: none;font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif;transition: all .15s;}.bzoj-submit-col-link:hover {background: #56758f;color: #fff;text-decoration: none;}.theme--dark .bzoj-submit-col-link,html[data-mantine-color-scheme="dark"] .bzoj-submit-col-link {background: rgba(142,179,208,0.15);color: #8eb3d0;}.theme--dark .bzoj-submit-col-link:hover,html[data-mantine-color-scheme="dark"] .bzoj-submit-col-link:hover {background: #56758f;color: #fff;}`);self.injectColumns();// 监听 DOM 变化(Hydro 可能动态加载/重建表格)self._installObserver();},/** 判断一个 URL 是否是题目链接:/p/<id>(排除 submit 等子路径) */isProblemLink: function (href) {if (!href) return false;if (/\/p\/[^\/]+\/(submit|solution|edit|files|manage)/.test(href)) return false;return /\/p\/[^\/]+/.test(href);},/** 从题目链接 href 构建 submit URL(保留 tid 参数) */buildSubmitUrl: function (href) {const url = new URL(href, location.href);return url.pathname.replace(/\/$/, '') + '/submit' + (url.search || '');},/** 在题目列表表格中新增「提交」列(不修改原有列,只在最右侧追加) */injectColumns: function () {const self = this;// 第一步:移除页面中所有 Hydro 自带的「递交」链接(class="typo-a" 且指向 submit),// 这些链接通常是 float:right 的纯文字+图标,样式较陋,用我们新增的列替代。// 独立于表格处理执行,确保即使行已被标记也能清理。const allOldLinks = document.querySelectorAll('a.typo-a[href*="/submit"]');for (const oldLink of allOldLinks) {oldLink.remove();}// 查找所有包含题目链接的表格const tables = document.querySelectorAll('table.data-table');let count = 0;for (const table of tables) {if (table.dataset.bzojSubmitCol === '1') continue; // 已处理const tbody = table.querySelector('tbody');if (!tbody) continue;// 检查表格是否包含题目链接(决定是否处理此表格)const rows = tbody.querySelectorAll('tr');let hasProblemRow = false;for (const row of rows) {const link = row.querySelector('a[href*="/p/"]');if (link && self.isProblemLink(link.getAttribute('href') || '')) {hasProblemRow = true;break;}}if (!hasProblemRow) continue;// 找到表头行(thead > tr),也在表头加一列let headerRow = null;const thead = table.querySelector('thead');if (thead) headerRow = thead.querySelector('tr');// Hydro 可能还有独立的 sticky 表头表(section__table-header),也要同步加列let stickyHeaderRow = null;const container = table.closest('.section__body, .section, .problem-list-container, .col-container');if (container) {const stickyTable = container.querySelector('table.section__table-header');if (stickyTable) {const stickyThead = stickyTable.querySelector('thead');if (stickyThead) stickyHeaderRow = stickyThead.querySelector('tr');}}// 同步 colgroup:如果有 <colgroup>,需要加一个 <col> 保持列数一致const colgroup = table.querySelector('colgroup');if (colgroup && !colgroup.dataset.bzojSubmitCol) {const col = document.createElement('col');col.style.width = '80px';colgroup.appendChild(col);colgroup.dataset.bzojSubmitCol = '1';}// sticky 表头的 colgroup 也要同步if (container) {const stickyTable = container.querySelector('table.section__table-header');if (stickyTable) {const stickyColgroup = stickyTable.querySelector('colgroup');if (stickyColgroup && !stickyColgroup.dataset.bzojSubmitCol) {const col = document.createElement('col');col.style.width = '80px';stickyColgroup.appendChild(col);stickyColgroup.dataset.bzojSubmitCol = '1';}}}// 在表头加一列「提交」// 表头文字右对齐,padding-right 设为 28px(= td 的 16px + 按钮自身的 12px padding),// 使「提交」文字与下方按钮内文字的垂直中线对齐if (headerRow && !headerRow.dataset.bzojSubmitHeader) {const th = document.createElement('th');th.textContent = '提交';th.style.cssText = 'text-align: right; white-space: nowrap; width: 80px; padding-right: 28px;';headerRow.appendChild(th);headerRow.dataset.bzojSubmitHeader = '1';}// sticky 表头也加一列if (stickyHeaderRow && !stickyHeaderRow.dataset.bzojSubmitHeader) {const th = document.createElement('th');th.textContent = '提交';th.style.cssText = 'text-align: right; white-space: nowrap; width: 80px; padding-right: 28px;';stickyHeaderRow.appendChild(th);stickyHeaderRow.dataset.bzojSubmitHeader = '1';}// 遍历所有行:有题目链接的加「提交」链接,无题目链接的(如 * 占位行)补空 td 保持列数一致for (const row of rows) {if (row.dataset.bzojSubmitCell === '1') continue;const link = row.querySelector('a[href*="/p/"]');const isValidProblem = link && self.isProblemLink(link.getAttribute('href') || '');const td = document.createElement('td');td.style.cssText = 'text-align: right; white-space: nowrap; padding-right: 16px;';if (isValidProblem) {// 有题目链接:加「提交」按钮const href = link.getAttribute('href') || '';const submitUrl = self.buildSubmitUrl(href);const a = document.createElement('a');a.href = submitUrl;a.className = 'bzoj-submit-col-link';a.textContent = '提交';a.title = '递交此题';a.target = link.target || '_self';td.appendChild(a);count++;} else {// 无题目链接(如 * 占位行):补空 td,保持列数一致,不破坏行的灰色背景td.innerHTML = ' ';}row.appendChild(td);row.dataset.bzojSubmitCell = '1';}table.dataset.bzojSubmitCol = '1';}return count;},_observer: null,_debounce: null,_installObserver: function () {const self = this;if (self._observer) return;self._observer = new MutationObserver(function () {clearTimeout(self._debounce);self._debounce = setTimeout(function () {self.injectColumns();}, 300);});self._observer.observe(document.body, { childList: true, subtree: true });}};// ================================================================// 模块四:比赛/作业成绩表增强(scoreboard)// 适用页面:// - /contest/<hex>/scoreboard// - /homework/<hex>/scoreboard// 功能:// 1. 黄色高亮当前登录用户所在行// 2. 对当前用户行的每道题,异步 fetch 该题的提交记录页面,// 提取最新一次提交的详细信息(状态、分数、耗时、内存),// 用直角状态方块显示在单元格内。// 兼容所有 Hydro 系 OJ。// ================================================================const BZOJ_ScoreboardModule = {/** 状态信息(复用 testcase 模块的颜色定义,方块改为直角) */STATUS_MAP: {'accepted': { bg: '#f6ffed', text: 'AC', color: '#389e0d', border: '#b7eb8f' },'wrong answer': { bg: '#fff2f0', text: 'WA', color: '#cf1322', border: '#ffccc7' },'time limit exceeded': { bg: '#e6f7ff', text: 'TLE', color: '#0958d9', border: '#91d5ff' },'memory limit exceeded': { bg: '#e6f7ff', text: 'MLE', color: '#0958d9', border: '#91d5ff' },'runtime error': { bg: '#f9f0ff', text: 'RE', color: '#722ed1', border: '#d3adf7' },'compile error': { bg: '#fffbe6', text: 'CE', color: '#d48806', border: '#ffe58f' },'output limit exceeded': { bg: '#e6f7ff', text: 'OLE', color: '#0958d9', border: '#91d5ff' },'system error': { bg: '#f5f5f5', text: 'SE', color: '#434343', border: '#d9d9d9' },'judging': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true },'compiling': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true },'waiting': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true },'running': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true },},DARK_STATUS_MAP: {'accepted': { bg: '#1e3a1e', text: 'AC', color: '#95de64', border: '#389e0d' },'wrong answer': { bg: '#3d1f22', text: 'WA', color: '#ff9c9c', border: '#a8071a' },'time limit exceeded': { bg: '#1a2d42', text: 'TLE', color: '#69c0ff', border: '#003a8c' },'memory limit exceeded': { bg: '#1a2d42', text: 'MLE', color: '#69c0ff', border: '#003a8c' },'runtime error': { bg: '#2d1f3d', text: 'RE', color: '#c9a0f5', border: '#531dab' },'compile error': { bg: '#3d321e', text: 'CE', color: '#ffd666', border: '#ad6800' },'output limit exceeded': { bg: '#1a2d42', text: 'OLE', color: '#69c0ff', border: '#003a8c' },'system error': { bg: '#2e2e2e', text: 'SE', color: '#d9d9d9', border: '#434343' },},/** 判断当前页面是否是成绩表页 */shouldRun: function () {const path = window.location.pathname;return /\/(contest|homework)\/[^\/]+\/scoreboard\/?$/.test(path);},/** 从 URL 提取 tid(比赛/作业 ID) */getTid: function () {const m = window.location.pathname.match(/\/(contest|homework)\/([^\/]+)\/scoreboard/);return m ? m[2] : '';},/** 检测暗色模式 */isDarkMode: function () {const html = document.documentElement;if (html.classList.contains('theme--dark')) return true;if (html.classList.contains('theme--light')) return false;if (html.getAttribute('data-mantine-color-scheme') === 'dark') return true;if (html.getAttribute('data-mantine-color-scheme') === 'light') return false;try {const bgColor = getComputedStyle(document.body).backgroundColor;const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if (match) {return (0.299 * +match[1] + 0.587 * +match[2] + 0.114 * +match[3]) / 255 < 0.5;}} catch (e) {}return false;},/** 获取当前登录用户的 uid */getCurrentUid: function () {// Hydro 导航栏: nav .nav__list--secondary a[href^="/user/"]const userLink = document.querySelector('nav .nav__list--secondary a[href^="/user/"]');if (userLink) {const m = userLink.getAttribute('href').match(/\/user\/(\w+)/);if (m) return m[1];}// 兜底const altLink = document.querySelector('a[href^="/user/"][class*="user-profile"], a.uname[href^="/user/"]');if (altLink) {const m = altLink.getAttribute('href').match(/\/user\/(\w+)/);if (m) return m[1];}return null;},init: function () {const self = this;if (!self.shouldRun()) return;GM_addStyle(`/* 当前用户行高亮 */.bzoj-scoreboard-highlight {background-color: rgba(255, 230, 0, 0.25) !important;}.theme--dark .bzoj-scoreboard-highlight,html[data-mantine-color-scheme="dark"] .bzoj-scoreboard-highlight {background-color: rgba(255, 200, 0, 0.18) !important;}/* 详细状态方块(直角,填满单元格,契合表格) */.bzoj-score-cell {display: flex;flex-direction: column;align-items: center;justify-content: center;width: 100%;box-sizing: border-box;padding: 4px 2px;border: 1px solid;border-radius: 0;font-family: system-ui, -apple-system, sans-serif;font-weight: 600;line-height: 1.2;cursor: default;transition: transform 0.1s;text-decoration: none;}.bzoj-score-cell:hover {transform: scale(1.05);}/* 让 td 本身也成为 flex 容器,确保方块填满 */td.col--problem:has(.bzoj-score-cell) {padding: 2px !important;}.bzoj-score-cell__text {font-size: 11px;font-weight: 700;}.bzoj-score-cell__score {font-size: 13px;font-weight: 700;}.bzoj-score-cell__detail {font-size: 9px;font-weight: 400;opacity: 0.8;white-space: nowrap;}@keyframes bzoj-score-spin {from { transform: rotate(0deg); } to { transform: rotate(360deg); }}.bzoj-score-cell__text--spin {animation: bzoj-score-spin 1.5s linear infinite;}/* 加载中占位 */.bzoj-score-loading {display: inline-block;width: 14px;height: 14px;border: 2px solid rgba(86,117,143,0.2);border-top-color: #56758f;border-radius: 50%;animation: bzoj-score-spin 0.8s linear infinite;}`);self.enhanceScoreboard();self._installObserver();},/** 标准化状态文本 */normalizeStatus: function (raw) {if (!raw) return '';const text = raw.trim().toLowerCase();const aliases = {'time exceeded': 'time limit exceeded','memory exceeded': 'memory limit exceeded','ac': 'accepted', 'wa': 'wrong answer','tle': 'time limit exceeded', 'mle': 'memory limit exceeded','re': 'runtime error', 'ce': 'compile error','ole': 'output limit exceeded', 'se': 'system error',};if (aliases[text]) return aliases[text];for (const key of Object.keys(this.STATUS_MAP)) {if (text.includes(key)) return key;}return text;},/** 获取状态信息 */getStatusInfo: function (key) {const isDark = this.isDarkMode();const map = isDark ? this.DARK_STATUS_MAP : this.STATUS_MAP;return map[key] || {bg: isDark ? '#2e2e2e' : '#f5f5f5',text: key.substring(0, 3).toUpperCase(),color: isDark ? '#d9d9d9' : '#434343',border: isDark ? '#434343' : '#d9d9d9',};},/** 从表头提取每道题的 pid 列表 */extractProblemIds: function () {// Hydro 成绩表表头在独立的 sticky 表 (table.section__table-header) 或同表 theadconst headerLinks = document.querySelectorAll('table.section__table-header thead th.col--problem a[href*="/p/"], ' +'table thead th.col--problem a[href*="/p/"]');const pids = [];for (const a of headerLinks) {const m = a.getAttribute('href').match(/\/p\/([^\/?]+)/);if (m) pids.push(m[1]);}return pids;},/** 增强成绩表:高亮当前用户行 + 异步加载提交详情 */enhanceScoreboard: function () {const self = this;const uid = self.getCurrentUid();const tid = self.getTid();// 查找成绩表 tbody(Hydro 用 table.data-table,tbody 里有行)const tables = document.querySelectorAll('table.data-table');for (const table of tables) {const tbody = table.querySelector('tbody');if (!tbody) continue;const rows = tbody.querySelectorAll('tr');if (rows.length === 0) continue;// 检查是否是成绩表(有 col--rank / col--user 列)if (!table.querySelector('col.col--rank, col.col--user, td.col--rank, td.col--user')) continue;if (table.dataset.bzojScoreboard === '1') continue;table.dataset.bzojScoreboard = '1';// 提取每题 pid(从表头)const pids = self.extractProblemIds();for (const row of rows) {if (row.dataset.bzojScoreRow === '1') continue;row.dataset.bzojScoreRow = '1';// 高亮当前用户行if (uid) {const userBtn = row.querySelector('[data-uid]');const userLink = row.querySelector('a[href^="/user/"]');let rowUid = null;if (userBtn) rowUid = userBtn.getAttribute('data-uid');else if (userLink) {const m = userLink.getAttribute('href').match(/\/user\/(\w+)/);if (m) rowUid = m[1];}if (rowUid && rowUid === uid) {row.classList.add('bzoj-scoreboard-highlight');// 对当前用户行,异步加载每题提交详情self._loadUserSubmissionDetails(row, uid, tid, pids);}}}}},/** 异步加载当前用户每道题的提交详情 */_loadUserSubmissionDetails: async function (row, uid, tid, pids) {const self = this;// 获取当前行的题目单元格(col--problem)const problemCells = row.querySelectorAll('td.col--problem');if (problemCells.length === 0) return;// 为每个题目单元格先放加载占位problemCells.forEach((cell, idx) => {if (cell.querySelector('.bzoj-score-cell, .bzoj-score-loading')) return;// 保留原始分数文本const originalScore = cell.textContent.trim();cell.dataset.bzojOriginalScore = originalScore;const loader = document.createElement('span');loader.className = 'bzoj-score-loading';cell.innerHTML = '';cell.appendChild(loader);});// 逐题 fetch 提交记录for (let i = 0; i < problemCells.length && i < pids.length; i++) {const cell = problemCells[i];const pid = pids[i];try {await self._fetchAndShowDetail(cell, pid, uid, tid);} catch (e) {self._restoreCell(cell);}}},/** fetch 单题提交记录,提取最新提交的 record 链接,再 fetch record 详情 */_fetchAndShowDetail: async function (cell, pid, uid, tid) {const self = this;// Hydro 提交记录列表: /record?pid=<pid>&uidOrName=<uid>&tid=<tid>const listUrl = `/record?pid=${encodeURIComponent(pid)}&uidOrName=${encodeURIComponent(uid)}${tid ? '&tid=' + tid : ''}`;const resp = await fetch(listUrl, { credentials: 'same-origin' });const html = await resp.text();const doc = new DOMParser().parseFromString(html, 'text/html');// 找到第一条提交记录的链接 /record/<rid>const recordLink = doc.querySelector('a[href^="/record/"]');if (!recordLink) {self._restoreCell(cell);return;}const ridMatch = recordLink.getAttribute('href').match(/\/record\/(\w+)/);if (!ridMatch) {self._restoreCell(cell);return;}const rid = ridMatch[1];// fetch record 详情页const recordUrl = `/record/${rid}`;const resp2 = await fetch(recordUrl, { credentials: 'same-origin' });const html2 = await resp2.text();const doc2 = new DOMParser().parseFromString(html2, 'text/html');// 从 record 页面提取状态、分数、耗时、内存const detail = self._extractRecordDetail(doc2);self._renderDetailCell(cell, detail, recordUrl);},/** 从 record 详情页提取状态/分数/耗时/内存* 页面结构:* 顶栏 #status .section__title 内含 .record-status--text(状态文字,如 Accepted)* 和 .float-right 或无 class 的 span(分数,如 60)* 侧边栏 #summary 的 dl.horizontal 内:* <dt>分数</dt><dd>60</dd>* <dt>总耗时</dt><dd>39ms</dd>* <dt>峰值时间</dt><dd>1ms</dd>* <dt>峰值内存</dt><dd>768 KiB</dd>*/_extractRecordDetail: function (doc) {const self = this;// 状态:顶栏的 .record-status--text(排除 .float-right 分数部分)let statusKey = '';const statusEls = doc.querySelectorAll('#status .record-status--text, .record-status--text');for (const el of statusEls) {// 克隆后移除 .float-right 子元素,只取状态文字const clone = el.cloneNode(true);clone.querySelectorAll('.float-right').forEach(e => e.remove());const text = clone.textContent.trim();if (text) {statusKey = self.normalizeStatus(text);if (statusKey) break;}}// 从 #summary 的 dl.horizontal 提取分数/时间/内存let score = '', time = '', memory = '';const summaryDl = doc.querySelector('#summary, dl#summary');if (summaryDl) {const dts = summaryDl.querySelectorAll('dt');const dds = summaryDl.querySelectorAll('dd');for (let i = 0; i < dts.length && i < dds.length; i++) {const label = dts[i].textContent.trim().toLowerCase();const value = dds[i].textContent.trim();if (label === '分数' || label === 'score') {score = value;} else if (label === '峰值时间' || label === '总耗时' || label.includes('时间') || label.includes('time')) {if (!time) time = value; // 优先取峰值时间/总耗时} else if (label === '峰值内存' || label.includes('内存') || label.includes('memory')) {memory = value;}}}// 兜底:分数从顶栏 .float-right 或 section__title 提取if (!score) {const floatRight = doc.querySelector('#status .float-right, .record-status--text .float-right');if (floatRight) {score = floatRight.textContent.trim();}}if (!score) {const titleEl = doc.querySelector('#status .section__title');if (titleEl) {const m = titleEl.textContent.match(/(\d+)/);if (m) score = m[1];}}return { statusKey, score, time, memory };},/** 渲染详细状态方块到单元格 */_renderDetailCell: function (cell, detail, recordUrl) {const self = this;const originalScore = cell.dataset.bzojOriginalScore || '';cell.innerHTML = '';if (!detail.statusKey && !detail.score && !originalScore) {self._restoreCell(cell);return;}const statusKey = detail.statusKey || '';const info = statusKey ? self.getStatusInfo(statusKey) : {bg: this.isDarkMode() ? '#2e2e2e' : '#f5f5f5',text: '', color: this.isDarkMode() ? '#d9d9d9' : '#434343',border: this.isDarkMode() ? '#434343' : '#d9d9d9',};const block = document.createElement('a');block.href = recordUrl;block.target = '_blank';block.className = 'bzoj-score-cell';block.style.background = info.bg;block.style.color = info.color;block.style.borderColor = info.border;// 状态缩写if (info.text) {const textEl = document.createElement('span');textEl.className = 'bzoj-score-cell__text';if (info.spin) textEl.classList.add('bzoj-score-cell__text--spin');textEl.textContent = info.text;block.appendChild(textEl);}// 分数const scoreVal = detail.score || originalScore;if (scoreVal) {const scoreEl = document.createElement('span');scoreEl.className = 'bzoj-score-cell__score';scoreEl.textContent = scoreVal;block.appendChild(scoreEl);}// 耗时 / 内存if (detail.time || detail.memory) {const detailEl = document.createElement('span');detailEl.className = 'bzoj-score-cell__detail';detailEl.textContent = [detail.time, detail.memory].filter(Boolean).join(' / ');block.appendChild(detailEl);}cell.appendChild(block);},/** 恢复原始分数显示 */_restoreCell: function (cell) {const original = cell.dataset.bzojOriginalScore;if (original !== undefined) {cell.innerHTML = '';cell.textContent = original;}},_observer: null,_debounce: null,_installObserver: function () {const self = this;if (self._observer) return;self._observer = new MutationObserver(function () {clearTimeout(self._debounce);self._debounce = setTimeout(function () {self.enhanceScoreboard();}, 500);});self._observer.observe(document.body, { childList: true, subtree: true });}};// ================================================================// 模块五:网页字体更换器(所有站点运行)// ================================================================// ==================== 默认常量 ====================const FS_DEFAULT_BTN_SIZE = 42;const FS_COLLAPSED_VISIBLE = 6;const FS_HOVER_ZONE = 10;const FS_DEFAULT_IDLE_MS = 5000;const FS_DRAG_THRESHOLD = 4;const FS_PANEL_W = 360;const FS_PANEL_MAX_H = 560;const FS_MARGIN = 8;// ==================== 存储 ====================const FS_STORAGE_KEY_CUSTOM_FONTS = 'fontSwitcher_customFonts';const FS_STORAGE_KEY_GLOBAL_SETTINGS = 'fontSwitcher_globalSettings';const FS_CURRENT_HOST = location.hostname;function fsSiteKey(base) { return `${base}@${FS_CURRENT_HOST}`; }const FS_STORAGE_KEY_ACTIVE_FONT = fsSiteKey('fontSwitcher_activeFont');const FS_STORAGE_KEY_ENABLED = fsSiteKey('fontSwitcher_enabled');const FS_STORAGE_KEY_BTN_POS = fsSiteKey('fontSwitcher_btnPos');const FS_STORAGE_KEY_FONT_SETTINGS = fsSiteKey('fontSwitcher_fontSettings');function fsLoadFromStorage(key, fallback) {try {if (typeof GM_getValue === 'function') {const v = GM_getValue(key, null);if (v !== null && v !== undefined) return v;3 行未改动} catch (e) { /* 忽略 */ }return fallback;}function fsSaveToStorage(key, value) {try {if (typeof GM_setValue === 'function') GM_setValue(key, value);localStorage.setItem(key, JSON.stringify(value));} catch (e) { /* 忽略 */ }}// ==================== 全局设置 ====================const FS_DEFAULT_GLOBAL_SETTINGS = {btnSize: 42,snapToEdge: true,autoCollapse: true,idleMs: 5000,excludeInputs: false,toastDuration: 2000,};let fsGlobalSettings = Object.assign({}, FS_DEFAULT_GLOBAL_SETTINGS, fsLoadFromStorage(FS_STORAGE_KEY_GLOBAL_SETTINGS, {}));function fsSaveGlobalSettings() {fsSaveToStorage(FS_STORAGE_KEY_GLOBAL_SETTINGS, fsGlobalSettings);}let FS_BTN_SIZE = fsGlobalSettings.btnSize || FS_DEFAULT_BTN_SIZE;let FS_IDLE_MS = fsGlobalSettings.autoCollapse ? (fsGlobalSettings.idleMs || FS_DEFAULT_IDLE_MS) : Infinity;let FS_COLLAPSED_SHIFT = FS_BTN_SIZE - FS_COLLAPSED_VISIBLE;function fsRefreshDerivedSettings() {FS_BTN_SIZE = fsGlobalSettings.btnSize || FS_DEFAULT_BTN_SIZE;FS_IDLE_MS = fsGlobalSettings.autoCollapse ? (fsGlobalSettings.idleMs || FS_DEFAULT_IDLE_MS) : Infinity;FS_COLLAPSED_SHIFT = FS_BTN_SIZE - FS_COLLAPSED_VISIBLE;}// ==================== 状态 ====================let fsCustomFonts = fsLoadFromStorage(FS_STORAGE_KEY_CUSTOM_FONTS, []);let fsActiveFontValue = fsLoadFromStorage(FS_STORAGE_KEY_ACTIVE_FONT, '');let fsIsEnabled = fsLoadFromStorage(FS_STORAGE_KEY_ENABLED, true);let fsFontSettings = fsLoadFromStorage(FS_STORAGE_KEY_FONT_SETTINGS, {});const fsSavedPos = fsLoadFromStorage(FS_STORAGE_KEY_BTN_POS, null);let fsBtnSide = (fsSavedPos && fsSavedPos.side) ? fsSavedPos.side : 'right';let fsBtnY = (fsSavedPos && typeof fsSavedPos.y === 'number') ? fsSavedPos.y : 60;let fsBtnX = (fsSavedPos && typeof fsSavedPos.x === 'number') ? fsSavedPos.x : -1;let fsPanelVisible = false;let fsBtnCollapsed = false;let fsIdleTimer = null;let fsIsDragging = false;let fsHasDragged = false;let fsDragStartX = 0, fsDragStartY = 0;let fsBtnStartLeft = 0, fsBtnStartTop = 0;let fsPreviewStyleEl = null;let fsExpandedSettingsSet = new Set();let fsSettingsViewActive = false;// ==================== 预置字体 ====================const FS_PRESET_FONTS = [{ name: '默认(不替换)', value: '' },{ name: '微软雅黑', value: '"Microsoft YaHei", "微软雅黑", sans-serif' },{ name: '苹方', value: '"PingFang SC", "Helvetica Neue", sans-serif' },{ name: '宋体', value: 'SimSun, "宋体", serif' },17 行未改动{ name: 'Trebuchet MS', value: '"Trebuchet MS", Helvetica, sans-serif' },{ name: 'Verdana', value: 'Verdana, Geneva, sans-serif' },];// ==================== 字体可用性检测 ====================const fsFontAvailability = new Map();function fsDetectFontAvailability(fontValue) {if (!fontValue) return true;const primaryFont = fontValue.split(',')[0].trim().replace(/^"|"$/g, '');if (!primaryFont) return true;if (fsFontAvailability.has(primaryFont)) return fsFontAvailability.get(primaryFont);const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');if (!ctx) { fsFontAvailability.set(primaryFont, true); return true; }const testStr = 'mmmmmmmmmmlli1WqB@#&_%';const size = '72px';const fallbacks = ['sans-serif', 'serif', 'monospace'];const baseWidths = fallbacks.map(fb => {ctx.font = `${size} ${fb}`;return ctx.measureText(testStr).width;});ctx.font = `${size} "${primaryFont}", sans-serif`;const testWidth = ctx.measureText(testStr).width;const available = !baseWidths.every(bw => Math.abs(bw - testWidth) < 0.5);fsFontAvailability.set(primaryFont, available);return available;}function fsDetectAllFonts() {fsFontAvailability.clear();FS_PRESET_FONTS.forEach(font => {if (font.value) fsDetectFontAvailability(font.value);});fsCustomFonts.forEach(font => {if (font.value) {const primaryFont = font.value.split(',')[0].trim().replace(/^"|"$/g, '');if (primaryFont) fsFontAvailability.set(primaryFont, true);}});}// ==================== 字体设置工具 ====================function fsGetFontSettings(fontValue) {if (!fontValue) return null;return fsFontSettings[fontValue] || null;}function fsSetFontSettings(fontValue, settings) {if (!fontValue) return;fsFontSettings[fontValue] = settings;fsSaveToStorage(FS_STORAGE_KEY_FONT_SETTINGS, fsFontSettings);}function fsRemoveFontSettings(fontValue) {if (!fontValue) return;delete fsFontSettings[fontValue];fsSaveToStorage(FS_STORAGE_KEY_FONT_SETTINGS, fsFontSettings);}function fsHasNonDefaultSettings(fontValue) {if (!fontValue) return false;const s = fsFontSettings[fontValue];if (!s) return false;if (s.size) return true;if (s.weight && s.weight !== '' && s.weight !== 'normal') return true;return false;}// ==================== 样式注入 ====================function fsBuildStyles() {return `/* ========== 按钮 ========== */#fs-trigger-btn {position: fixed;z-index: 2147483647;width: ${FS_BTN_SIZE}px;height: ${FS_BTN_SIZE}px;border: none;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: #fff;font-size: ${Math.round(FS_BTN_SIZE * 0.43)}px;font-weight: bold;cursor: pointer;box-shadow: 0 4px 15px rgba(102, 126, 234, 0.45);display: flex;17 行未改动}#fs-trigger-btn .fs-btn-icon {pointer-events: none;line-height: 1;font-size: ${Math.round(FS_BTN_SIZE * 0.48)}px;transition: opacity 0.2s;}#fs-trigger-btn.fs-free {left: auto;right: auto;border-radius: 50%;}#fs-trigger-btn.fs-free.fs-collapsed {opacity: 0.35;transform: scale(0.85);pointer-events: none;}#fs-trigger-btn.fs-free.fs-collapsed .fs-btn-icon { opacity: 0.6; }#fs-trigger-btn.fs-side-right {right: 0;left: auto;border-radius: ${FS_BTN_SIZE / 2}px 0 0 ${FS_BTN_SIZE / 2}px;}#fs-trigger-btn.fs-side-right.fs-collapsed {transform: translateX(${FS_COLLAPSED_SHIFT}px);border-radius: 8px 0 0 8px;pointer-events: none;opacity: 0.5;}#fs-trigger-btn.fs-side-right.fs-collapsed .fs-btn-icon { opacity: 0; }#fs-trigger-btn.fs-side-left {left: 0;right: auto;border-radius: 0 ${FS_BTN_SIZE / 2}px ${FS_BTN_SIZE / 2}px 0;}#fs-trigger-btn.fs-side-left.fs-collapsed {transform: translateX(-${FS_COLLAPSED_SHIFT}px);border-radius: 0 8px 8px 0;pointer-events: none;opacity: 0.5;}#fs-trigger-btn.fs-side-left.fs-collapsed .fs-btn-icon { opacity: 0; }#fs-trigger-btn.fs-dragging {cursor: grabbing !important;opacity: 1;box-shadow: 0 8px 30px rgba(118, 75, 162, 0.7);transform: scale(1.08) !important;border-radius: 50% !important;transition: box-shadow 0.15s, opacity 0.15s;}#fs-trigger-btn.fs-snapping {transition: left 0.35s cubic-bezier(0.25, 1, 0.5, 1),top 0.25s ease,border-radius 0.3s ease,transform 0.3s ease !important;transform: scale(1) !important;}#fs-trigger-btn.fs-active {opacity: 1;box-shadow: 0 6px 24px rgba(118, 75, 162, 0.7);}18 行未改动/* ========== 面板 ========== */#fs-panel {position: fixed;z-index: 2147483647;width: ${FS_PANEL_W}px;max-height: ${FS_PANEL_MAX_H}px;background: #ffffff;border-radius: 16px;box-shadow: 0 12px 48px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.08);font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;9 行未改动from { opacity: 0; transform: translateY(-12px) scale(0.96); }to { opacity: 1; transform: translateY(0) scale(1); }}#fs-panel .fs-header {padding: 16px 18px 12px;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: #fff;display: flex;align-items: center;justify-content: space-between;flex-shrink: 0;}#fs-panel .fs-header-left { display: flex; flex-direction: column; gap: 2px; }#fs-panel .fs-header-title { font-size: 15px; font-weight: 600; letter-spacing: 0.5px; }#fs-panel .fs-header-host { font-size: 10px; opacity: 0.7; font-weight: 400; }#fs-panel .fs-header-actions { display: flex; align-items: center; gap: 6px; }#fs-panel .fs-header-gear,#fs-panel .fs-header-close {width: 28px; height: 28px; border-radius: 50%; border: none;background: rgba(255,255,255,0.2); color: #fff; font-size: 16px;cursor: pointer; display: flex; align-items: center; justify-content: center;transition: background 0.15s; line-height: 1;}#fs-panel .fs-header-gear:hover,#fs-panel .fs-header-close:hover { background: rgba(255,255,255,0.35); }#fs-panel .fs-header-gear.fs-gear-active { background: rgba(255,255,255,0.45); }#fs-panel .fs-toggle-row {display: flex; align-items: center; justify-content: space-between;padding: 10px 18px; background: #f8f8ff; border-bottom: 1px solid #eee; flex-shrink: 0;}#fs-panel .fs-toggle-label { font-size: 13px; color: #666; }#fs-panel .fs-toggle-switch { position: relative; width: 44px; height: 24px; cursor: pointer; }#fs-panel .fs-toggle-switch input { opacity: 0; width: 0; height: 0; }#fs-panel .fs-toggle-slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0;background: #ccc; border-radius: 24px; transition: background 0.25s;}#fs-panel .fs-toggle-slider::before {content: ''; position: absolute; width: 18px; height: 18px;left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: transform 0.25s;}#fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider { background: #667eea; }#fs-panel .fs-toggle-switch input:checked + .fs-toggle-slider::before { transform: translateX(20px); }#fs-panel .fs-list-container {flex: 1; overflow-y: auto; padding: 4px 0;scrollbar-width: thin; scrollbar-color: #d0d0d0 transparent;}#fs-panel .fs-list-container::-webkit-scrollbar { width: 5px; }#fs-panel .fs-list-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }#fs-panel .fs-group-title {padding: 8px 18px 4px; font-size: 11px; font-weight: 600;color: #999; text-transform: uppercase; letter-spacing: 1px; user-select: none;}#fs-panel .fs-font-item {display: flex; align-items: center; padding: 7px 12px 7px 18px;cursor: pointer; transition: background 0.12s; gap: 8px;}#fs-panel .fs-font-item:hover { background: #f0f0ff; }#fs-panel .fs-font-item.fs-active { background: #eef0ff; }#fs-panel .fs-font-item .fs-radio {width: 16px; height: 16px; border-radius: 50%; border: 2px solid #ccc;flex-shrink: 0; display: flex; align-items: center; justify-content: center;transition: border-color 0.15s;}#fs-panel .fs-font-item.fs-active .fs-radio { border-color: #667eea; }#fs-panel .fs-font-item.fs-active .fs-radio::after {content: ''; width: 8px; height: 8px; border-radius: 50%; background: #667eea;}#fs-panel .fs-font-item .fs-font-info { flex: 1; min-width: 0; }#fs-panel .fs-font-item .fs-font-name {font-size: 13px; color: #333; white-space: nowrap; overflow: hidden;text-overflow: ellipsis; display: flex; align-items: center; gap: 5px;}#fs-panel .fs-font-item .fs-font-unavail {font-size: 9px; color: #e57373; background: #fff5f5; border: 1px solid #ffcdd2;border-radius: 3px; padding: 0 4px; line-height: 16px; font-weight: 500;flex-shrink: 0; white-space: nowrap;}#fs-panel .fs-font-item.fs-unavail .fs-font-name { color: #bbb; }#fs-panel .fs-font-item.fs-unavail .fs-font-preview { color: #ccc; }#fs-panel .fs-font-item .fs-font-preview {font-size: 12px; color: #888; margin-top: 1px; white-space: nowrap;overflow: hidden; text-overflow: ellipsis;}#fs-panel .fs-font-item .fs-has-settings {font-size: 9px; color: #667eea; margin-left: 4px; font-weight: 600;}#fs-panel .fs-font-item .fs-settings-btn {width: 22px; height: 22px; border-radius: 4px; border: none;background: transparent; color: #bbb; font-size: 13px; cursor: pointer;display: flex; align-items: center; justify-content: center;transition: all 0.15s; flex-shrink: 0; opacity: 0;}#fs-panel .fs-font-item:hover .fs-settings-btn { opacity: 1; }#fs-panel .fs-font-item .fs-settings-btn:hover { background: #e8e8ff; color: #667eea; }#fs-panel .fs-font-item .fs-settings-btn.fs-settings-active { opacity: 1; color: #667eea; }#fs-panel .fs-font-item .fs-delete-btn {width: 22px; height: 22px; border-radius: 4px; border: none;background: transparent; color: #bbb; font-size: 14px; cursor: pointer;display: flex; align-items: center; justify-content: center;transition: all 0.15s; flex-shrink: 0; opacity: 0;}#fs-panel .fs-font-item:hover .fs-delete-btn { opacity: 1; }#fs-panel .fs-font-item .fs-delete-btn:hover { background: #ffe0e0; color: #e55; }#fs-panel .fs-font-settings {background: #f5f5ff; border-bottom: 1px solid #e0e0ee; padding: 10px 18px; display: none;}#fs-panel .fs-font-settings.fs-show { display: block; }#fs-panel .fs-font-settings .fs-settings-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }#fs-panel .fs-font-settings .fs-settings-row:last-child { margin-bottom: 0; }#fs-panel .fs-font-settings .fs-settings-label { font-size: 11px; color: #777; width: 42px; flex-shrink: 0; }#fs-panel .fs-font-settings .fs-settings-input {flex: 1; height: 28px; border: 1px solid #d8d8e8; border-radius: 6px;padding: 0 8px; font-size: 12px; font-family: inherit; outline: none;background: #fff; color: #333; transition: border-color 0.15s;}#fs-panel .fs-font-settings .fs-settings-input:focus { border-color: #667eea; }#fs-panel .fs-font-settings .fs-settings-select {flex: 1; height: 28px; border: 1px solid #d8d8e8; border-radius: 6px;padding: 0 6px; font-size: 12px; font-family: inherit; outline: none;background: #fff; color: #333; cursor: pointer;}#fs-panel .fs-font-settings .fs-settings-hint { font-size: 10px; color: #aaa; margin-top: 4px; }/* ========== 设置视图 ========== */#fs-panel .fs-settings-view {flex: 1; overflow-y: auto; padding: 0;scrollbar-width: thin; scrollbar-color: #d0d0d0 transparent;}#fs-panel .fs-settings-view::-webkit-scrollbar { width: 5px; }#fs-panel .fs-settings-view::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }#fs-panel .fs-sv-section { padding: 12px 18px; border-bottom: 1px solid #f0f0f0; }#fs-panel .fs-sv-section:last-child { border-bottom: none; }#fs-panel .fs-sv-section-title {font-size: 12px; font-weight: 600; color: #888; margin-bottom: 10px;text-transform: uppercase; letter-spacing: 0.5px;}#fs-panel .fs-sv-row { display: flex; align-items: center; justify-content: space-between; padding: 6px 0; min-height: 32px; }#fs-panel .fs-sv-row-label { font-size: 13px; color: #444; flex-shrink: 0; }#fs-panel .fs-sv-row-label small { display: block; font-size: 10px; color: #aaa; font-weight: 400; margin-top: 1px; }#fs-panel .fs-sv-row-right { display: flex; align-items: center; gap: 6px; }#fs-panel .fs-sv-select {height: 30px; border: 1px solid #d8d8e8; border-radius: 6px;padding: 0 8px; font-size: 12px; font-family: inherit; outline: none;background: #fff; color: #333; cursor: pointer; min-width: 100px;}#fs-panel .fs-sv-select:focus { border-color: #667eea; }#fs-panel .fs-sv-range-wrapper { display: flex; align-items: center; gap: 10px; }#fs-panel .fs-sv-range {-webkit-appearance: none; appearance: none; width: 110px; height: 6px;border-radius: 3px;background: linear-gradient(to right, #667eea 0%, #667eea var(--range-pct, 50%), #ddd var(--range-pct, 50%), #ddd 100%);outline: none; cursor: pointer; transition: background 0.1s;}#fs-panel .fs-sv-range::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 18px; height: 18px;border-radius: 50%; background: #fff; border: 3px solid #667eea; cursor: pointer;box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);transition: transform 0.15s, box-shadow 0.15s;}#fs-panel .fs-sv-range::-webkit-slider-thumb:hover {transform: scale(1.15); box-shadow: 0 2px 8px rgba(102, 126, 234, 0.5);}#fs-panel .fs-sv-range::-moz-range-thumb {width: 18px; height: 18px; border-radius: 50%; background: #fff;border: 3px solid #667eea; cursor: pointer; box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);}#fs-panel .fs-sv-range::-moz-range-track { height: 6px; border-radius: 3px; background: #ddd; }#fs-panel .fs-sv-range::-moz-range-progress { height: 6px; border-radius: 3px; background: #667eea; }#fs-panel .fs-sv-range-value {font-size: 12px; color: #667eea; font-weight: 700; min-width: 38px;text-align: right; font-variant-numeric: tabular-nums;}#fs-panel .fs-sv-btn-preview {border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);box-shadow: 0 1px 4px rgba(102, 126, 234, 0.35);transition: width 0.2s ease, height 0.2s ease; flex-shrink: 0;}#fs-panel .fs-sv-toggle { position: relative; width: 44px; height: 24px; cursor: pointer; }#fs-panel .fs-sv-toggle input { opacity: 0; width: 0; height: 0; }#fs-panel .fs-sv-toggle-slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0;background: #ccc; border-radius: 24px; transition: background 0.25s;}#fs-panel .fs-sv-toggle-slider::before {content: ''; position: absolute; width: 18px; height: 18px;left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: transform 0.25s;}#fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider { background: #667eea; }#fs-panel .fs-sv-toggle input:checked + .fs-sv-toggle-slider::before { transform: translateX(20px); }#fs-panel .fs-sv-btn {height: 32px; border: 1px solid #d8d8e8; border-radius: 8px;padding: 0 14px; font-size: 12px; font-family: inherit; cursor: pointer;background: #fff; color: #555; transition: all 0.15s;}#fs-panel .fs-sv-btn:hover { border-color: #667eea; color: #667eea; background: #f5f5ff; }#fs-panel .fs-sv-btn-danger { color: #e55; }#fs-panel .fs-sv-btn-danger:hover { border-color: #e55; color: #e55; background: #fff5f5; }#fs-panel .fs-sv-upload-btn {flex: 1; height: 36px; border: 1.5px dashed #bbb; border-radius: 8px;background: #fff; color: #667eea; font-size: 13px; font-weight: 500;cursor: pointer; transition: border-color 0.15s, background 0.15s;white-space: nowrap; display: flex; align-items: center; justify-content: center; gap: 6px;}#fs-panel .fs-sv-upload-btn:hover { border-color: #667eea; background: #f0f0ff; }#fs-panel .fs-sv-upload-hint { font-size: 10px; color: #aaa; margin-top: 6px; }#fs-toast {position: fixed; z-index: 2147483647; padding: 10px 24px; border-radius: 10px;font-size: 13px; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;color: #fff; pointer-events: none; visibility: hidden; opacity: 0;left: 50%; transform: translateX(-50%) translateY(-12px); top: 24px;white-space: nowrap; transition: opacity 0.3s ease, transform 0.3s ease, visibility 0s 0.3s;}#fs-toast.fs-toast-show {visibility: visible; opacity: 1; transform: translateX(-50%) translateY(0);transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), visibility 0s 0s;}#fs-toast.fs-toast-success { background: #4caf50; }#fs-toast.fs-toast-error { background: #f44336; }#fs-toast.fs-toast-info { background: #667eea; }`;}let fsMainStyleEl = null;function fsInjectStyles() {if (fsMainStyleEl) fsMainStyleEl.remove();fsMainStyleEl = document.createElement('style');fsMainStyleEl.id = 'fs-main-styles';fsMainStyleEl.textContent = fsBuildStyles();document.head.appendChild(fsMainStyleEl);}function fsUpdateStyles() {if (fsMainStyleEl) fsMainStyleEl.textContent = fsBuildStyles();fsTriggerBtn.style.width = FS_BTN_SIZE + 'px';fsTriggerBtn.style.height = FS_BTN_SIZE + 'px';}fsInjectStyles();fsPreviewStyleEl = document.createElement('style');fsPreviewStyleEl.id = 'fs-preview-styles';document.head.appendChild(fsPreviewStyleEl);const fsUiRecoveryStyleEl = document.createElement('style');fsUiRecoveryStyleEl.id = 'fs-ui-recovery';fsUiRecoveryStyleEl.textContent = `#fs-trigger-btn, #fs-trigger-btn *,#fs-overlay,#fs-panel, #fs-panel *,#fs-toast, #fs-toast * {font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif !important;}`;document.head.appendChild(fsUiRecoveryStyleEl);// ==================== DOM 构建 ====================const fsTriggerBtn = document.createElement('button');fsTriggerBtn.id = 'fs-trigger-btn';fsTriggerBtn.title = '字体更换器(可拖拽移动)';fsTriggerBtn.innerHTML = '<span class="fs-btn-icon">Aa</span>';fsTriggerBtn.classList.add(fsGlobalSettings.snapToEdge !== false ? ('fs-side-' + fsBtnSide) : 'fs-free', 'fs-entering');document.body.appendChild(fsTriggerBtn);const fsOverlay = document.createElement('div');fsOverlay.id = 'fs-overlay';document.body.appendChild(fsOverlay);const fsPanel = document.createElement('div');fsPanel.id = 'fs-panel';fsPanel.innerHTML = `<div class="fs-header"><div class="fs-header-left"><span class="fs-header-title">字体更换器</span><span class="fs-header-host">${FS_CURRENT_HOST}</span></div><div class="fs-header-actions"><button class="fs-header-gear" id="fs-header-gear-btn" title="设置">⚙</button><button class="fs-header-close" title="关闭">×</button>5 行未改动<input type="checkbox" id="fs-enabled-toggle"><span class="fs-toggle-slider"></span></label></div><div class="fs-list-container" id="fs-font-list"></div><div class="fs-settings-view" id="fs-settings-view" style="display:none;"></div>`;document.body.appendChild(fsPanel);const fsToast = document.createElement('div');fsToast.id = 'fs-toast';document.body.appendChild(fsToast);const fsFontFileInput = document.createElement('input');fsFontFileInput.type = 'file';fsFontFileInput.id = 'fs-font-file-input';fsFontFileInput.accept = '.woff2,.woff,.ttf,.otf,.eot';fsFontFileInput.multiple = true;fsFontFileInput.style.display = 'none';document.body.appendChild(fsFontFileInput);// ==================== 按钮位置管理 ====================function fsApplyBtnPosition() {fsTriggerBtn.classList.remove('fs-side-left', 'fs-side-right', 'fs-free');if (fsGlobalSettings.snapToEdge) {fsTriggerBtn.style.top = fsBtnY + 'px';fsTriggerBtn.style.left = '';fsTriggerBtn.style.right = '';fsTriggerBtn.classList.add('fs-side-' + fsBtnSide);} else {fsTriggerBtn.style.left = fsBtnX + 'px';fsTriggerBtn.style.right = 'auto';fsTriggerBtn.style.top = fsBtnY + 'px';fsTriggerBtn.classList.add('fs-free');}if (!fsBtnCollapsed) fsTriggerBtn.style.transform = '';}function fsClampBtnPos() {fsBtnY = Math.max(0, Math.min(fsBtnY, window.innerHeight - FS_BTN_SIZE));fsBtnX = Math.max(0, Math.min(fsBtnX, window.innerWidth - FS_BTN_SIZE));}function fsSaveBtnPosition() {fsSaveToStorage(FS_STORAGE_KEY_BTN_POS, { side: fsBtnSide, x: fsBtnX, y: fsBtnY });}// ==================== 收缩 / 展开 ====================function fsCollapseBtn() {if (fsBtnCollapsed || fsPanelVisible) return;if (!fsGlobalSettings.autoCollapse) return;fsBtnCollapsed = true;fsTriggerBtn.classList.add('fs-collapsed');}function fsIsSnapMode() {return fsGlobalSettings.snapToEdge !== false;}function fsExpandBtn() {if (!fsBtnCollapsed) return;fsBtnCollapsed = false;fsTriggerBtn.classList.remove('fs-collapsed');fsResetIdleTimer();}function fsResetIdleTimer() {if (fsIdleTimer) clearTimeout(fsIdleTimer);if (!fsPanelVisible && fsGlobalSettings.autoCollapse) {fsIdleTimer = setTimeout(fsCollapseBtn, FS_IDLE_MS);}}document.addEventListener('mousemove', (e) => {if (!fsBtnCollapsed) return;if (fsIsSnapMode()) {const vx = window.innerWidth;const nearEdge = (fsBtnSide === 'right' && e.clientX > vx - FS_HOVER_ZONE) ||(fsBtnSide === 'left' && e.clientX < FS_HOVER_ZONE);const nearBtnY = e.clientY >= fsBtnY - FS_HOVER_ZONE &&e.clientY <= fsBtnY + FS_BTN_SIZE + FS_HOVER_ZONE;if (nearEdge && nearBtnY) fsExpandBtn();} else {const bx = fsBtnX >= 0 ? fsBtnX : (window.innerWidth - FS_BTN_SIZE - 10);const nearBtn = e.clientX >= bx - FS_HOVER_ZONE &&e.clientX <= bx + FS_BTN_SIZE + FS_HOVER_ZONE &&e.clientY >= fsBtnY - FS_HOVER_ZONE &&e.clientY <= fsBtnY + FS_BTN_SIZE + FS_HOVER_ZONE;if (nearBtn) fsExpandBtn();}});fsTriggerBtn.addEventListener('mouseenter', () => {if (!fsBtnCollapsed) fsResetIdleTimer();});// ==================== 拖拽逻辑 ====================function fsOnPointerDown(e) {if (fsBtnCollapsed) return;if (e.button && e.button !== 0) return;const clientX = e.touches ? e.touches[0].clientX : e.clientX;const clientY = e.touches ? e.touches[0].clientY : e.clientY;fsIsDragging = true;fsHasDragged = false;fsDragStartX = clientX;fsDragStartY = clientY;const rect = fsTriggerBtn.getBoundingClientRect();fsBtnStartLeft = rect.left;fsBtnStartTop = rect.top;e.preventDefault();}function fsOnPointerMove(e) {if (!fsIsDragging) return;const clientX = e.touches ? e.touches[0].clientX : e.clientX;const clientY = e.touches ? e.touches[0].clientY : e.clientY;const dx = clientX - fsDragStartX;const dy = clientY - fsDragStartY;if (!fsHasDragged && Math.abs(dx) < FS_DRAG_THRESHOLD && Math.abs(dy) < FS_DRAG_THRESHOLD) return;if (!fsHasDragged) { fsHasDragged = true; fsClosePanel(); }fsTriggerBtn.style.right = 'auto';fsTriggerBtn.style.left = (fsBtnStartLeft + dx) + 'px';fsTriggerBtn.style.top = (fsBtnStartTop + dy) + 'px';fsTriggerBtn.classList.remove('fs-collapsed');fsTriggerBtn.classList.add('fs-dragging');fsBtnCollapsed = false;e.preventDefault();}function fsOnPointerUp(e) {if (!fsIsDragging) return;fsIsDragging = false;fsTriggerBtn.classList.remove('fs-dragging');if (fsHasDragged) {const rect = fsTriggerBtn.getBoundingClientRect();if (fsIsSnapMode()) {fsBtnSide = (rect.left + rect.width / 2) < window.innerWidth / 2 ? 'left' : 'right';fsBtnY = rect.top;fsClampBtnPos();fsSaveBtnPosition();fsTriggerBtn.style.right = 'auto';fsTriggerBtn.style.left = rect.left + 'px';fsTriggerBtn.style.top = fsBtnY + 'px';fsTriggerBtn.classList.add('fs-snapping');const targetLeft = fsBtnSide === 'left' ? 0 : window.innerWidth - FS_BTN_SIZE;const targetRadius = fsBtnSide === 'left'? `0 ${FS_BTN_SIZE / 2}px ${FS_BTN_SIZE / 2}px 0`: `${FS_BTN_SIZE / 2}px 0 0 ${FS_BTN_SIZE / 2}px`;fsTriggerBtn.style.left = targetLeft + 'px';fsTriggerBtn.style.borderRadius = targetRadius;let snapFinished = false;const finishSnap = () => {if (snapFinished) return;snapFinished = true;fsTriggerBtn.removeEventListener('transitionend', onSnapEnd);fsTriggerBtn.classList.remove('fs-snapping');fsTriggerBtn.style.borderRadius = '';fsApplyBtnPosition();fsResetIdleTimer();setTimeout(() => { fsHasDragged = false; }, 50);};const onSnapEnd = (evt) => { if (evt.propertyName !== 'left') return; finishSnap(); };fsTriggerBtn.addEventListener('transitionend', onSnapEnd);setTimeout(finishSnap, 450);} else {fsBtnX = rect.left;fsBtnY = rect.top;fsClampBtnPos();fsSaveBtnPosition();fsApplyBtnPosition();fsResetIdleTimer();setTimeout(() => { fsHasDragged = false; }, 50);}}}fsTriggerBtn.addEventListener('mousedown', fsOnPointerDown);document.addEventListener('mousemove', fsOnPointerMove);document.addEventListener('mouseup', fsOnPointerUp);fsTriggerBtn.addEventListener('touchstart', fsOnPointerDown, { passive: false });document.addEventListener('touchmove', fsOnPointerMove, { passive: false });document.addEventListener('touchend', fsOnPointerUp);fsTriggerBtn.addEventListener('click', (e) => {if (fsHasDragged || fsBtnCollapsed) return;fsTogglePanel();});window.addEventListener('resize', () => {fsClampBtnPos();fsApplyBtnPosition();if (fsPanelVisible) fsPositionPanel();});// ==================== 面板定位 ====================function fsPositionPanel() {const btnRect = fsTriggerBtn.getBoundingClientRect();const vw = window.innerWidth;const vh = window.innerHeight;const gap = 10;const inwardOffset = FS_BTN_SIZE + 12;let left, top;if (fsIsSnapMode()) {if (fsBtnSide === 'right') {left = btnRect.left - FS_PANEL_W - gap;if (left < FS_MARGIN) left = btnRect.right - FS_PANEL_W + inwardOffset;} else {left = btnRect.right + gap;if (left + FS_PANEL_W > vw - FS_MARGIN) left = btnRect.left - inwardOffset;}} else {left = btnRect.left - FS_PANEL_W - gap;if (left < FS_MARGIN) left = btnRect.right + gap;if (left + FS_PANEL_W > vw - FS_MARGIN) left = btnRect.right - FS_PANEL_W + inwardOffset;}left = Math.max(FS_MARGIN, Math.min(left, vw - FS_PANEL_W - FS_MARGIN));top = btnRect.top;if (top + FS_PANEL_MAX_H > vh - FS_MARGIN) top = vh - FS_PANEL_MAX_H - FS_MARGIN;if (top < FS_MARGIN) top = FS_MARGIN;fsPanel.style.left = left + 'px';fsPanel.style.top = top + 'px';}// ==================== 字体应用(核心) ====================let fsInjectedStyleEl = null;function fsApplyFont(fontValue) {if (fsInjectedStyleEl) { fsInjectedStyleEl.remove(); fsInjectedStyleEl = null; }if (!fontValue || !fsIsEnabled) return;const settings = fsGetFontSettings(fontValue);const fontSize = (settings && settings.size) ? settings.size : '';const fontWeight = (settings && settings.weight) ? settings.weight : '';let extraProps = '';if (fontSize) extraProps += `font-size: ${fontSize} !important;\n`;if (fontWeight) extraProps += `font-weight: ${fontWeight} !important;\n`;const excludeInputs = fsGlobalSettings.excludeInputs;const inputSelector = excludeInputs ? '' : `, input, textarea, select, button`;fsInjectedStyleEl = document.createElement('style');fsInjectedStyleEl.id = 'fs-injected-font';fsInjectedStyleEl.textContent = `html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp,9 行未改动font-family: ${fontValue} !important;${extraProps}}`;document.head.appendChild(fsInjectedStyleEl);}// Blob URL 缓存:fontName -> blobUrl,避免重复创建const fsBlobUrlCache = new Map();/*** 将 dataUrl 转换为 Blob URL(浏览器解析比 dataUrl 快得多)* Blob URL 在页面生命周期内有效,无需每次重新解码 base64*/function fsDataUrlToBlobUrl(dataUrl) {if (fsBlobUrlCache.has(dataUrl)) return fsBlobUrlCache.get(dataUrl);try {const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);if (!match) return dataUrl; // 不是标准 dataUrl,原样返回const mimeType = match[1];const base64 = match[2];const binaryStr = atob(base64);const bytes = new Uint8Array(binaryStr.length);for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i);const blob = new Blob([bytes], { type: mimeType });const blobUrl = URL.createObjectURL(blob);fsBlobUrlCache.set(dataUrl, blobUrl);return blobUrl;} catch (e) {return dataUrl; // 转换失败,回退到 dataUrl}}function fsLoadCustomFontFace(name, url, format) {const id = 'fs-fontface-' + CSS.escape(name.replace(/\s+/g, '-'));if (document.getElementById(id)) return;// 优先使用 Blob URL,提升浏览器解析速度const fontUrl = url.startsWith('data:') ? fsDataUrlToBlobUrl(url) : url;const styleEl = document.createElement('style');styleEl.id = id;const srcStr = format ? `url("${fontUrl}") format("${format}")` : `url("${fontUrl}")`;styleEl.textContent = `@font-face { font-family: "${name}"; src: ${srcStr}; }`;document.head.appendChild(styleEl);}// ==================== 预览样式更新 ====================function fsUpdatePreviewStyles() {const allFonts = [...FS_PRESET_FONTS, ...fsCustomFonts];let css = '';allFonts.forEach((font, i) => {if (font.value) css += `#fs-panel #fs-preview-${i} { font-family: ${font.value} !important; }\n`;});fsPreviewStyleEl.textContent = css;}// ==================== 渲染字体列表 ====================function fsRenderFontList() {const listContainer = document.getElementById('fs-font-list');listContainer.innerHTML = '';let idx = 0;const presetGroup = document.createElement('div');presetGroup.className = 'fs-group-title';presetGroup.textContent = '预置字体';listContainer.appendChild(presetGroup);FS_PRESET_FONTS.forEach(font => {presetGroup.appendChild(fsCreateFontItem(font, false, idx++));});if (fsCustomFonts.length > 0) {const customGroup = document.createElement('div');customGroup.className = 'fs-group-title';customGroup.textContent = '自定义字体(全局)';listContainer.appendChild(customGroup);fsCustomFonts.forEach(font => {customGroup.appendChild(fsCreateFontItem(font, true, idx++));});}fsUpdatePreviewStyles();}function fsCreateFontItem(font, isCustom, index) {const isActive = fsActiveFontValue === font.value;const wrapper = document.createElement('div');const item = document.createElement('div');item.className = 'fs-font-item' + (isActive ? ' fs-active' : '');7 行未改动const nameEl = document.createElement('div');nameEl.className = 'fs-font-name';nameEl.textContent = font.name;if (font.value && !isCustom) {const primaryFont = font.value.split(',')[0].trim().replace(/^"|"$/g, '');if (primaryFont && fsFontAvailability.has(primaryFont) && !fsFontAvailability.get(primaryFont)) {item.classList.add('fs-unavail');const unavailTag = document.createElement('span');unavailTag.className = 'fs-font-unavail';unavailTag.textContent = '未安装';nameEl.appendChild(unavailTag);}}const settings = fsGetFontSettings(font.value);if (settings && (settings.size || settings.weight) && font.value) {const badge = document.createElement('span');badge.className = 'fs-has-settings';let label = '';14 行未改动item.appendChild(info);if (font.value) {const settingsBtn = document.createElement('button');settingsBtn.className = 'fs-settings-btn' + (fsExpandedSettingsSet.has(font.value) ? ' fs-settings-active' : '');settingsBtn.innerHTML = '⚙';settingsBtn.title = '字号/加粗设置';settingsBtn.addEventListener('click', (e) => {e.stopPropagation();fsToggleSettings(font.value, wrapper);});item.appendChild(settingsBtn);}3 行未改动delBtn.innerHTML = '×';delBtn.title = '删除此字体';delBtn.addEventListener('click', (e) => {e.stopPropagation();fsDeleteCustomFont(font);});item.appendChild(delBtn);}item.addEventListener('click', () => fsSelectFont(font));wrapper.appendChild(item);if (font.value) {const settingsPanel = document.createElement('div');settingsPanel.className = 'fs-font-settings' + (fsExpandedSettingsSet.has(font.value) ? ' fs-show' : '');settingsPanel.id = 'fs-settings-' + index;const current = fsGetFontSettings(font.value) || {};settingsPanel.innerHTML = `<div class="fs-settings-row"><span class="fs-settings-label">字号</span>30 行未改动const handler = () => {const fv = input.dataset.fontValue;const field = input.dataset.field;const val = input.value.trim();const s = fsGetFontSettings(fv) || {};if (val) { s[field] = val; } else { delete s[field]; }if (Object.keys(s).length === 0) { fsRemoveFontSettings(fv); } else { fsSetFontSettings(fv, s); }if (fv === fsActiveFontValue) { fsApplyFont(fsActiveFontValue); }const settingsPanelEl = input.closest('.fs-font-settings');if (fsHasNonDefaultSettings(fv)) {fsExpandedSettingsSet.add(fv);if (settingsPanelEl) settingsPanelEl.classList.add('fs-show');} else {fsExpandedSettingsSet.delete(fv);if (settingsPanelEl) settingsPanelEl.classList.remove('fs-show');}const wrapperEl = settingsPanelEl ? settingsPanelEl.previousElementSibling : null;if (wrapperEl) {const gearBtn = wrapperEl.querySelector('.fs-settings-btn');if (gearBtn) {if (fsExpandedSettingsSet.has(fv)) gearBtn.classList.add('fs-settings-active');else gearBtn.classList.remove('fs-settings-active');}}};6 行未改动return wrapper;}function fsToggleSettings(fontValue, wrapper) {if (fsExpandedSettingsSet.has(fontValue)) fsExpandedSettingsSet.delete(fontValue);else fsExpandedSettingsSet.add(fontValue);fsRenderFontList();}// ==================== 字体选择 ====================function fsSelectFont(font) {fsActiveFontValue = font.value;fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, fsActiveFontValue);// 懒加载:选择自定义字体时才注入其 @font-faceif (font.value && fsIsEnabled) {const customFont = fsCustomFonts.find(f => f.value === font.value);if (customFont) {const url = customFont.dataUrl || customFont.url;if (url) fsLoadCustomFontFace(customFont.name, url, customFont.format || null);}fsApplyFont(font.value);} else {fsApplyFont('');}fsRenderFontList();fsShowToast(`已切换为:${font.name}`, 'success');}function fsDeleteCustomFont(font) {fsCustomFonts = fsCustomFonts.filter(f => f.value !== font.value);fsSaveToStorage(FS_STORAGE_KEY_CUSTOM_FONTS, fsCustomFonts);fsRemoveFontSettings(font.value);if (fsActiveFontValue === font.value) {fsActiveFontValue = '';fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, fsActiveFontValue);fsApplyFont('');}const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));const faceEl = document.getElementById(faceId);if (faceEl) faceEl.remove();fsRenderFontList();fsShowToast(`已删除:${font.name}`, 'info');}// ==================== 添加自定义字体 ====================function fsAddUploadedFont(name, dataUrl, format) {const value = `"${name}", sans-serif`;if (fsCustomFonts.some(f => f.name === name)) { fsShowToast('该字体名称已存在', 'error'); return; }fsLoadCustomFontFace(name, dataUrl, format);fsCustomFonts.push({ name, value, dataUrl, format });fsSaveToStorage(FS_STORAGE_KEY_CUSTOM_FONTS, fsCustomFonts);fsRenderFontList();fsShowToast(`已添加字体:${name}`, 'success');}function fsHandleFontFileUpload(files) {if (!files || files.length === 0) return;const validExts = ['.woff2', '.woff', '.ttf', '.otf', '.eot'];const formatMap = { 'woff2': 'woff2', 'woff': 'woff', 'ttf': 'truetype', 'otf': 'opentype', 'eot': 'embedded-opentype' };Array.from(files).forEach(file => {const ext = '.' + file.name.split('.').pop().toLowerCase();if (!validExts.includes(ext)) { fsShowToast(`不支持的格式:${file.name}`, 'error'); return; }const fontName = file.name.replace(/\.[^.]+$/, '');const format = formatMap[ext.replace('.', '')] || 'truetype';if (fsCustomFonts.some(f => f.name === fontName)) { fsShowToast(`字体已存在:${fontName}`, 'error'); return; }const reader = new FileReader();reader.onload = function(e) { fsAddUploadedFont(fontName, e.target.result, format); };reader.onerror = function() { fsShowToast(`读取失败:${file.name}`, 'error'); };reader.readAsDataURL(file);});}/*** 懒加载自定义字体:仅为当前激活的字体注入 @font-face* 非激活字体等到用户选择时再加载,大幅减少页面初始注入量*/function fsReloadCustomFonts() {if (!fsActiveFontValue || !fsIsEnabled) return;// 找到当前激活的自定义字体const activeFont = fsCustomFonts.find(f => f.value === fsActiveFontValue);if (activeFont) {const url = activeFont.dataUrl || activeFont.url;if (url) fsLoadCustomFontFace(activeFont.name, url, activeFont.format || null);}}// ==================== 滑块进度更新工具 ====================function fsUpdateRangeProgress(rangeEl) {const min = parseFloat(rangeEl.min) || 0;const max = parseFloat(rangeEl.max) || 100;const val = parseFloat(rangeEl.value) || min;const pct = ((val - min) / (max - min)) * 100;rangeEl.style.setProperty('--range-pct', pct + '%');}// ==================== 设置视图渲染 ====================function fsRenderSettingsView() {const view = document.getElementById('fs-settings-view');view.innerHTML = '';// --- 外观 ---const secAppearance = document.createElement('div');secAppearance.className = 'fs-sv-section';secAppearance.innerHTML = `<div class="fs-sv-section-title">外观</div>`;const rowBtnSize = document.createElement('div');rowBtnSize.className = 'fs-sv-row';const btnPreviewSize = Math.max(12, Math.round(FS_BTN_SIZE * 0.42));rowBtnSize.innerHTML = `<span class="fs-sv-row-label">按钮大小<small>拖动滑块调整悬浮按钮尺寸</small></span><div class="fs-sv-row-right"><div class="fs-sv-btn-preview" id="fs-sv-btnPreview" style="width:${btnPreviewSize}px;height:${btnPreviewSize}px;"></div><div class="fs-sv-range-wrapper"><input type="range" class="fs-sv-range" id="fs-sv-btnSize"min="28" max="60" step="2" value="${FS_BTN_SIZE}"><span class="fs-sv-range-value" id="fs-sv-btnSize-val">${FS_BTN_SIZE}px</span></div></div>`;secAppearance.appendChild(rowBtnSize);const rowExcludeInputs = document.createElement('div');rowExcludeInputs.className = 'fs-sv-row';rowExcludeInputs.innerHTML = `<span class="fs-sv-row-label">排除输入框<small>不对 input / textarea / select 应用字体</small></span><div class="fs-sv-row-right"><label class="fs-sv-toggle"><input type="checkbox" id="fs-sv-excludeInputs" ${fsGlobalSettings.excludeInputs ? 'checked' : ''}><span class="fs-sv-toggle-slider"></span></label></div>`;secAppearance.appendChild(rowExcludeInputs);view.appendChild(secAppearance);// --- 行为 ---const secBehavior = document.createElement('div');secBehavior.className = 'fs-sv-section';secBehavior.innerHTML = `<div class="fs-sv-section-title">行为</div>`;const rowSnapToEdge = document.createElement('div');rowSnapToEdge.className = 'fs-sv-row';rowSnapToEdge.innerHTML = `<span class="fs-sv-row-label">吸附到边缘<small>拖动后自动贴靠屏幕左/右边缘,关闭后可自由放置</small></span><div class="fs-sv-row-right"><label class="fs-sv-toggle"><input type="checkbox" id="fs-sv-snapToEdge" ${fsGlobalSettings.snapToEdge !== false ? 'checked' : ''}><span class="fs-sv-toggle-slider"></span></label></div>`;secBehavior.appendChild(rowSnapToEdge);const rowAutoCollapse = document.createElement('div');rowAutoCollapse.className = 'fs-sv-row';rowAutoCollapse.innerHTML = `<span class="fs-sv-row-label">自动吸附收起<small>闲置后按钮收缩至屏幕边缘</small></span><div class="fs-sv-row-right"><label class="fs-sv-toggle"><input type="checkbox" id="fs-sv-autoCollapse" ${fsGlobalSettings.autoCollapse ? 'checked' : ''}><span class="fs-sv-toggle-slider"></span></label></div>`;secBehavior.appendChild(rowAutoCollapse);const rowIdleMs = document.createElement('div');rowIdleMs.className = 'fs-sv-row';rowIdleMs.innerHTML = `<span class="fs-sv-row-label">收起延迟<small>闲置多久后自动收起</small></span><div class="fs-sv-row-right"><select class="fs-sv-select" id="fs-sv-idleMs"><option value="3000" ${fsGlobalSettings.idleMs === 3000 ? 'selected' : ''}>3 秒</option><option value="5000" ${fsGlobalSettings.idleMs === 5000 ? 'selected' : ''}>5 秒</option><option value="10000" ${fsGlobalSettings.idleMs === 10000 ? 'selected' : ''}>10 秒</option><option value="15000" ${fsGlobalSettings.idleMs === 15000 ? 'selected' : ''}>15 秒</option><option value="30000" ${fsGlobalSettings.idleMs === 30000 ? 'selected' : ''}>30 秒</option></select></div>`;secBehavior.appendChild(rowIdleMs);const rowToast = document.createElement('div');rowToast.className = 'fs-sv-row';rowToast.innerHTML = `<span class="fs-sv-row-label">提示显示时长<small>操作反馈提示的持续时间</small></span><div class="fs-sv-row-right"><select class="fs-sv-select" id="fs-sv-toastDuration"><option value="1000" ${fsGlobalSettings.toastDuration === 1000 ? 'selected' : ''}>1 秒</option><option value="2000" ${fsGlobalSettings.toastDuration === 2000 ? 'selected' : ''}>2 秒</option><option value="3000" ${fsGlobalSettings.toastDuration === 3000 ? 'selected' : ''}>3 秒</option></select></div>`;secBehavior.appendChild(rowToast);view.appendChild(secBehavior);// --- 字体管理 ---const secFonts = document.createElement('div');7 行未改动<div class="fs-sv-upload-hint">支持 .woff2 / .woff / .ttf / .otf 格式,全局共享</div>`;secFonts.appendChild(rowUpload);if (fsCustomFonts.length > 0) {const rowFontCount = document.createElement('div');rowFontCount.className = 'fs-sv-row';rowFontCount.innerHTML = `<span class="fs-sv-row-label">已导入 ${fsCustomFonts.length} 个自定义字体</span><div class="fs-sv-row-right"><button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-clearFonts">全部清除</button></div>`;secFonts.appendChild(rowFontCount);}view.appendChild(secFonts);// --- 数据 ---const secData = document.createElement('div');18 行未改动<button class="fs-sv-btn fs-sv-btn-danger" id="fs-sv-resetSite">重置</button></div>`;secData.appendChild(rowResetSite);view.appendChild(secData);// ========== 绑定设置事件 ==========const btnSizeRange = document.getElementById('fs-sv-btnSize');const btnSizeVal = document.getElementById('fs-sv-btnSize-val');const btnPreview = document.getElementById('fs-sv-btnPreview');fsUpdateRangeProgress(btnSizeRange);btnSizeRange.addEventListener('input', function() {const val = parseInt(this.value);btnSizeVal.textContent = val + 'px';fsUpdateRangeProgress(this);const previewPx = Math.max(12, Math.round(val * 0.42));btnPreview.style.width = previewPx + 'px';btnPreview.style.height = previewPx + 'px';fsGlobalSettings.btnSize = val;fsSaveGlobalSettings();fsRefreshDerivedSettings();fsUpdateStyles();fsClampBtnPos();fsApplyBtnPosition();});btnSizeRange.addEventListener('change', function() {fsShowToast(`按钮大小已更新为 ${this.value}px`, 'info');});document.getElementById('fs-sv-excludeInputs').addEventListener('change', function() {fsGlobalSettings.excludeInputs = this.checked;fsSaveGlobalSettings();if (fsActiveFontValue && fsIsEnabled) fsApplyFont(fsActiveFontValue);fsShowToast(this.checked ? '已排除输入框' : '输入框将应用字体', 'info');});document.getElementById('fs-sv-snapToEdge').addEventListener('change', function() {fsGlobalSettings.snapToEdge = this.checked;fsSaveGlobalSettings();fsClosePanel();if (this.checked) {const rect = fsTriggerBtn.getBoundingClientRect();fsBtnSide = (rect.left + rect.width / 2) < window.innerWidth / 2 ? 'left' : 'right';fsBtnY = rect.top;fsClampBtnPos();fsSaveBtnPosition();fsTriggerBtn.style.right = 'auto';fsTriggerBtn.style.left = rect.left + 'px';fsTriggerBtn.style.top = fsBtnY + 'px';fsTriggerBtn.classList.remove('fs-side-left', 'fs-side-right', 'fs-free');fsTriggerBtn.classList.add('fs-snapping');const targetLeft = fsBtnSide === 'left' ? 0 : window.innerWidth - FS_BTN_SIZE;const targetRadius = fsBtnSide === 'left'? `0 ${FS_BTN_SIZE / 2}px ${FS_BTN_SIZE / 2}px 0`: `${FS_BTN_SIZE / 2}px 0 0 ${FS_BTN_SIZE / 2}px`;fsTriggerBtn.style.left = targetLeft + 'px';fsTriggerBtn.style.borderRadius = targetRadius;let snapFinished = false;const finishSnap = () => {if (snapFinished) return;snapFinished = true;fsTriggerBtn.removeEventListener('transitionend', onSnapEnd);fsTriggerBtn.classList.remove('fs-snapping');fsTriggerBtn.style.borderRadius = '';fsApplyBtnPosition();fsResetIdleTimer();};const onSnapEnd = (evt) => { if (evt.propertyName !== 'left') return; finishSnap(); };fsTriggerBtn.addEventListener('transitionend', onSnapEnd);setTimeout(finishSnap, 450);} else {const rect = fsTriggerBtn.getBoundingClientRect();fsBtnX = rect.left;fsBtnY = rect.top;if (fsBtnCollapsed) fsExpandBtn();if (fsIdleTimer) clearTimeout(fsIdleTimer);fsClampBtnPos();fsSaveBtnPosition();fsApplyBtnPosition();fsResetIdleTimer();}fsShowToast(this.checked ? '已开启边缘吸附' : '已关闭边缘吸附,可自由拖动', 'info');});document.getElementById('fs-sv-autoCollapse').addEventListener('change', function() {fsGlobalSettings.autoCollapse = this.checked;fsSaveGlobalSettings();fsRefreshDerivedSettings();if (this.checked) fsResetIdleTimer();else { if (fsIdleTimer) clearTimeout(fsIdleTimer); if (fsBtnCollapsed) fsExpandBtn(); }fsShowToast(this.checked ? '已开启自动收起' : '已关闭自动收起', 'info');});document.getElementById('fs-sv-idleMs').addEventListener('change', function() {fsGlobalSettings.idleMs = parseInt(this.value);fsSaveGlobalSettings();fsRefreshDerivedSettings();fsResetIdleTimer();fsShowToast(`收起延迟已更新`, 'info');});document.getElementById('fs-sv-toastDuration').addEventListener('change', function() {fsGlobalSettings.toastDuration = parseInt(this.value);fsSaveGlobalSettings();fsShowToast(`提示时长已更新`, 'info');});document.getElementById('fs-sv-upload-btn').addEventListener('click', () => { fsFontFileInput.click(); });const clearBtn = document.getElementById('fs-sv-clearFonts');if (clearBtn) {clearBtn.addEventListener('click', () => {if (!confirm('确认清除所有自定义字体?此操作不可撤销。')) return;fsCustomFonts.forEach(font => {const faceId = 'fs-fontface-' + CSS.escape(font.name.replace(/\s+/g, '-'));const faceEl = document.getElementById(faceId);if (faceEl) faceEl.remove();fsRemoveFontSettings(font.value);});if (fsCustomFonts.some(f => f.value === fsActiveFontValue)) {fsActiveFontValue = '';fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, fsActiveFontValue);fsApplyFont('');}fsCustomFonts = [];fsSaveToStorage(FS_STORAGE_KEY_CUSTOM_FONTS, fsCustomFonts);fsRenderSettingsView();fsShowToast('已清除所有自定义字体', 'info');});}document.getElementById('fs-sv-resetPos').addEventListener('click', () => {fsBtnSide = 'right'; fsBtnY = 60; fsBtnX = -1;fsSaveBtnPosition(); fsApplyBtnPosition(); fsClosePanel();fsShowToast('按钮位置已重置', 'info');});document.getElementById('fs-sv-resetSite').addEventListener('click', () => {if (!confirm('确认重置当前站点的所有字体设置?')) return;fsActiveFontValue = ''; fsIsEnabled = true; fsFontSettings = {};fsSaveToStorage(FS_STORAGE_KEY_ACTIVE_FONT, '');fsSaveToStorage(FS_STORAGE_KEY_ENABLED, true);fsSaveToStorage(FS_STORAGE_KEY_FONT_SETTINGS, {});fsApplyFont('');document.getElementById('fs-enabled-toggle').checked = true;fsExpandedSettingsSet.clear();fsRenderFontList(); fsClosePanel();fsShowToast('当前站点设置已重置', 'info');});}// ==================== 设置视图切换 ====================function fsToggleSettingsView() {fsSettingsViewActive = !fsSettingsViewActive;const listContainer = document.getElementById('fs-font-list');const settingsView = document.getElementById('fs-settings-view');const gearBtn = document.getElementById('fs-header-gear-btn');const toggleRow = fsPanel.querySelector('.fs-toggle-row');if (fsSettingsViewActive) {listContainer.style.display = 'none';toggleRow.style.display = 'none';settingsView.style.display = 'block';gearBtn.classList.add('fs-gear-active');fsRenderSettingsView();} else {listContainer.style.display = '';toggleRow.style.display = '';settingsView.style.display = 'none';2 行未改动}// ==================== 面板控制 ====================function fsTogglePanel() {fsPanelVisible = !fsPanelVisible;if (fsPanelVisible) {if (fsSettingsViewActive) fsToggleSettingsView();fsPositionPanel();fsPanel.classList.add('fs-show');fsOverlay.classList.add('fs-show');fsTriggerBtn.classList.add('fs-active');if (fsIdleTimer) clearTimeout(fsIdleTimer);} else {fsPanel.classList.remove('fs-show');fsOverlay.classList.remove('fs-show');fsTriggerBtn.classList.remove('fs-active');if (fsSettingsViewActive) {fsSettingsViewActive = false;document.getElementById('fs-font-list').style.display = '';fsPanel.querySelector('.fs-toggle-row').style.display = '';document.getElementById('fs-settings-view').style.display = 'none';document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');}fsResetIdleTimer();}}function fsClosePanel() {if (!fsPanelVisible) return;fsPanelVisible = false;fsPanel.classList.remove('fs-show');fsOverlay.classList.remove('fs-show');fsTriggerBtn.classList.remove('fs-active');if (fsSettingsViewActive) {fsSettingsViewActive = false;document.getElementById('fs-font-list').style.display = '';fsPanel.querySelector('.fs-toggle-row').style.display = '';document.getElementById('fs-settings-view').style.display = 'none';document.getElementById('fs-header-gear-btn').classList.remove('fs-gear-active');}fsResetIdleTimer();}// ==================== Toast ====================let fsToastTimer = null;let fsToastHideTimer = null;function fsShowToast(msg, type = 'info') {if (fsToastTimer) clearTimeout(fsToastTimer);if (fsToastHideTimer) clearTimeout(fsToastHideTimer);fsToast.textContent = msg;fsToast.className = 'fs-toast-' + type + ' fs-toast-show';fsToastTimer = setTimeout(() => {fsToast.classList.remove('fs-toast-show');fsToastHideTimer = setTimeout(() => { fsToast.className = ''; fsToastHideTimer = null; }, 320);fsToastTimer = null;}, fsGlobalSettings.toastDuration || 2000);}// ==================== 事件绑定 ====================fsOverlay.addEventListener('click', fsClosePanel);fsPanel.querySelector('.fs-header-close').addEventListener('click', fsClosePanel);document.getElementById('fs-header-gear-btn').addEventListener('click', (e) => {e.stopPropagation();fsToggleSettingsView();});const fsEnabledToggle = document.getElementById('fs-enabled-toggle');fsEnabledToggle.checked = fsIsEnabled;fsEnabledToggle.addEventListener('change', () => {fsIsEnabled = fsEnabledToggle.checked;fsSaveToStorage(FS_STORAGE_KEY_ENABLED, fsIsEnabled);if (fsIsEnabled && fsActiveFontValue) fsApplyFont(fsActiveFontValue);else fsApplyFont('');fsShowToast(fsIsEnabled ? `字体替换已启用(${FS_CURRENT_HOST})` : `字体替换已关闭(${FS_CURRENT_HOST})`, 'info');});fsFontFileInput.addEventListener('change', (e) => {fsHandleFontFileUpload(e.target.files);e.target.value = '';if (fsSettingsViewActive) fsRenderSettingsView();});// ==================== 初始化 ====================function fsInitExpandedSettings() {const allFonts = [...FS_PRESET_FONTS, ...fsCustomFonts];allFonts.forEach(font => {if (font.value && fsHasNonDefaultSettings(font.value)) fsExpandedSettingsSet.add(font.value);});}function fsInit() {fsDetectAllFonts();fsReloadCustomFonts();fsInitExpandedSettings();fsRenderFontList();fsClampBtnPos();fsApplyBtnPosition();if (fsIsEnabled && fsActiveFontValue) fsApplyFont(fsActiveFontValue);setTimeout(() => { fsTriggerBtn.classList.remove('fs-entering'); }, 500);fsResetIdleTimer();}// ================================================================// 主入口:初始化五个模块// ================================================================function main() {// 字体更换器:所有站点运行fsInit();// BZOJ 测试点模块:仅 bzoj.org 下运行(init 内部有双重判断)BZOJ_TestcaseModule.init();// BZOJ 题目 Markdown 查看/复制:仅 /p/<id> 题目详情页运行(init 内部有路径与结构双重判断)BZOJ_ProblemMarkdownModule.init();// BZOJ 题目列表「提交」快捷列:仅题库/比赛/作业/训练列表页运行BZOJ_SubmitLinkModule.init();// BZOJ 成绩表增强:仅 /contest/<hex>/scoreboard 和 /homework/<hex>/scoreboard 运行BZOJ_ScoreboardModule.init();}if (document.readyState === 'complete' || document.readyState === 'interactive') {main();} else {document.addEventListener('DOMContentLoaded', main);}})();```