跳到正文

个人记录

3个可爱的小插件

Fanciful约 177 分钟
原文
文章信息与版本

文章信息

发布
2026年10月21日
收录
2026年10月21日
更新
2026年11月20日
篇幅
约 177 分钟

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1

也是成功写出来!!! (我写完,文心一言帮我完善了一下),感谢 @ArknightsEndfield 让我借鉴了她的背景插件她的qwq。

一。武侠风luogu背景插件(墨韵传书(洛谷专属)请配合第二个插件使用)

我是折叠框
JavaScript
// ==UserScript==
// @name         墨韵壁(通用背景 · 水墨武侠风)
// @namespace    https://www.luogu.com.cn/user/1276929
// @version      1.6.10 更换版本+1.6最后一版+结束文本修缮版
// @description  为任意网页挂一幅水墨之壁:支持本地图画/影像与外境图链、手动/自动换景、墨晕渐显过渡、可拖动墨印、面板内置画谱说明;支持在控制面板显示当前版本。
// @author       Crepuscule_oublie
// @license      MIT
// @match        *://*/*
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_notification
// @run-at       document-idle
// ==/UserScript==

(function() {
	'use strict';

	// ===== 黑名单 =====
	const BLACKLIST = [
		//'oier.baoshuo.dev',建议这一行保留,删掉注释
	];

	// ===== 只在顶层窗口运行(防止 iframe 嵌套导致重复加载) =====
	let isTopWindow = false;
	try {
		isTopWindow = (window.top === window.self);
	} catch (e) {
		isTopWindow = false;
	}
	if (!isTopWindow) {
		console.log('[背景脚本] 当前在 iframe 中,跳过执行');
		return;
	}

	const host = window.location.hostname;
	const isBlocked = BLACKLIST.some(pattern => {
		if (pattern.startsWith('.')) {
			// 匹配子域名:.example.com 匹配 example.com 和 *.example.com
			return host === pattern.slice(1) || host.endsWith(pattern);
		}
		if (pattern.includes('*')) {
			const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
			return regex.test(host);
		}
		// 精确匹配完整域名,避免子串误匹配
		return host === pattern || host.endsWith('.' + pattern);
	});

	if (isBlocked) {
		console.log('[背景脚本] 当前网站已在黑名单中,跳过执行');
		return;
	}


	// ===== 配置 =====
	const DB_NAME = 'BgDB';
	const STORE_NAME = 'media';
	const MAX_SIZE = 100 * 1024 * 1024; // 100MB
	const DEFAULT_OPACITY = 0.3;
	const DEFAULT_BLUR = 0;
	const DEFAULT_BRIGHTNESS = 100;
	const DEFAULT_Z_INDEX = 0;
	const DEFAULT_AUTO_SWITCH = false;
	const DEFAULT_INTERVAL_HOURS = 0;
	const DEFAULT_INTERVAL_MINUTES = 0;
	const DEFAULT_INTERVAL_SECONDS = 10;
	const BTN_POS_KEY = 'ug_bg_btn_pos';

	// 管理 Blob URL,防止内存泄漏
	const activeBlobUrls = new Set();
	const thumbBlobUrls = new Set();

	function createObjectURL(blob) {
		const url = URL.createObjectURL(blob);
		activeBlobUrls.add(url);
		return url;
	}

	function createThumbURL(blob) {
		const url = URL.createObjectURL(blob);
		thumbBlobUrls.add(url);
		return url;
	}

	function revokeObjectURL(url) {
		if (url && activeBlobUrls.has(url)) {
			URL.revokeObjectURL(url);
			activeBlobUrls.delete(url);
		}
	}

	function revokeThumbURL(url) {
		if (url && thumbBlobUrls.has(url)) {
			URL.revokeObjectURL(url);
			thumbBlobUrls.delete(url);
		}
	}

	function revokeAllObjectURLs() {
		activeBlobUrls.forEach(url => URL.revokeObjectURL(url));
		activeBlobUrls.clear();
		thumbBlobUrls.forEach(url => URL.revokeObjectURL(url));
		thumbBlobUrls.clear();
	}

	// 页面卸载时释放所有资源
	window.addEventListener('beforeunload', revokeAllObjectURLs);

	// ----- IndexedDB -----
	function openDB() {
		return new Promise((resolve, reject) => {
			const req = indexedDB.open(DB_NAME, 1);
			req.onupgradeneeded = e => {
				const db = e.target.result;
				if (!db.objectStoreNames.contains(STORE_NAME)) {
					db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
				}
			};
			req.onsuccess = e => resolve(e.target.result);
			req.onerror = e => reject(e.target.error);
		});
	}

	async function dbSave(data, type, mime) {
		const db = await openDB();
		const tx = db.transaction(STORE_NAME, 'readwrite');
		const store = tx.objectStore(STORE_NAME);
		return new Promise((resolve, reject) => {
			const req = store.add({ data, type, mime, timestamp: Date.now() });
			req.onsuccess = () => resolve(req.result);
			req.onerror = () => reject(req.error);
			tx.oncomplete = () => resolve(req.result);
			tx.onerror = () => reject(tx.error);
		});
	}

	// 只获取媒体元数据列表(不加载二进制数据),避免内存暴涨
	async function dbGetAllMeta() {
		const db = await openDB();
		const tx = db.transaction(STORE_NAME, 'readonly');
		const store = tx.objectStore(STORE_NAME);
		return new Promise((resolve, reject) => {
			const results = [];
			const req = store.openCursor();
			req.onsuccess = e => {
				const cursor = e.target.result;
				if (cursor) {
					const val = cursor.value;
					// 只保留元数据,不返回大的data字段
					results.push({
						id: val.id,
						type: val.type,
						mime: val.mime,
						timestamp: val.timestamp,
						size: val.data ? (val.data.byteLength || val.data.length) : 0
					});
					cursor.continue();
				} else {
					resolve(results);
				}
			};
			req.onerror = () => reject(req.error);
		});
	}

	// 获取单个完整媒体
	async function dbGetById(id) {
		const db = await openDB();
		const tx = db.transaction(STORE_NAME, 'readonly');
		const store = tx.objectStore(STORE_NAME);
		return new Promise((resolve, reject) => {
			const req = store.get(id);
			req.onsuccess = () => resolve(req.result);
			req.onerror = () => reject(req.error);
		});
	}

	async function dbClear() {
		const db = await openDB();
		const tx = db.transaction(STORE_NAME, 'readwrite');
		const store = tx.objectStore(STORE_NAME);
		return new Promise((resolve, reject) => {
			const req = store.clear();
			req.onsuccess = () => resolve();
			req.onerror = () => reject(req.error);
		});
	}

	async function dbDelete(id) {
		const db = await openDB();
		const tx = db.transaction(STORE_NAME, 'readwrite');
		const store = tx.objectStore(STORE_NAME);
		return new Promise((resolve, reject) => {
			const req = store.delete(id);
			req.onsuccess = () => resolve();
			req.onerror = () => reject(req.error);
		});
	}

	// ----- 工具 -----
	function blobToArrayBuffer(blob) {
		return new Promise((resolve, reject) => {
			const r = new FileReader();
			r.onload = () => resolve(r.result);
			r.onerror = reject;
			r.readAsArrayBuffer(blob);
		});
	}

	function fileToDataURL(file) {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.onload = () => resolve(reader.result);
			reader.onerror = reject;
			reader.readAsDataURL(file);
		});
	}

	function mediaToUrl(media) {
		if (media.type === 'image') {
			if (typeof media.data === 'string' && media.data.startsWith('data:')) {
				return media.data;
			}
			try {
				const blob = new Blob([media.data], { type: media.mime });
				return createObjectURL(blob);
			} catch (e) {
				return null;
			}
		} else if (media.type === 'video') {
			try {
				const blob = new Blob([media.data], { type: media.mime });
				return createObjectURL(blob);
			} catch (e) {
				return null;
			}
		}
		return null;
	}

	function formatSize(bytes) {
		if (bytes < 1024) return bytes + 'B';
		if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
		return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
	}

	// 防抖函数
	function debounce(fn, delay = 200) {
		let timer;
		return function(...args) {
			clearTimeout(timer);
			timer = setTimeout(() => fn.apply(this, args), delay);
		};
	}

	// 解析时间输入,强制为非负整数:负数一律按 0 处理,非法值回退到 fallback
	function toNonNegInt(value, fallback = 0) {
		const n = parseInt(value, 10);
		if (isNaN(n)) return fallback;
		return n < 0 ? 0 : n;
	}

	// ----- 样式 -----
	GM_addStyle(`
	/* ================= 墨韵壁 · 水墨武侠风(宣纸 / 浓墨 / 朱砂) ================= */

	/* ---- 背景层 ---- */
	#ug-bg-layer {
		position: fixed;
		top: 0; left: 0;
		width: 100vw; height: 100vh;
		z-index: 0 !important;
		pointer-events: none !important;
		overflow: hidden;
		background: transparent !important;
	}
	#ug-bg-layer .ug-bg-media {
		position: absolute;
		top: 0; left: 0;
		width: 100%; height: 100%;
		object-fit: cover;
		transition: opacity 0.5s ease, filter 0.5s ease;
		opacity: 0;
		transform: translateZ(0);
		will-change: opacity, filter;
	}
	#ug-bg-layer .ug-bg-media.active { opacity: 1; }
	#ug-bg-layer video, #ug-bg-layer img {
		width: 100%; height: 100%;
		object-fit: cover;
		position: absolute;
		top: 0; left: 0;
	}

	/* ---- 壁面(设置面板):一纸素宣 ---- */
	#ug-bg-panel {
		position: fixed;
		z-index: 9999999;
		top: 100px;
		left: 100px;
		width: 332px;
		max-height: 80vh;
		overflow-y: auto;
		padding: 15px 16px 17px;
		color: #2b2823;
		font-family: "Songti SC", "STSong", "Noto Serif CJK SC", "SimSun", serif;
		font-size: 13px;
		border: 1px solid rgba(35,33,30,0.5);
		border-radius: 2px;
		background:
			repeating-linear-gradient(0deg, rgba(255,255,255,0.45) 0 2px, rgba(236,226,208,0.3) 2px 4px),
			linear-gradient(160deg, rgba(250,245,235,0.98) 0%, rgba(241,233,217,0.98) 58%, rgba(233,222,201,0.98) 100%);
		box-shadow:
			inset 0 0 0 4px rgba(250,246,237,0.96),
			inset 0 0 0 5px rgba(35,33,30,0.15),
			inset 0 0 34px rgba(176,160,130,0.28),
			0 16px 42px rgba(18,16,13,0.4);
		opacity: 0;
		visibility: hidden;
		transform: translateY(6px);
		transition: opacity 0.28s ease, visibility 0.28s ease, transform 0.28s ease;
		scrollbar-width: thin;
		scrollbar-color: rgba(35,33,30,0.32) transparent;
	}
	#ug-bg-panel:not(.collapsed) {
		opacity: 1;
		visibility: visible;
		transform: translateY(0);
	}
	#ug-bg-panel.collapsed { pointer-events: none; }
	#ug-bg-panel::-webkit-scrollbar { width: 6px; }
	#ug-bg-panel::-webkit-scrollbar-track { background: transparent; }
	#ug-bg-panel::-webkit-scrollbar-thumb {
		background: rgba(35,33,30,0.26);
		border-radius: 3px;
	}

	#ug-bg-panel .pk-head {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		padding-bottom: 9px;
		border-bottom: 1px solid rgba(35,33,30,0.22);
	}
	#ug-bg-panel .pk-title {
		font-weight: 700;
		font-size: 15px;
		letter-spacing: 2px;
		color: #1f1d1a;
	}
	#ug-bg-panel .pk-title .seal {
		display: inline-block;
		margin-left: 6px;
		padding: 0 3px;
		font-size: 10px;
		line-height: 14px;
		letter-spacing: 0;
		color: #a8332a;
		background: rgba(168,51,42,0.07);
		border: 1px solid rgba(168,51,42,0.6);
		border-radius: 1px;
		vertical-align: 2px;
	}
	#ug-bg-panel .pk-sep {
		margin-top: 10px;
		padding-top: 9px;
		border-top: 1px dashed rgba(35,33,30,0.25);
	}
	#ug-bg-panel .pk-sub {
		font-size: 12px;
		color: #7a7266;
		letter-spacing: 1px;
	}
	#ug-bg-panel .pk-foot {
		margin-top: 12px;
		font-size: 11px;
		color: #948a78;
		text-align: center;
		letter-spacing: 0.5px;
	}

	#ug-bg-panel .row {
		display: flex;
		gap: 6px;
		margin: 6px 0;
		flex-wrap: wrap;
		align-items: center;
	}
	#ug-bg-panel .btn {
		padding: 5px 11px;
		border: 1px solid rgba(35,33,30,0.45);
		border-radius: 2px;
		background: rgba(255,253,247,0.72);
		color: #2b2823;
		font-family: inherit;
		font-size: 12px;
		letter-spacing: 0.5px;
		cursor: pointer;
		transition: background 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
	}
	#ug-bg-panel .btn:hover {
		background: rgba(35,33,30,0.88);
		color: #f7f1e6;
		box-shadow: 0 2px 10px rgba(18,16,13,0.26);
	}
	#ug-bg-panel .btn-primary {
		background: rgba(35,33,30,0.9);
		color: #f7f1e6;
		border-color: rgba(35,33,30,0.9);
	}
	#ug-bg-panel .btn-primary:hover {
		background: #151412;
		color: #fffdf8;
		box-shadow: 0 0 12px rgba(35,33,30,0.3);
	}
	#ug-bg-panel .btn-secondary {
		background: rgba(255,253,247,0.72);
		color: #4a443a;
	}
	#ug-bg-panel .btn-danger {
		background: rgba(255,253,247,0.72);
		color: #a8332a;
		border-color: rgba(168,51,42,0.55);
	}
	#ug-bg-panel .btn-danger:hover {
		background: rgba(168,51,42,0.9);
		color: #fbf3e6;
		box-shadow: 0 2px 10px rgba(140,38,31,0.3);
	}
	#ug-bg-panel .btn-success {
		background: rgba(255,253,247,0.72);
		color: #2f5d4b;
		border-color: rgba(47,93,75,0.5);
	}
	#ug-bg-panel .btn-success:hover {
		background: rgba(47,93,75,0.9);
		color: #f3f7f2;
		box-shadow: 0 2px 10px rgba(31,66,53,0.3);
	}
	#ug-bg-panel .btn-sm { padding: 4px 9px; font-size: 11.5px; }

	/* 画谱入口:朱砂细印 */
	#ug-bg-panel .help-entry {
		background: rgba(168,51,42,0.1);
		color: #8e2b23;
		border-color: rgba(168,51,42,0.45);
	}
	#ug-bg-panel .help-entry:hover {
		background: rgba(168,51,42,0.9);
		color: #fbf3e6;
	}

	#ug-bg-panel .media-list {
		display: flex;
		flex-wrap: wrap;
		gap: 7px;
		margin-top: 7px;
	}
	#ug-bg-panel .media-item {
		position: relative;
		width: 52px; height: 52px;
		border: 1px solid rgba(35,33,30,0.35);
		border-radius: 2px;
		background: rgba(255,253,247,0.8);
		cursor: pointer;
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: inset 0 0 8px rgba(170,155,126,0.35);
		transition: box-shadow 0.2s ease, border-color 0.2s ease;
	}
	#ug-bg-panel .media-item:hover { border-color: rgba(35,33,30,0.62); }
	#ug-bg-panel .media-item.active {
		border-color: #a8332a;
		box-shadow: 0 0 0 1px rgba(168,51,42,0.5), 0 0 10px rgba(168,51,42,0.32), inset 0 0 6px rgba(168,51,42,0.16);
	}
	#ug-bg-panel .media-item.active::after {
		content: '现';
		position: absolute;
		right: 1px;
		bottom: 1px;
		width: 13px;
		height: 13px;
		line-height: 13px;
		text-align: center;
		font-size: 9px;
		color: #fbf3e6;
		background: rgba(168,51,42,0.92);
		border-radius: 1px;
	}
	#ug-bg-panel .media-item img {
		width: 100%; height: 100%;
		object-fit: cover;
	}
	#ug-bg-panel .media-item .video-icon { font-size: 19px; }
	#ug-bg-panel .media-item .del {
		position: absolute;
		top: 0; right: 0;
		width: 15px; height: 15px;
		line-height: 15px;
		padding: 0;
		border: none;
		background: rgba(168,51,42,0.82);
		color: #fbf3e6;
		font-family: inherit;
		font-size: 10px;
		cursor: pointer;
		border-radius: 0 1px 0 1px;
	}
	#ug-bg-panel .media-item .del:hover { background: rgba(140,38,31,1); }
	#ug-bg-panel .media-item .img-placeholder { color: #7d7462; }

	#ug-bg-panel .hint {
		font-size: 11px;
		color: #857b69;
		margin-top: 4px;
		letter-spacing: 0.3px;
	}

	#ug-bg-panel .slider-group {
		display: flex;
		align-items: center;
		gap: 9px;
		margin: 7px 0;
	}
	#ug-bg-panel .slider-group label {
		min-width: 42px;
		font-size: 12px;
		color: #5b5446;
		text-align: right;
		letter-spacing: 1px;
	}
	#ug-bg-panel input[type="range"] {
		flex: 1;
		-webkit-appearance: none;
		appearance: none;
		height: 3px;
		border-radius: 2px;
		background: linear-gradient(90deg, rgba(35,33,30,0.72), rgba(35,33,30,0.16));
		outline: none;
	}
	#ug-bg-panel input[type="range"]::-webkit-slider-thumb {
		-webkit-appearance: none;
		width: 15px; height: 15px;
		border-radius: 50%;
		background: radial-gradient(circle at 35% 30%, #4c4740 0%, #23211e 62%, #131211 100%);
		border: 1px solid rgba(247,241,230,0.85);
		box-shadow: 0 1px 5px rgba(18,16,13,0.45);
		cursor: pointer;
	}
	#ug-bg-panel input[type="range"]::-moz-range-thumb {
		width: 14px; height: 14px;
		border-radius: 50%;
		background: #23211e;
		border: 1px solid rgba(247,241,230,0.85);
		cursor: pointer;
	}
	#ug-bg-panel .val-display {
		min-width: 38px;
		text-align: center;
		font-size: 11px;
		color: #4a4438;
		background: rgba(255,253,247,0.78);
		border: 1px solid rgba(35,33,30,0.25);
		border-radius: 2px;
		padding: 1px 5px;
	}

	#ug-bg-panel .auto-input {
		width: 42px;
		padding: 2px 4px;
		text-align: center;
		font-size: 12px;
		color: #2b2823;
		background: rgba(255,253,247,0.85);
		border: 1px solid rgba(35,33,30,0.35);
		border-radius: 2px;
		font-family: inherit;
	}
	#ug-bg-panel .auto-input:focus {
		outline: none;
		border-color: rgba(35,33,30,0.75);
		box-shadow: 0 0 0 2px rgba(35,33,30,0.12);
	}
	#ug-bg-panel .auto-status {
		font-size: 11px;
		color: #7a7266;
		margin-top: 5px;
		letter-spacing: 0.5px;
	}

	#ug-bg-panel .url-input {
		flex: 1;
		min-width: 168px;
		padding: 5px 9px;
		font-size: 12px;
		color: #2b2823;
		background: rgba(255,253,247,0.85);
		border: 1px solid rgba(35,33,30,0.35);
		border-radius: 2px;
		font-family: inherit;
	}
	#ug-bg-panel .url-input:focus {
		outline: none;
		border-color: rgba(35,33,30,0.75);
		box-shadow: 0 0 0 2px rgba(35,33,30,0.12);
	}
	#ug-bg-panel .url-input::placeholder { color: #9c9382; }

	/* ---- 墨印(悬浮按钮):宣纸墨印、飞白墨晕、朱砂小钤 ---- */
	#ug-bg-toggle-btn {
		position: fixed;
		bottom: 30px;
		right: 30px;
		z-index: 9999998;
		width: 56px; height: 56px;
		border-radius: 50%;
		background: radial-gradient(circle at 34% 26%, #fffdf7 0%, #f7f0e4 38%, #ead9c0 72%, #d7c4a5 100%);
		border: 1px solid rgba(35,33,30,0.55);
		color: #1f1d1a;
		font-size: 27px;
		line-height: 1;
		font-family: "STKaiti", "KaiTi", "Kaiti SC", "Songti SC", "Noto Serif CJK SC", "SimSun", serif;
		cursor: grab;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow:
			0 0 0 3px rgba(246,240,229,0.5),
			0 8px 22px rgba(18,16,13,0.35),
			inset 0 0 14px rgba(150,132,104,0.35);
		text-shadow: 0 1px 0 rgba(255,255,255,0.75);
		user-select: none;
		touch-action: none;
		transition: box-shadow 0.25s ease, transform 0.15s ease, color 0.2s ease;
	}
	#ug-bg-toggle-btn::before {
		content: '';
		position: absolute;
		top: -7px; left: -7px; right: -7px; bottom: -7px;
		border-radius: 50%;
		background:
			radial-gradient(circle at 22% 78%, rgba(35,33,30,0.14) 0%, rgba(35,33,30,0) 44%),
			radial-gradient(circle at 78% 20%, rgba(35,33,30,0.1) 0%, rgba(35,33,30,0) 40%);
		pointer-events: none;
	}
	#ug-bg-toggle-btn::after {
		content: '';
		position: absolute;
		right: 5px;
		bottom: 7px;
		width: 9px; height: 9px;
		background: rgba(168,51,42,0.85);
		border-radius: 1px;
		pointer-events: none;
	}
	#ug-bg-toggle-btn:hover {
		color: #000;
		box-shadow:
			0 0 0 3px rgba(246,240,229,0.62),
			0 10px 26px rgba(18,16,13,0.45),
			0 0 18px rgba(60,52,40,0.3),
			inset 0 0 14px rgba(120,104,80,0.45);
	}
	#ug-bg-toggle-btn:active {
		cursor: grabbing;
		transform: scale(0.96);
	}

	/* ---- 飞白提示 ---- */
	#ug-bg-toast {
		position: fixed;
		z-index: 9999999;
		max-width: 320px;
		padding: 8px 15px;
		background: rgba(31,29,26,0.93);
		color: #f6efe3;
		font-family: "Songti SC", "Noto Serif CJK SC", "SimSun", serif;
		font-size: 12.5px;
		letter-spacing: 0.6px;
		border: 1px solid rgba(246,239,227,0.32);
		border-radius: 2px;
		box-shadow: 0 8px 22px rgba(18,16,13,0.38);
		opacity: 0;
		transition: opacity 0.3s ease;
		pointer-events: none;
	}
	#ug-bg-toast.show { opacity: 1; }

	/* ---- 画谱(使用说明):线装古页 ---- */
	#ug-bg-help-mask {
		position: fixed;
		top: 0; left: 0; right: 0; bottom: 0;
		z-index: 10000000;
		background: rgba(24,22,19,0.55);
		backdrop-filter: blur(3px);
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0;
		visibility: hidden;
		transition: opacity 0.25s ease, visibility 0.25s ease;
	}
	#ug-bg-help-mask.show { opacity: 1; visibility: visible; }

	#ug-bg-help {
		width: 400px;
		max-width: 90vw;
		max-height: 80vh;
		overflow-y: auto;
		padding: 18px 20px 20px;
		color: #2b2823;
		font-family: "Songti SC", "STSong", "Noto Serif CJK SC", "SimSun", serif;
		font-size: 13px;
		line-height: 1.75;
		border: 1px solid rgba(35,33,30,0.5);
		border-radius: 2px;
		background:
			repeating-linear-gradient(90deg, rgba(224,211,186,0.35) 0 1px, rgba(0,0,0,0) 1px 24px),
			linear-gradient(165deg, #faf5eb 0%, #f1e9d9 62%, #e9ddc5 100%);
		box-shadow:
			inset 0 0 0 4px rgba(250,246,237,0.95),
			inset 0 0 0 5px rgba(35,33,30,0.15),
			inset 0 0 30px rgba(176,160,130,0.25),
			0 22px 60px rgba(15,13,11,0.5);
		transform: translateY(12px) scale(0.98);
		transition: transform 0.25s ease;
		scrollbar-width: thin;
		scrollbar-color: rgba(35,33,30,0.32) transparent;
	}
	#ug-bg-help::-webkit-scrollbar { width: 6px; }
	#ug-bg-help::-webkit-scrollbar-thumb {
		background: rgba(35,33,30,0.26);
		border-radius: 3px;
	}
	#ug-bg-help-mask.show #ug-bg-help { transform: translateY(0) scale(1); }

	#ug-bg-help .help-head {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 16px;
		font-weight: 700;
		letter-spacing: 2px;
		color: #1f1d1a;
		margin-bottom: 10px;
		padding-bottom: 9px;
		border-bottom: 1px solid rgba(35,33,30,0.3);
	}
	#ug-bg-help .help-close {
		width: 24px; height: 24px;
		line-height: 22px;
		padding: 0;
		background: rgba(255,253,247,0.72);
		color: #a8332a;
		border: 1px solid rgba(168,51,42,0.45);
		border-radius: 2px;
		font-family: inherit;
		font-size: 12px;
		letter-spacing: 0;
		cursor: pointer;
	}
	#ug-bg-help .help-close:hover {
		background: rgba(168,51,42,0.9);
		color: #fbf3e6;
	}
	#ug-bg-help .help-intro {
		color: #7a7266;
		font-size: 12px;
		margin: 0 0 12px;
	}
	#ug-bg-help .help-sec { margin-bottom: 12px; }
	#ug-bg-help .help-sec-title {
		font-weight: 700;
		color: #23211e;
		margin-bottom: 4px;
		letter-spacing: 1px;
	}
	#ug-bg-help .help-sec ul {
		margin: 0;
		padding-left: 18px;
		color: #4e483d;
	}
	#ug-bg-help .help-sec li { margin: 3px 0; }
	#ug-bg-help .help-sec b { color: #8e2b23; font-weight: 700; }
	#ug-bg-help .help-tip {
		margin-top: 12px;
		padding: 8px 11px;
		background: rgba(168,51,42,0.08);
		border-left: 2px solid rgba(168,51,42,0.55);
		color: #8e2b23;
		font-size: 12px;
	}

	#ug-bg-help .help-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 14px;
		border-top: 1px dashed rgba(60,50,40,0.25);
		margin-top: 8px;
	}
	#ug-bg-help .help-page-btn {
		padding: 6px 14px;
		background: rgba(60,50,40,0.05);
		border: 1px solid rgba(60,50,40,0.25);
		border-radius: 2px;
		color: #2c2c2c;
		font-size: 13px;
		cursor: pointer;
		font-family: inherit;
		transition: all 0.2s ease;
	}
	#ug-bg-help .help-page-btn:hover:not(:disabled) {
		background: rgba(60,50,40,0.15);
		border-color: rgba(60,50,40,0.45);
	}
	#ug-bg-help .help-page-btn:disabled {
		opacity: 0.4;
		cursor: not-allowed;
	}
	#ug-bg-help .help-page-indicator {
		font-size: 13px;
		color: #555;
	}
	#ug-bg-help .help-page-indicator .page-num {
		display: inline-block;
		width: 20px;
		text-align: center;
		transition: all 0.2s ease;
	}
	#ug-bg-help .help-page-indicator .page-num.active {
		color: #2c2c2c;
		font-weight: 600;
		font-size: 15px;
	}
	#ug-bg-help .help-page-indicator .page-sep {
		margin: 0 4px;
		color: #888;
	}

`);

	// ----- Toast -----
	function showToast(msg, duration = 2000) {
		let t = document.getElementById('ug-bg-toast');
		if (!t) {
			t = document.createElement('div');
			t.id = 'ug-bg-toast';
			document.body.appendChild(t);
		}
		t.textContent = msg;
		// Toast位置跟随按钮
		const btn = document.getElementById('ug-bg-toggle-btn');
		if (btn) {
			const btnRect = btn.getBoundingClientRect();
			t.style.left = btnRect.left + 'px';
			t.style.bottom = (window.innerHeight - btnRect.top + 12) + 'px';
			t.style.right = 'auto';
			t.style.top = 'auto';
		} else {
			t.style.bottom = '90px';
			t.style.right = '30px';
			t.style.left = 'auto';
		}
		t.classList.add('show');
		clearTimeout(t._timer);
		t._timer = setTimeout(() => t.classList.remove('show'), duration);
	}

		// ===== 小助手(使用方法) =====
	let helpMask = null;
	let helpCurrentPage = 1;
	const HELP_TOTAL_PAGES = 2;

	function buildHelpHtml() {
		return `
		<div id="ug-bg-help">
			<div class="help-head">
				<span>📜 凌霄秘录 <b> 1.6.10版</span>
				<button class="help-close" id="ug-help-close">✕</button>
			</div>
			<div class="help-body">
				<div class="help-page" data-page="1">
					<p class="help-intro">为任意网页挂一幅墨韵之壁:可收本地图画、影像与外境图链,悬于正文之后,换景时墨晕渐显,不夺页面本味。</p>

					<div class="help-sec">
						<div class="help-sec-title">一 · 启壁与移印</div>
						<ul>
							<li>点右下角 <b>「墨」</b> 印即启壁,再点一次收壁。</li>
							<li>按住 <b>「墨」</b> 印可拖至任意处,壁面随印而行。</li>
							<li>欲再看谱,点壁面题头 <b>📜 凌霄秘录</b> 即可。</li>
						</ul>
					</div>

					<div class="help-sec">
						<div class="help-sec-title">二 · 入景</div>
						<ul>
							<li><b>🖼️ 入画</b>:收此地图画入壁(JPG/PNG/GIF/WebP 等,≤100MB)。</li>
							<li><b>🎞️ 存影</b>:收此地影像入壁(MP4/WebM 等,≤100MB),静音循环不绝。</li>
							<li><b>🌐 引景</b>:收外界图链,无须入藏灵台。</li>
						</ul>
					</div>

					<div class="help-sec">
						<div class="help-sec-title">三 · 换景与删景</div>
						<ul>
							<li>于 <b>灵台景致</b> 中点任意小图换景,墨晕渐显过渡。</li>
							<li>小图右上 <b>×</b> 删其一,<b>🗑️ 清卷</b> 尽删诸景。</li>
							<li>小图皆显真容,无须猜测所藏何景。</li>
						</ul>
					</div>

					<div class="help-sec">
						<div class="help-sec-title">四 · 调景</div>
						<ul>
							<li><b>晕染 / 明暗 / 浓淡</b>:拖滑杆即时见其效。</li>
							<li><b>层级</b>:数越大景越靠前,最底为 0,可调 0–10。</li>
						</ul>
					</div>

					<div class="help-sec">
						<div class="help-sec-title">五 · 景随时换</div>
						<ul>
							<li>填 时 / 分 / 秒 之隔,点 <b>▶ 启</b> 定时轮转诸景。</li>
							<li>点 <b>⏹ 止</b> 收功,间隔不得少于 1 秒。</li>
						</ul>
					</div>

					<div class="help-sec">
						<div class="help-sec-title">六 · 墨韵传书(洛谷专属)</div>
						<ul>
							<li>【功能未开放,敬请期待】 可以暂时与我的另一个插件进行搭配,或自行融合使用。</li>
                            <li>浏览洛谷时,若有新私信送达,自动弹出<b>桌面通知</b>与<b>页面水墨提示</b>。</li>
							<li>通知停留五秒自消,点通知可直达私信会话,点 ✕ 可即时关闭。</li>
							<li>首次使用请允许桌面通知权限,否则仅页面内提示。【貌似是多余的】</li>
						</ul>
					</div>

					<div class="help-tip">⚠️ 时辰之数不可为负,误填负数自归其零。</div>
				</div>

				<div class="help-page" data-page="2" style="display: none; text-align: center; padding-top: 40px;">
					<div style="font-size: 22px; color: #9a2c20; font-weight: bold; margin-bottom: 30px; letter-spacing: 2px; text-shadow: 1px 1px 2px rgba(0,0,0,0.1);">
						Crepuscule_oublie 独家制作
					</div>
					<div style="font-size: 15px; color: #555; margin-bottom: 50px; line-height: 2;">
						墨韵成壁,万象入画<br>
						江湖路远,后会有期
					</div>
					<a href="https://www.luogu.com.cn/user/1276929" target="_blank" rel="noopener noreferrer"
					   style="display: inline-block; padding: 12px 30px; background: #5b8c85; color: #fff;
							  text-decoration: none; border-radius: 2px; font-size: 15px;
							  border: 1px solid #3d6b65; box-shadow: 2px 2px 6px rgba(0,0,0,0.15);
							  transition: all 0.2s ease;">
						🏯 访问作者洛谷主页
					</a>
				</div>
			</div>
			<div class="help-footer">
				<button class="help-page-btn" id="help-prev" disabled>← 上一页</button>
				<span class="help-page-indicator">
					<span class="page-num active" data-page="1">1</span>
					<span class="page-sep">/</span>
					<span class="page-num" data-page="2">2</span>
				</span>
				<button class="help-page-btn" id="help-next">下一页 →</button>
			</div>
		</div>`;
	}

	function renderHelpPage() {
		if (!helpMask) return;
		// 切换页面显示
		helpMask.querySelectorAll('.help-page').forEach(page => {
			const pageNum = parseInt(page.dataset.page);
			page.style.display = pageNum === helpCurrentPage ? 'block' : 'none';
		});
		// 更新页码高亮
		helpMask.querySelectorAll('.page-num').forEach(num => {
			const pageNum = parseInt(num.dataset.page);
			num.classList.toggle('active', pageNum === helpCurrentPage);
		});
		// 更新按钮状态
		const prevBtn = helpMask.querySelector('#help-prev');
		const nextBtn = helpMask.querySelector('#help-next');
		if (prevBtn) prevBtn.disabled = helpCurrentPage === 1;
		if (nextBtn) nextBtn.disabled = helpCurrentPage === HELP_TOTAL_PAGES;
	}

	function showHelp() {
		if (!document.body) return;
		// 如果旧弹窗存在先移除
		if (helpMask && helpMask.parentNode) {
			helpMask.parentNode.removeChild(helpMask);
			helpMask = null;
		}
		// 打开默认回到第一页
		helpCurrentPage = 1;
		helpMask = document.createElement('div');
		helpMask.id = 'ug-bg-help-mask';
		helpMask.innerHTML = buildHelpHtml();
		document.body.appendChild(helpMask);
		const closeHandler = () => hideHelp();
		helpMask.addEventListener('click', e => {
			if (e.target === helpMask) closeHandler();
		});
		const closeBtn = helpMask.querySelector('#ug-help-close');
		if (closeBtn) closeBtn.addEventListener('click', closeHandler);
		// 翻页按钮事件
		const prevBtn = helpMask.querySelector('#help-prev');
		const nextBtn = helpMask.querySelector('#help-next');
		if (prevBtn) prevBtn.addEventListener('click', () => {
			if (helpCurrentPage > 1) {
				helpCurrentPage--;
				renderHelpPage();
			}
		});
		if (nextBtn) nextBtn.addEventListener('click', () => {
			if (helpCurrentPage < HELP_TOTAL_PAGES) {
				helpCurrentPage++;
				renderHelpPage();
			}
		});
		// 初始化第一页状态
		renderHelpPage();
		// Esc键关闭
		const escHandler = (e) => {
			if (e.key === 'Escape') {
				closeHandler();
				document.removeEventListener('keydown', escHandler);
			}
		};
		document.addEventListener('keydown', escHandler);
		requestAnimationFrame(() => helpMask.classList.add('show'));
	}

	function hideHelp() {
		if (helpMask) {
			helpMask.classList.remove('show');
			setTimeout(() => {
				if (helpMask && helpMask.parentNode) {
					helpMask.parentNode.removeChild(helpMask);
				}
				helpMask = null;
			}, 300);
		}
	}

	// ===== 状态管理 =====
	function loadState() {
		try {
			const raw = localStorage.getItem('ug_bg_state');
			if (raw) {
				const parsed = JSON.parse(raw);
				if (parsed.opacity === undefined || parsed.opacity === null) parsed.opacity = DEFAULT_OPACITY;
				if (parsed.blur === undefined || parsed.blur === null) parsed.blur = DEFAULT_BLUR;
				if (parsed.brightness === undefined || parsed.brightness === null) parsed.brightness = DEFAULT_BRIGHTNESS;
				if (parsed.zIndex === undefined || parsed.zIndex === null) parsed.zIndex = DEFAULT_Z_INDEX;
				// 兼容旧的负z-index配置,自动修正为0
				if (parsed.zIndex < 0) parsed.zIndex = 0;
				if (parsed.autoSwitch === undefined || parsed.autoSwitch === null) parsed.autoSwitch = DEFAULT_AUTO_SWITCH;
				if (parsed.intervalHours === undefined || parsed.intervalHours === null) parsed.intervalHours = DEFAULT_INTERVAL_HOURS;
				if (parsed.intervalMinutes === undefined || parsed.intervalMinutes === null) parsed.intervalMinutes = DEFAULT_INTERVAL_MINUTES;
				if (parsed.intervalSeconds === undefined || parsed.intervalSeconds === null) parsed.intervalSeconds = DEFAULT_INTERVAL_SECONDS;
				return parsed;
			}
		} catch (e) {}
		return {
			selectedId: null,
			opacity: DEFAULT_OPACITY,
			blur: DEFAULT_BLUR,
			brightness: DEFAULT_BRIGHTNESS,
			zIndex: DEFAULT_Z_INDEX,
			autoSwitch: DEFAULT_AUTO_SWITCH,
			intervalHours: DEFAULT_INTERVAL_HOURS,
			intervalMinutes: DEFAULT_INTERVAL_MINUTES,
			intervalSeconds: DEFAULT_INTERVAL_SECONDS
		};
	}

	function saveState(state) {
		localStorage.setItem('ug_bg_state', JSON.stringify(state));
	}

	// ===== 应用层级 =====
	function applyZIndex(zIndex) {
		const layer = document.getElementById('ug-bg-layer');
		if (layer) {
			layer.style.setProperty('z-index', String(zIndex), 'important');
		}
	}

	// ===== 滤镜应用 =====
	function applyFilter(blur, brightness, el) {
		if (!el) {
			const layer = document.getElementById('ug-bg-layer');
			if (layer) el = layer.querySelector('.ug-bg-media.active');
		}
		if (el) {
			el.style.filter = `blur(${blur || 0}px) brightness(${(brightness || 100) / 100})`;
		}
	}

	// ===== 队列式切换核心逻辑(融合版:模糊淡入过渡 + 竞态防护) =====
	let switchQueue = [];
	let isSwitching = false;
	let currentRenderToken = 0;

	function renderBg(media) {
		if (switchQueue.length >= 5) {
			switchQueue.shift();
		}
		switchQueue.push(media);
		processQueue();
	}

	async function processQueue() {
		if (isSwitching || switchQueue.length === 0) return;
		isSwitching = true;

		const media = switchQueue.shift();
		try {
			await executeBackgroundChange(media);
		} catch (e) {
			console.error('[背景] 切换异常:', e);
		} finally {
			isSwitching = false;
			if (switchQueue.length > 0) {
				processQueue();
			}
		}
	}

	async function executeBackgroundChange(media) {
		// 竞态token
		currentRenderToken++;
		const myToken = currentRenderToken;

		let layer = document.getElementById('ug-bg-layer');
		if (!layer) {
			layer = document.createElement('div');
			layer.id = 'ug-bg-layer';
			const parent = document.body || document.documentElement;
			if (parent) parent.prepend(layer);
			else return;
		}

		if (!media) {
			// 清空背景时释放所有Blob URL
			layer.querySelectorAll('.ug-bg-media').forEach(el => {
				if (el.src && el.src.startsWith('blob:')) {
					revokeObjectURL(el.src);
				}
			});
			layer.innerHTML = '';
			resetAutoTimer();
			return;
		}

		const state = loadState();
		const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY;
		const currentZIndex = Math.max(0, state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX);
		const currentBlur = state.blur || 0;
		const currentBrightness = state.brightness || 100;

		layer.style.position = 'fixed';
		layer.style.top = '0';
		layer.style.left = '0';
		layer.style.width = '100vw';
		layer.style.height = '100vh';
		layer.style.overflow = 'hidden';
		layer.style.display = 'block';
		layer.style.background = 'transparent';
		layer.style.setProperty('z-index', String(currentZIndex), 'important');
		layer.style.setProperty('pointer-events', 'none', 'important');
		layer.style.setProperty('opacity', String(currentOpacity), 'important');

		// 获取 URL
		let url;
		let isRemote = false;
		if (media.type === 'remote') {
			const sep = media.data.includes('?') ? '&' : '?';
			url = media.data + sep + '_t=' + Date.now();
			isRemote = true;
		} else {
			url = mediaToUrl(media);
			if (!url) {
				showToast('❌ 化景未成,请另择其图');
				return;
			}
		}

		const oldActiveEl = layer.querySelector('.ug-bg-media.active');

		let newEl;
		let hasError = false;
		if (media.type === 'video') {
			newEl = document.createElement('video');
			newEl.src = url;
			newEl.muted = true;
			newEl.loop = true;
			newEl.playsInline = true;
			newEl.preload = 'auto';
			newEl.addEventListener('loadeddata', () => {
				newEl.play().catch(() => {});
			});
			newEl.onerror = () => {
				hasError = true;
				if (myToken !== currentRenderToken) return;
				showToast('❌ 影像难显,或其格式不容');
				if (newEl.parentNode) newEl.remove();
				if (newEl.src && newEl.src.startsWith('blob:')) {
					revokeObjectURL(newEl.src);
				}
			};
		} else {
			newEl = document.createElement('img');
			if (isRemote) {
				newEl.referrerPolicy = 'no-referrer';
			}
			newEl.src = url;
			newEl.onerror = () => {
				hasError = true;
				if (myToken !== currentRenderToken) return;
				showToast('❌ 图画难显,或被外站所禁');
				if (newEl.parentNode) newEl.remove();
				// 远程URL不需要revoke
				if (newEl.src && newEl.src.startsWith('blob:')) {
					revokeObjectURL(newEl.src);
				}
			};
		}

		newEl.className = 'ug-bg-media';
		newEl.style.transition = 'none';
		newEl.style.filter = `blur(30px) brightness(${currentBrightness / 100})`;
		newEl.style.opacity = '0';

		layer.appendChild(newEl);

		// 等待加载完成(最多等10秒,超时放弃)
		let loaded = false;
		const loadPromise = new Promise(resolve => {
			const finish = () => { if (!loaded) { loaded = true; resolve(); } };
			if (media.type === 'video') {
				if (newEl.readyState >= 2) finish();
				else newEl.addEventListener('loadeddata', finish, { once: true });
			} else {
				if (newEl.complete && newEl.naturalWidth > 0) finish();
				else newEl.addEventListener('load', finish, { once: true });
			}
			// 10秒超时
			setTimeout(finish, 10000);
		});

		await loadPromise;

		if (myToken !== currentRenderToken) {
			// 这是旧的加载,清理掉
			if (newEl.parentNode) newEl.remove();
			if (newEl.src && newEl.src.startsWith('blob:')) {
				revokeObjectURL(newEl.src);
			}
			return;
		}

		if (hasError) return;

		// 开始模糊淡入过渡
		void newEl.offsetWidth; // 触发重绘
		newEl.style.transition = '';
		newEl.classList.add('active');
		newEl.style.opacity = '1';

		// 旧元素淡出
		if (oldActiveEl && oldActiveEl !== newEl) {
			oldActiveEl.classList.remove('active');
			oldActiveEl.style.filter = `blur(30px) brightness(${currentBrightness / 100})`;
			oldActiveEl.style.opacity = '0';
			setTimeout(() => {
				if (oldActiveEl.parentNode) oldActiveEl.remove();
				if (oldActiveEl.src && oldActiveEl.src.startsWith('blob:')) {
					revokeObjectURL(oldActiveEl.src);
				}
			}, 600);
		}

		// 滤镜平滑过渡到目标值
		setTimeout(() => {
			newEl.style.filter = `blur(${currentBlur}px) brightness(${currentBrightness / 100})`;
		}, 50);

		if (media.type === 'video') {
			newEl.play().catch(() => {});
		}

		resetAutoTimer();
	}

	// ===== 自动切换相关 =====
	let switchTimer = null;

	async function switchToNextBg() {
		const all = await dbGetAllMeta();
		if (all.length === 0) {
			showToast('⚠️ 灵台无景可换');
			return;
		}
		const state = loadState();
		let currentId = state.selectedId;
		if (!currentId || !all.some(m => m.id === currentId)) {
			currentId = all[0].id;
		} else {
			const index = all.findIndex(m => m.id === currentId);
			const nextIndex = (index + 1) % all.length;
			currentId = all[nextIndex].id;
		}
		// 只获取需要显示的单个媒体数据
		const media = await dbGetById(currentId);
		if (media) {
			state.selectedId = currentId;
			saveState(state);
			renderBg(media);
			const p = document.getElementById('ug-bg-panel');
			if (p && !p.classList.contains('collapsed')) {
				await showPanel(state);
			}
		}
	}

	function startAutoSwitch() {
		stopAutoSwitch();
		const state = loadState();
		const hours = toNonNegInt(state.intervalHours, 0);
		const minutes = toNonNegInt(state.intervalMinutes, 0);
		const seconds = toNonNegInt(state.intervalSeconds, 0);
		const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;
		if (totalMs < 1000) {
			showToast('⚠️ 轮转之隔不得少于 1 秒');
			return;
		}
		state.autoSwitch = true;
		saveState(state);
		switchTimer = setInterval(switchToNextBg, totalMs);
		updateAutoStatus(true, totalMs);
		showToast(`✅ 景随时换已启(每 ${hours}时 ${minutes}分 ${seconds}秒)`);
	}

	function stopAutoSwitch() {
		if (switchTimer) {
			clearInterval(switchTimer);
			switchTimer = null;
		}
		const state = loadState();
		state.autoSwitch = false;
		saveState(state);
		updateAutoStatus(false, 0);
		showToast('⏹️ 景随时换已止');
	}

	function resetAutoTimer() {
		const state = loadState();
		if (state.autoSwitch) {
			if (switchTimer) {
				clearInterval(switchTimer);
				switchTimer = null;
			}
			const hours = toNonNegInt(state.intervalHours, 0);
			const minutes = toNonNegInt(state.intervalMinutes, 0);
			const seconds = toNonNegInt(state.intervalSeconds, 0);
			const totalMs = (hours * 3600 + minutes * 60 + seconds) * 1000;
			if (totalMs >= 1000) {
				state.autoSwitch = true;
				saveState(state);
				switchTimer = setInterval(switchToNextBg, totalMs);
				updateAutoStatus(true, totalMs);
			} else {
				state.autoSwitch = false;
				saveState(state);
				updateAutoStatus(false, 0);
			}
		}
	}

	function updateAutoStatus(isRunning, intervalMs) {
		const statusEl = document.getElementById('ug-auto-status');
		if (statusEl) {
			if (isRunning) {
				const sec = Math.floor(intervalMs / 1000);
				const h = Math.floor(sec / 3600);
				const m = Math.floor((sec % 3600) / 60);
				const s = sec % 60;
				statusEl.textContent = `✅ 轮转中(每 ${h}时 ${m}分 ${s}秒)`;
				statusEl.style.color = '#2f5d4b';
			} else {
				statusEl.textContent = '⏹️ 已止';
				statusEl.style.color = '#7a7266';
			}
		}
	}

	// ===== 面板位置跟随按钮 =====
	function updatePanelPosition() {
		const p = document.getElementById('ug-bg-panel');
		const btn = document.getElementById('ug-bg-toggle-btn');
		if (!p || !btn) return;
		if (p.classList.contains('collapsed')) return;

		const btnRect = btn.getBoundingClientRect();
		const panelW = p.offsetWidth || 320;
		const panelH = p.offsetHeight || 400;
		const gap = 12;
		const margin = 10;

		let left;
		// 优先放在按钮左边
		if (btnRect.left - gap - panelW >= margin) {
			left = btnRect.left - gap - panelW;
		}
		// 左边放不下放右边
		else if (btnRect.right + gap + panelW <= window.innerWidth - margin) {
			left = btnRect.right + gap;
		}
		// 两边都放不下,居中对齐
		else {
			left = Math.max(margin, Math.min(window.innerWidth - panelW - margin, btnRect.left + btnRect.width / 2 - panelW / 2));
		}

		// 垂直方向:优先放在按钮上方,放不下放下方
		let top;
		if (btnRect.top - gap - panelH >= margin) {
			top = btnRect.top - panelH;
		} else if (btnRect.bottom + gap + panelH <= window.innerHeight - margin) {
			top = btnRect.bottom + gap;
		} else {
			// 上下都放不下,靠上边缘对齐
			top = margin;
		}

		p.style.left = left + 'px';
		p.style.top = top + 'px';
		p.style.right = 'auto';
		p.style.bottom = 'auto';

		// Toast位置也跟随
		const t = document.getElementById('ug-bg-toast');
		if (t) {
			t.style.left = btnRect.left + 'px';
			t.style.bottom = (window.innerHeight - btnRect.top + 12) + 'px';
			t.style.right = 'auto';
			t.style.top = 'auto';
		}
	}

	// ===== 可拖动按钮 =====
	let dragRafId = null;
	let pendingLeft = null, pendingTop = null;

	function createToggleButton() {
		if (document.getElementById('ug-bg-toggle-btn')) return;
		if (!document.body) {
			setTimeout(createToggleButton, 100);
			return;
		}

		const btn = document.createElement('div');
		btn.id = 'ug-bg-toggle-btn';
		btn.textContent = '墨';

		try {
			const pos = JSON.parse(localStorage.getItem(BTN_POS_KEY) || 'null');
			if (pos && typeof pos.left === 'number' && typeof pos.top === 'number') {
				const maxLeft = Math.max(0, window.innerWidth - 56);
				const maxTop = Math.max(0, window.innerHeight - 56);
				const left = Math.min(Math.max(0, pos.left), maxLeft);
				const top = Math.min(Math.max(0, pos.top), maxTop);
				btn.style.left = left + 'px';
				btn.style.top = top + 'px';
				btn.style.right = 'auto';
				btn.style.bottom = 'auto';
			}
		} catch (e) {}

		let isDragging = false;
		let hasMoved = false;
		let startX = 0, startY = 0, startLeft = 0, startTop = 0;

		btn.addEventListener('pointerdown', (e) => {
			if (e.button !== 0 && e.pointerType === 'mouse') return;
			isDragging = true;
			hasMoved = false;
			startX = e.clientX;
			startY = e.clientY;
			const rect = btn.getBoundingClientRect();
			startLeft = rect.left;
			startTop = rect.top;
			try { btn.setPointerCapture(e.pointerId); } catch (err) {}
			e.preventDefault();
		});

		// requestAnimationFrame丝滑拖动
		function flushDragPosition() {
			if (pendingLeft !== null) {
				btn.style.left = pendingLeft + 'px';
				btn.style.top = pendingTop + 'px';
				btn.style.right = 'auto';
				btn.style.bottom = 'auto';
				pendingLeft = null;
				pendingTop = null;
				// 面板实时跟随
				updatePanelPosition();
			}
			dragRafId = null;
		}

		btn.addEventListener('pointermove', (e) => {
			if (!isDragging) return;
			const dx = e.clientX - startX;
			const dy = e.clientY - startY;
			if (!hasMoved && (Math.abs(dx) > 3 || Math.abs(dy) > 3)) {
				hasMoved = true;
			}
			if (!hasMoved) return;
			const w = btn.offsetWidth || 48;
			const h = btn.offsetHeight || 48;
			pendingLeft = Math.max(0, Math.min(window.innerWidth - w, startLeft + dx));
			pendingTop = Math.max(0, Math.min(window.innerHeight - h, startTop + dy));
			if (!dragRafId) {
				dragRafId = requestAnimationFrame(flushDragPosition);
			}
		});

		const saveButtonPosition = debounce(() => {
			const left = parseInt(btn.style.left, 10) || 0;
			const top = parseInt(btn.style.top, 10) || 0;
			localStorage.setItem(BTN_POS_KEY, JSON.stringify({ left, top }));
		}, 100);

		const endDrag = (e) => {
			if (!isDragging) return;
			isDragging = false;
			if (dragRafId) {
				cancelAnimationFrame(dragRafId);
				dragRafId = null;
				flushDragPosition();
			}
			try { btn.releasePointerCapture(e.pointerId); } catch (err) {}
			if (hasMoved) {
				saveButtonPosition();
				updatePanelPosition();
			}
		};

		btn.addEventListener('pointerup', endDrag);
		btn.addEventListener('pointercancel', endDrag);

		btn.addEventListener('click', (e) => {
			if (hasMoved) {
				e.stopPropagation();
				e.preventDefault();
				hasMoved = false;
				return;
			}
			togglePanel();
		});

		document.body.appendChild(btn);
	}

	// ===== 面板 =====
	let panelVisible = false;
	let panel = null;

	async function togglePanel() {
		panelVisible = !panelVisible;
		if (panelVisible) {
			const state = loadState();
			await showPanel(state);
		} else {
			const p = document.getElementById('ug-bg-panel');
			if (p) p.classList.add('collapsed');
		}
	}

	// 生成视频首帧缩略图
	async function generateVideoThumbnail(media) {
		return new Promise((resolve) => {
			try {
				const blob = new Blob([media.data], { type: media.mime });
				const url = createObjectURL(blob);
				const video = document.createElement('video');
				video.src = url;
				video.muted = true;
				video.playsInline = true;
				video.preload = 'auto';
				video.crossOrigin = 'anonymous';
				const timeout = setTimeout(() => {
					revokeObjectURL(url);
					resolve(null);
				}, 5000);
				video.addEventListener('loadeddata', () => {
					clearTimeout(timeout);
					try {
						video.currentTime = 0.1;
					} catch (e) {}
				});
				video.addEventListener('seeked', () => {
					try {
						const canvas = document.createElement('canvas');
						canvas.width = 100;
						canvas.height = 100;
						const ctx = canvas.getContext('2d');
						ctx.drawImage(video, 0, 0, 100, 100);
						canvas.toBlob((thumbBlob) => {
							revokeObjectURL(url);
							if (thumbBlob) {
								resolve(createThumbURL(thumbBlob));
							} else {
								resolve(null);
							}
						}, 'image/jpeg', 0.7);
					} catch (e) {
						revokeObjectURL(url);
						resolve(null);
					}
				});
				video.addEventListener('error', () => {
					clearTimeout(timeout);
					revokeObjectURL(url);
					resolve(null);
				});
			} catch (e) {
				resolve(null);
			}
		});
	}

	async function showPanel(state) {
		// 如果面板已存在,先释放旧的缩略图URL
		if (panel) {
			panel.querySelectorAll('.media-item img').forEach(img => {
				if (img.src && img.src.startsWith('blob:') && thumbBlobUrls.has(img.src)) {
					revokeThumbURL(img.src);
				}
			});
		}

		if (!panel) {
			panel = document.createElement('div');
			panel.id = 'ug-bg-panel';
			panel.classList.add('collapsed');
			document.body.appendChild(panel);
		}

		// 只获取元数据,不加载完整二进制
		const all = await dbGetAllMeta();
		let listHtml = '';
		if (all.length === 0) {
			listHtml = '<span class="hint">灵台尚无景致,先「入画」或「存影」</span>';
		} else {
			listHtml = all.map(m => {
				const active = m.id === state.selectedId ? 'active' : '';
				if (m.type === 'remote') {
					return `<div class="media-item ${active}" data-id="${m.id}" title="外境图链: ${m.data}">
					<span style="font-size:20px;">🌐</span>
					<button class="del" data-id="${m.id}">×</button>
					</div>`;
				}
				if (m.type === 'video') {
					return `<div class="media-item ${active}" data-id="${m.id}" data-type="video" title="影 ${formatSize(m.size)}">
					<div class="img-placeholder" style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:14px;position:relative;">
						<span class="video-icon">🎬</span>
						<span style="position:absolute;top:1px;left:2px;font-size:10px;">🎞️</span>
					</div>
					<button class="del" data-id="${m.id}">×</button>
					</div>`;
				}
				// 图片:占位符,懒加载缩略图
				return `<div class="media-item ${active}" data-id="${m.id}" data-type="image" title="画 ${formatSize(m.size)}">
				<div class="img-placeholder" style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:14px;">🖼️</div>
				<button class="del" data-id="${m.id}">×</button>
				</div>`;
			}).join('');
		}

		const currentOpacity = state.opacity !== undefined ? state.opacity : DEFAULT_OPACITY;
		const currentBlur = state.blur !== undefined ? state.blur : DEFAULT_BLUR;
		const currentBrightness = state.brightness !== undefined ? state.brightness : DEFAULT_BRIGHTNESS;
		// 修正负z-index
		const currentZIndex = Math.max(0, state.zIndex !== undefined ? state.zIndex : DEFAULT_Z_INDEX);
		const autoSwitch = state.autoSwitch || false;
		const h = toNonNegInt(state.intervalHours, 0);
		const m = toNonNegInt(state.intervalMinutes, 0);
		const s = toNonNegInt(state.intervalSeconds, 10);

		panel.innerHTML = `
		<div class="pk-head">
		<span class="pk-title">🖌️ 墨韵万象壁<span class="seal">钤</span></span>
		<div style="display:flex;gap:6px;align-items:center;">
		<button class="btn btn-sm help-entry" id="ug-panel-help" title="展开凌霄秘录">📜 凌霄秘录</button>
		<button class="btn btn-secondary btn-sm" id="ug-panel-close" title="收壁">✕</button>
		</div>
		</div>

		<div class="row">
		<button class="btn btn-primary btn-sm" id="ug-upload-img">🖼️ 入画</button>
		<button class="btn btn-primary btn-sm" id="ug-upload-video">🎞️ 存影</button>
		<button class="btn btn-danger btn-sm" id="ug-clear-all">🗑️ 清卷</button>
		</div>
		<div class="hint">入画 / 存影 ≤ 100MB · 容 JPG/PNG/GIF/MP4/WebM · 换景墨晕渐显</div>

		<div style="margin-top:9px;display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
		<input type="text" id="ug-remote-input" placeholder="图画直链 URL" class="url-input">
		<button class="btn btn-success btn-sm" id="ug-remote-add">🌐 引景</button>
		</div>
		<div class="hint">亦可直引外境图链,无须入藏灵台</div>

		<div class="pk-sep">
		<div class="slider-group">
		<label>晕染</label>
		<input type="range" id="ug-slider-blur" min="0" max="30" value="${currentBlur}" step="1">
		<span class="val-display" id="ug-val-blur">${currentBlur}px</span>
		</div>
		<div class="slider-group">
		<label>明暗</label>
		<input type="range" id="ug-slider-brightness" min="10" max="200" value="${currentBrightness}" step="5">
		<span class="val-display" id="ug-val-brightness">${currentBrightness}%</span>
		</div>
		<div class="slider-group">
		<label>浓淡</label>
		<input type="range" id="ug-slider-opacity" min="0" max="100" value="${Math.round(currentOpacity * 100)}" step="5">
		<span class="val-display" id="ug-val-opacity">${Math.round(currentOpacity * 100)}%</span>
		</div>
		<div class="slider-group">
		<label>层级</label>
		<input type="range" id="ug-slider-zindex" min="0" max="10" value="${currentZIndex}" step="1">
		<span class="val-display" id="ug-val-zindex">${currentZIndex}</span>
		</div>
		</div>

		<div class="pk-sep">
		<div class="pk-sub" style="margin-bottom:6px;">⏳ 景随时换</div>
		<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
		<input type="number" id="ug-auto-hours" min="0" max="23" step="1" inputmode="numeric" value="${h}" class="auto-input">时
		<input type="number" id="ug-auto-minutes" min="0" max="59" step="1" inputmode="numeric" value="${m}" class="auto-input">分
		<input type="number" id="ug-auto-seconds" min="0" max="3600" step="1" inputmode="numeric" value="${s}" class="auto-input">秒
		</div>
		<div style="display:flex;gap:6px;margin-top:6px;">
		<button class="btn btn-primary btn-sm" id="ug-auto-start">▶ 启</button>
		<button class="btn btn-danger btn-sm" id="ug-auto-stop">⏹ 止</button>
		</div>
		<div id="ug-auto-status" class="auto-status">${autoSwitch ? '✅ 轮转中' : '⏹️ 已止'}</div>
		</div>

		<div class="pk-sep">
		<div class="pk-sub">灵台景致 (${all.length})</div>
		<div class="media-list">${listHtml}</div>
		</div>

		<div class="pk-foot">点小图换景 · 右上「×」删景 · 换景墨晕渐显</div>
		`;

		requestAnimationFrame(() => {
			panel.classList.remove('collapsed');
			updatePanelPosition();
		});

		// 懒加载图片和视频缩略图,分批延迟加载避免卡顿
		const mediaItems = panel.querySelectorAll('.media-item[data-type]');
		mediaItems.forEach((item, index) => {
			const id = Number(item.dataset.id);
			const type = item.dataset.type;
			setTimeout(async () => {
				try {
					// 检查元素是否还存在
					if (!item.isConnected) return;
					const media = await dbGetById(id);
					if (!media || !item.querySelector('.img-placeholder')) return;

					if (type === 'image') {
						const img = document.createElement('img');
						img.src = typeof media.data === 'string' ? media.data : createThumbURL(new Blob([media.data], { type: media.mime }));
						img.style.width = '100%';
						img.style.height = '100%';
						img.style.objectFit = 'cover';
						img.onload = () => {
							const placeholder = item.querySelector('.img-placeholder');
							if (placeholder) placeholder.replaceWith(img);
						};
						img.onerror = () => {};
					} else if (type === 'video') {
						// 视频生成首帧缩略图
						const thumbUrl = await generateVideoThumbnail(media);
						if (thumbUrl && item.querySelector('.img-placeholder')) {
							const img = document.createElement('img');
							img.src = thumbUrl;
							img.style.width = '100%';
							img.style.height = '100%';
							img.style.objectFit = 'cover';
							const placeholder = item.querySelector('.img-placeholder');
							if (placeholder) {
								// 保留🎞️角标
								const badge = placeholder.querySelector('span:last-child');
								placeholder.innerHTML = '';
								placeholder.appendChild(img);
								if (badge) placeholder.appendChild(badge);
								placeholder.style.display = 'block';
								placeholder.style.background = 'transparent';
							}
						}
					}
				} catch (e) {}
			}, index * 50); // 每个缩略图延迟50ms加载,避免阻塞
		});

		panel.querySelector('#ug-panel-close').addEventListener('click', togglePanel);
		panel.querySelector('#ug-panel-help').addEventListener('click', showHelp);

		// 上传图片(MIME+后缀双重校验)
		panel.querySelector('#ug-upload-img').addEventListener('click', () => {
			const inp = document.createElement('input');
			inp.type = 'file';
			inp.accept = 'image/*,.jpg,.jpeg,.png,.gif,.webp,.bmp,.svg,.avif';
			inp.onchange = async e => {
				const f = e.target.files[0];
				if (!f) return;
				// MIME+后缀双重判断格式
				const isImage = f.type.startsWith('image/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg|avif)$/i.test(f.name);
				if (!isImage) {
					showToast('❌ 请择图画之文件');
					return;
				}
				if (f.size > MAX_SIZE) {
					showToast(`❌ 所择文件 ${formatSize(f.size)},已逾 100MB 之限`);
					return;
				}
				showToast('⏳ 正在收画入壁…');
				try {
					const dataUrl = await fileToDataURL(f);
					const id = await dbSave(dataUrl, 'image', f.type || 'image/jpeg');
					const state = loadState();
					state.selectedId = id;
					saveState(state);
					const media = await dbGetById(id);
					renderBg(media);
					await showPanel(state);
					showToast('✅ 画已入壁,已现于前');
				} catch (err) {
					showToast('❌ 收画未成:' + (err.message || '未知之误'));
				}
			};
			inp.click();
		});

		// 上传视频(MIME+后缀双重校验)
		panel.querySelector('#ug-upload-video').addEventListener('click', () => {
			const inp = document.createElement('input');
			inp.type = 'file';
			inp.accept = 'video/*,.mp4,.webm,.ogg,.mov,.avi';
			inp.onchange = async e => {
				const f = e.target.files[0];
				if (!f) return;
				const isVideo = f.type.startsWith('video/') || /\.(mp4|webm|ogg|mov|avi)$/i.test(f.name);
				if (!isVideo) {
					showToast('❌ 请择影像之文件');
					return;
				}
				if (f.size > MAX_SIZE) {
					showToast(`❌ 所择文件 ${formatSize(f.size)},已逾 100MB 之限`);
					return;
				}
				showToast('⏳ 正在存影入壁…');
				try {
					const buf = await blobToArrayBuffer(f);
					const id = await dbSave(buf, 'video', f.type || 'video/mp4');
					const state = loadState();
					state.selectedId = id;
					saveState(state);
					const media = await dbGetById(id);
					renderBg(media);
					await showPanel(state);
					showToast('✅ 影已入壁,已现于前');
				} catch (err) {
					showToast('❌ 存影未成:' + (err.message || '未知之误'));
				}
			};
			inp.click();
		});

		// 添加URL
		panel.querySelector('#ug-remote-add').addEventListener('click', async () => {
			const input = panel.querySelector('#ug-remote-input');
			const rawUrl = (input.value || '').trim();
			if (!rawUrl) { showToast('⚠️ 请填入外境图链'); return; }
			if (!/^https?:\/\//i.test(rawUrl)) { showToast('⚠️ 图链须以 http(s):// 起首'); return; }

			try {
				const id = await dbSave(rawUrl, 'remote', 'image/*');
				const state = loadState();
				state.selectedId = id;
				saveState(state);
				const media = await dbGetById(id);
				renderBg(media);
				input.value = '';
				await showPanel(state);
				showToast('✅ 外境图链已引');
			} catch (err) {
				showToast('❌ 引景未成:' + err.message);
			}
		});

		// 清空
		panel.querySelector('#ug-clear-all').addEventListener('click', async () => {
			if (confirm('确定清尽灵台中所有景致吗?')) {
				revokeAllObjectURLs();
				await dbClear();
				const state = loadState();
				state.selectedId = null;
				saveState(state);
				renderBg(null);
				await showPanel(state);
				showToast('灵台已清');
				if (state.autoSwitch) stopAutoSwitch();
			}
		});

		// 点击缩略图
		panel.querySelectorAll('.media-item').forEach(el => {
			el.addEventListener('click', async e => {
				if (e.target.closest('.del')) return;
				const id = Number(el.dataset.id);
				// 只加载选中的单个媒体
				const media = await dbGetById(id);
				if (media) {
					const state = loadState();
					state.selectedId = id;
					saveState(state);
					renderBg(media);
					await showPanel(state);
				}
			});
		});

		// 删除
		panel.querySelectorAll('.del').forEach(el => {
			el.addEventListener('click', async e => {
				e.stopPropagation();
				const id = Number(el.dataset.id);
				await dbDelete(id);
				const state = loadState();
				if (state.selectedId === id) {
					state.selectedId = null;
					saveState(state);
					renderBg(null);
				}
				await showPanel(state);
				showToast('已删此景');
			});
		});

		// 滑块操作防抖保存
		const debouncedSave = debounce((state) => saveState(state), 150);

		// 透明度滑块
		const opacitySlider = panel.querySelector('#ug-slider-opacity');
		const opacityDisplay = panel.querySelector('#ug-val-opacity');
		opacitySlider.addEventListener('input', () => {
			const val = parseInt(opacitySlider.value) / 100;
			opacityDisplay.textContent = Math.round(val * 100) + '%';
			const layer = document.getElementById('ug-bg-layer');
			if (layer) {
				layer.style.setProperty('opacity', String(val), 'important');
			}
			const state = loadState();
			state.opacity = val;
			debouncedSave(state);
		});

		// 模糊滑块
		const blurSlider = panel.querySelector('#ug-slider-blur');
		const blurDisplay = panel.querySelector('#ug-val-blur');
		blurSlider.addEventListener('input', () => {
			const val = parseInt(blurSlider.value);
			blurDisplay.textContent = val + 'px';
			const state = loadState();
			state.blur = val;
			debouncedSave(state);
			applyFilter(val, state.brightness);
		});

		// 亮度滑块
		const brightSlider = panel.querySelector('#ug-slider-brightness');
		const brightDisplay = panel.querySelector('#ug-val-brightness');
		brightSlider.addEventListener('input', () => {
			const val = parseInt(brightSlider.value);
			brightDisplay.textContent = val + '%';
			const state = loadState();
			state.brightness = val;
			debouncedSave(state);
			applyFilter(state.blur, val);
		});

		// 层级滑块
		const zIndexSlider = panel.querySelector('#ug-slider-zindex');
		const zIndexDisplay = panel.querySelector('#ug-val-zindex');
		zIndexSlider.addEventListener('input', () => {
			const val = Math.max(0, parseInt(zIndexSlider.value));
			zIndexDisplay.textContent = val;
			const state = loadState();
			state.zIndex = val;
			debouncedSave(state);
			applyZIndex(val);
		});

		// 自动切换
		const autoStartBtn = panel.querySelector('#ug-auto-start');
		const autoStopBtn = panel.querySelector('#ug-auto-stop');
		const hoursInput = panel.querySelector('#ug-auto-hours');
		const minutesInput = panel.querySelector('#ug-auto-minutes');
		const secondsInput = panel.querySelector('#ug-auto-seconds');

		autoStartBtn.addEventListener('click', () => {
			const raws = [hoursInput, minutesInput, secondsInput].map(i => parseInt(i.value, 10));
			const hadNegative = raws.some(n => n < 0);
			// 负数一律归零,非法值回退默认
			state.intervalHours = toNonNegInt(hoursInput.value, 0);
			state.intervalMinutes = toNonNegInt(minutesInput.value, 0);
			state.intervalSeconds = toNonNegInt(secondsInput.value, 10);
			// 限制合理范围
			state.intervalHours = Math.min(23, state.intervalHours);
			state.intervalMinutes = Math.min(59, state.intervalMinutes);
			state.intervalSeconds = Math.min(3600, state.intervalSeconds);
			// 把归一化后的值回写输入框
			hoursInput.value = state.intervalHours;
			minutesInput.value = state.intervalMinutes;
			secondsInput.value = state.intervalSeconds;
			if (hadNegative) showToast('⚠️ 时辰之数不可为负,已自归其零');
			saveState(state);
			startAutoSwitch();
		});

		autoStopBtn.addEventListener('click', stopAutoSwitch);

		// 实时监听时间输入,输入时立即校验
		function sanitizeTimeInput(input, fallback, max) {
			let val = parseInt(input.value, 10);
			if (isNaN(val)) {
				val = fallback;
				input.value = val;
				return val;
			}
			if (val < 0) {
				val = 0;
				input.value = val;
				showToast('⚠️ 时辰之数不可为负,已自归其零');
			} else if (max !== undefined && val > max) {
				val = max;
				input.value = val;
			}
			return val;
		}

		const handleTimeInput = () => {
			sanitizeTimeInput(hoursInput, 0, 23);
			sanitizeTimeInput(minutesInput, 0, 59);
			sanitizeTimeInput(secondsInput, 10, 3600);
			const state = loadState();
			state.intervalHours = toNonNegInt(hoursInput.value, 0);
			state.intervalMinutes = toNonNegInt(minutesInput.value, 0);
			state.intervalSeconds = toNonNegInt(secondsInput.value, 10);
			debouncedSave(state);
		};

		hoursInput.addEventListener('input', handleTimeInput);
		minutesInput.addEventListener('input', handleTimeInput);
		secondsInput.addEventListener('input', handleTimeInput);
		hoursInput.addEventListener('blur', handleTimeInput);
		minutesInput.addEventListener('blur', handleTimeInput);
		secondsInput.addEventListener('blur', handleTimeInput);

		if (state.autoSwitch) {
			const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000;
			updateAutoStatus(true, totalMs);
		}
	}

	// ===== DOM守护(MutationObserver代替轮询,更高效) =====
	let observer = null;
	function startDomGuard() {
		if (observer) observer.disconnect();

		const check = () => {
			if (!document.body) return;
			if (!document.getElementById('ug-bg-toggle-btn')) {
				createToggleButton();
			}
			if (!document.getElementById('ug-bg-layer')) {
				const state = loadState();
				if (state.selectedId) {
					dbGetById(state.selectedId).then(media => {
						if (media && !document.getElementById('ug-bg-layer')) {
							renderBg(media);
						}
					}).catch(() => {});
				}
			}
		};

		check();

		observer = new MutationObserver(debounce(check, 200));
		observer.observe(document.body, { childList: true, subtree: false });
	}

	// ===== 窗口大小改变 =====
	let resizeRaf = null;
	window.addEventListener('resize', () => {
		if (resizeRaf) return;
		resizeRaf = requestAnimationFrame(() => {
			resizeRaf = null;
			updatePanelPosition();
			const btn = document.getElementById('ug-bg-toggle-btn');
			if (btn && btn.style.left) {
				const w = btn.offsetWidth || 48;
				const h = btn.offsetHeight || 48;
				const left = Math.min(parseInt(btn.style.left, 10) || 0, window.innerWidth - w);
				const top = Math.min(parseInt(btn.style.top, 10) || 0, window.innerHeight - h);
				btn.style.left = Math.max(0, left) + 'px';
				btn.style.top = Math.max(0, top) + 'px';
				// 修正后保存位置
				localStorage.setItem(BTN_POS_KEY, JSON.stringify({ left: Math.max(0, left), top: Math.max(0, top) }));
			}
		});
	});

	// ----- 初始化 -----
	async function init() {
		try {
			if (!document.body) {
				setTimeout(init, 100);
				return;
			}
			createToggleButton();

			const state = loadState();
			if (state.selectedId) {
				try {
					const media = await dbGetById(state.selectedId);
					if (media) {
						renderBg(media);
					} else {
						state.selectedId = null;
						saveState(state);
					}
				} catch (e) {
					state.selectedId = null;
					saveState(state);
				}
			}

			startDomGuard();

			if (state.autoSwitch) {
				const totalMs = ((state.intervalHours || 0) * 3600 + (state.intervalMinutes || 0) * 60 + (state.intervalSeconds || 0)) * 1000;
				if (totalMs >= 1000) {
					startAutoSwitch();
				} else {
					state.autoSwitch = false;
					saveState(state);
				}
			}

			// 点击页面播放视频(解决自动播放限制)
			document.addEventListener('click', () => {
				const video = document.querySelector('#ug-bg-layer .ug-bg-media.active');
				if (video && video.paused && video.tagName === 'VIDEO') {
					video.play().catch(() => {});
				}
			}, { once: false });

			// Esc键关闭面板
			document.addEventListener('keydown', (e) => {
				if (e.key === 'Escape') {
					const p = document.getElementById('ug-bg-panel');
					if (p && !p.classList.contains('collapsed')) {
						togglePanel();
					}
				}
			});

			console.log('[初始化] 🖌️ 墨韵壁 · 水墨武侠风 v1.5.0 已启');
		} catch (e) {
			console.error('[初始化] 启动失败:', e);
		}
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}

})();

luogu私信接收显示以及回复

我是折叠框
JavaScript
// ==UserScript==
// @name         洛谷私信提醒
// @namespace    local.luogu.pm-notify
// @version      2.2.1
// @description  收到新私信时,在洛谷页面右下角弹出提示气泡,并在标签页不可见时弹出桌面系统通知(整合自 Amazing-Luogu 私信通知功能)
// @match        *://www.luogu.com.cn/*
// @match        *://www.luogu.com/*
// @match        *://fecdn.luogu.com.cn/*
// @match        *://fecdn.luogu.com/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        unsafeWindow
// @require      https://cdn.amlg.top/npm/izitoast@1.4.0/dist/js/iziToast.min.js?version=1.0.1
// @resource     iziToastCSS https://cdn.amlg.top/npm/izitoast@1.4.0/dist/css/iziToast.min.css?version=1.0.1
// @run-at       document-start
// ==/UserScript==

(function () {
	"use strict";

	// 加载 iziToast 样式
	try {
		const css = GM_getResourceText("iziToastCSS");
		if (css) GM_addStyle(css);
	} catch (e) {
		console.debug("[私信提醒] 加载 iziToast 样式失败", e);
	}

	// ============================================================
	// 工具函数:获取当前登录用户 uid
	// ============================================================
	function getCurrentUserId() {
		try {
			const ctx = document.getElementById("lentille-context");
			if (ctx) return JSON.parse(ctx.innerHTML).user.uid.toString();
			if (
				window._feInjection &&
				window._feInjection.currentUser &&
				window._feInjection.currentUser.uid
			) {
				return window._feInjection.currentUser.uid.toString();
			}
			return null;
		} catch (e) {
			console.debug(e);
			return null;
		}
	}

	const IS_IFRAME =
		window !== window.top &&
		/^fecdn\.luogu\.com(\.cn)?$/.test(location.hostname);

	// ============================================================
	// iframe 分支(fecdn.luogu.com.cn):建立 WS 桥接并接力私信
	// ============================================================
	if (IS_IFRAME) {
		if (!GM_getValue("amlChatNotificationEnabled", true)) {
			console.debug("[私信提醒] 已关闭,iframe 不启动");
			return;
		}
		console.debug("[私信提醒] iframe 分支已启动");

		const amlParentOrigin = (() => {
			try {
				if (document.referrer) return new URL(document.referrer).origin;
			} catch (e) {}
			return "https://www.luogu.com.cn";
		})();
		const amlWorkerURLFallback =
			"https://fecdn.luogu.com.cn/columba/static.284b6b4b2a29779e.hub.worker.js";
		const amlRid = () => Math.random().toString(16).slice(2, 11);
		const amlNewId = () => [amlRid(), amlRid(), amlRid(), amlRid()].join("-");

		// 向主页面请求当前 uid
		const amlWaitUid = () =>
			new Promise((resolve) => {
				let timerId = null;
				const finish = (v) => {
					if (timerId !== null) clearInterval(timerId);
					window.removeEventListener("message", onMsg);
					resolve(v);
				};
				const onMsg = (e) => {
					try {
						if (e.origin !== amlParentOrigin) return;
						if (
							!e.data ||
							typeof e.data !== "object" ||
							typeof e.data.__amlChatUid !== "string" ||
							!e.data.__amlChatUid
						) {
							return;
						}
						finish(e.data.__amlChatUid);
					} catch (err) {}
				};
				const ask = () => {
					try {
						window.parent.postMessage({ __amlChatUidRequest: true }, amlParentOrigin);
					} catch (e) {}
				};
				window.addEventListener("message", onMsg);
				ask();
				let tries = 0;
				timerId = setInterval(() => {
					if (++tries > 45) {
						finish(null);
						return;
					}
					ask();
				}, 2000);
			});

		// 捕获官方 worker 地址
		let amlObservedWorkerURL = null;
		window.addEventListener("message", (e) => {
			try {
				const d = e.data;
				if (
					d &&
					typeof d === "object" &&
					d.type === "luogu-ws-bridge-port" &&
					typeof d.worker === "string" &&
					d.worker
				) {
					amlObservedWorkerURL = d.worker;
					GM_setValue("amlWSWorkerURL", d.worker);
					console.debug("[私信提醒] 捕获官方 worker 地址:", d.worker);
				}
			} catch (err) {}
		});
		const amlWaitWorkerURL = () =>
			new Promise((resolve) => {
				if (amlObservedWorkerURL) {
					resolve(amlObservedWorkerURL);
					return;
				}
				let tries = 0;
				const timer = setInterval(() => {
					if (amlObservedWorkerURL || ++tries > 40) {
						clearInterval(timer);
						resolve(amlObservedWorkerURL);
					}
				}, 500);
			});
		const amlResolveWorkerURL = async () => {
			const cached = GM_getValue("amlWSWorkerURL", "");
			if (cached) {
				console.debug("[私信提醒] worker URL 来自缓存:", cached);
				return cached;
			}
			const observed = await amlWaitWorkerURL();
			const url = observed || amlWorkerURLFallback;
			console.debug(
				"[私信提醒] worker URL 来自" + (observed ? "官方消息" : "内置兜底") + ":",
				url,
			);
			GM_setValue("amlWSWorkerURL", url);
			return url;
		};

		// 建立 SharedWorker 桥接,连接洛谷聊天 WS
		const amlBridgeSession = (workerURL, uid) => {
			let worker = null;
			try {
				worker = new SharedWorker(workerURL, {
					type: "module",
					name: "luogu-ws-shared-worker",
				});
			} catch (e) {
				console.warn("[私信提醒] SharedWorker 构建失败:", e);
				return null;
			}
			let activityHandler = null;
			const cb = new MessageChannel();
			const send = (path, argumentList, transfer) => {
				try {
					worker.port.postMessage(
						{ id: amlNewId(), type: "APPLY", path, argumentList },
						transfer || [],
					);
				} catch (e) {}
			};
			cb.port1.addEventListener("message", (e) => {
				const d = e.data;
				if (activityHandler) activityHandler();
				try {
					if (!d || typeof d !== "object") return;
					if (d.type === "APPLY" && d.id) cb.port1.postMessage({ type: "RAW", id: d.id });
					if (d.type !== "APPLY" || !Array.isArray(d.path)) return;
					if (
						d.path[0] === "onEvent" &&
						Array.isArray(d.argumentList) &&
						d.argumentList.length >= 3
					) {
						const channel = d.argumentList[0] && d.argumentList[0].value;
						const eventName = d.argumentList[1] && d.argumentList[1].value;
						const payload = d.argumentList[2] && d.argumentList[2].value;
						if (
							eventName === "message" &&
							typeof channel === "string" &&
							channel.indexOf("Chat:") === 0 &&
							typeof payload === "string"
						) {
							window.parent.postMessage({ __amlChatPayload: payload }, amlParentOrigin);
							console.debug("[私信提醒] 私信 payload 已接力给主页面");
						}
					}
				} catch (err) {}
			});
			cb.port1.start();
			worker.port.start();
			send(
				["connect"],
				[
					{ type: "RAW", value: "wss://ws2.luogu.com.cn/ws" },
					{ type: "RAW", value: false },
					{ type: "HANDLER", name: "proxy", value: cb.port2 },
				],
				[cb.port2],
			);
			send(["subscribe"], [{ type: "RAW", value: "Chat:" + uid }, { type: "RAW", value: "" }]);
			return {
				setActivityHandler(fn) {
					activityHandler = fn;
				},
				close() {
					try {
						worker.port.close();
					} catch (e) {}
					try {
						cb.port1.close();
					} catch (e) {}
				},
			};
		};

		// 启动桥接 + 断线看门狗
		let amlFailCount = 0;
		const amlStartBridge = (uid) => {
			const url = GM_getValue("amlWSWorkerURL", "") || amlWorkerURLFallback;
			const session = amlBridgeSession(url, uid);
			if (!session) {
				GM_setValue("amlWSWorkerURL", "");
				setTimeout(() => amlStartBridge(uid), 30000);
				return;
			}
			let lastActivity = Date.now();
			let stopped = false;
			session.setActivityHandler(() => {
				lastActivity = Date.now();
				amlFailCount = 0;
			});
			const retry = (delay) => {
				if (stopped) return;
				stopped = true;
				clearInterval(watchdog);
				session.close();
				amlFailCount++;
				console.warn(
					"[私信提醒] 连接异常," + delay / 1000 + " 秒后重连(连续失败 " + amlFailCount + " 次)",
				);
				if (amlFailCount >= 2) GM_setValue("amlWSWorkerURL", "");
				setTimeout(async () => {
					const url = await amlResolveWorkerURL();
					GM_setValue("amlWSWorkerURL", url);
					amlStartBridge(uid);
				}, delay);
			};
			const watchdog = setInterval(() => {
				if (Date.now() - lastActivity > 120000) retry(10000);
			}, 30000);
		};

		(async () => {
			const uid = await amlWaitUid();
			console.debug("[私信提醒] uid 获取结果:", uid);
			if (!uid) return;
			const url = await amlResolveWorkerURL();
			GM_setValue("amlWSWorkerURL", url);
			amlStartBridge(uid);
			console.debug("[私信提醒] 桥接直连已启动(iframe)");
		})();
		return;
	}

	// ============================================================
	// 主页面分支(www.luogu.com.cn):接收私信并通知
	// ============================================================
	unsafeWindow.GM_getValue = GM_getValue;
	unsafeWindow.GM_setValue = GM_setValue;

	if (GM_getValue("amlChatNotificationEnabled", true)) {
		const amlSeenChatMsgIds = new Set();

		const handleAMLChatPayload = function (raw) {
			try {
				const payload = JSON.parse(raw);
				const latestMessage = payload.message;
				if (!latestMessage || !latestMessage.target) {
					console.debug("[私信提醒] payload 结构不符,跳过");
					return;
				}
				if (latestMessage.myself && latestMessage.myself !== "RX") {
					console.debug("[私信提醒] 自己发的消息,跳过");
					return;
				}
				const chatSender = latestMessage.target;
				if (latestMessage.id !== undefined) {
					if (amlSeenChatMsgIds.has(latestMessage.id)) {
						console.debug("[私信提醒] 重复消息 id=" + latestMessage.id + ",跳过");
						return;
					}
					amlSeenChatMsgIds.add(latestMessage.id);
					if (amlSeenChatMsgIds.size > 500) amlSeenChatMsgIds.clear();
				}
				let snippet =
					latestMessage.content.length > 15
						? latestMessage.content.substring(0, 15) + "..."
						: latestMessage.content;
				// ① 右下角 iziToast 气泡 + “回复私信”按钮
				iziToast.show({
					title: `${chatSender.name}`,
					message: `${snippet}`,
					position: "bottomRight",
					theme: "light",
					image: `https://cdn.luogu.com.cn/upload/usericon/${chatSender.uid}.png`,
					imageWidth: 54,
					balloon: true,
					messageEscape: false,
					progressBar: true,
					pauseOnHover: true,
					timeout: 10000,
					buttons: [
						[
							'<button style="margin: 0 2px; margin-top: 3px !important;">回复私信</button>',
							function () {
								window.open(`https://www.luogu.com.cn/chat?uid=${chatSender.uid}`);
							},
							true,
						],
					],
					onClick: function () {
						window.open(`https://www.luogu.com.cn/chat?uid=${chatSender.uid}`);
					},
				});
				// ② 仅在标签页不可见时弹桌面系统通知
				if (
					"Notification" in window &&
					Notification.permission === "granted" &&
					(document.hidden || !document.hasFocus())
				) {
					const body =
						latestMessage.content.length > 100
							? latestMessage.content.substring(0, 100) + "..."
							: latestMessage.content;
					const desktopNotification = new Notification(`${chatSender.name} 的私信`, {
						body: body,
						icon: `https://cdn.luogu.com.cn/upload/usericon/${chatSender.uid}.png`,
						tag: `aml-chat-${chatSender.uid}`,
						requireInteraction: false,
					});
					desktopNotification.onclick = () => {
						window.open(`https://www.luogu.com.cn/chat?uid=${chatSender.uid}`);
						desktopNotification.close();
					};
					setTimeout(() => desktopNotification.close(), 10000);
				}
			} catch (e) {
				console.debug(e);
			}
		};

		// 处理 iframe 传来的私信 payload
		window.addEventListener("message", function (e) {
			try {
				if (!e.data || typeof e.data !== "object") return;
				if (e.data.__amlChatUidRequest === true) {
					if (
						!/^https:\/\/fecdn\.luogu\.com(\.cn)?$/.test(e.origin) ||
						!e.source
					) {
						return;
					}
					const uid = getCurrentUserId();
					e.source.postMessage({ __amlChatUid: uid ? String(uid) : "" }, e.origin);
					console.debug("[私信提醒] 收到 uid 请求,回复:", uid);
					return;
				}
				if (typeof e.data.__amlChatPayload !== "string") return;
				console.debug("[私信提醒] 主页面收到私信 payload");
				handleAMLChatPayload(e.data.__amlChatPayload);
			} catch (err) {
				console.debug(err);
			}
		});

		// 兜底:拦截主页面自身的 WS 桥接 MessagePort(部分页面聊天消息由此路由)
		const handleAMLBridgeEnvelope = function (data) {
			try {
				if (
					!data ||
					typeof data !== "object" ||
					data.type !== "APPLY" ||
					!Array.isArray(data.argumentList) ||
					data.argumentList.length < 3
				) {
					return;
				}
				const eventName = data.argumentList[1] && data.argumentList[1].value;
				const payloadRaw = data.argumentList[2] && data.argumentList[2].value;
				if (eventName !== "message" || typeof payloadRaw !== "string") return;
				handleAMLChatPayload(payloadRaw);
			} catch (e) {
				console.debug(e);
			}
		};
		const AMLMessagePortProto = unsafeWindow.MessagePort.prototype;
		const amlOriginalPortAddEventListener = AMLMessagePortProto.addEventListener;
		AMLMessagePortProto.addEventListener = function (type, fn, ...rest) {
			if (type === "message" && fn && !fn.__amlWSW) {
				const wrapped = function (e) {
					handleAMLBridgeEnvelope(e.data);
					return fn.call(this, e);
				};
				wrapped.__amlWSW = true;
				return amlOriginalPortAddEventListener.call(this, type, wrapped, ...rest);
			}
			return amlOriginalPortAddEventListener.call(this, type, fn, ...rest);
		};
		const amlPortOnMessageDesc = Object.getOwnPropertyDescriptor(
			AMLMessagePortProto,
			"onmessage",
		);
		if (amlPortOnMessageDesc && amlPortOnMessageDesc.set) {
			Object.defineProperty(AMLMessagePortProto, "onmessage", {
				get: amlPortOnMessageDesc.get,
				set(fn) {
					if (fn && !fn.__amlWSW) {
						const wrapped = function (e) {
							handleAMLBridgeEnvelope(e.data);
							return fn.call(this, e);
						};
						wrapped.__amlWSW = true;
						return amlPortOnMessageDesc.set.call(this, wrapped);
					}
					return amlPortOnMessageDesc.set.call(this, fn);
				},
			});
		}
	}
})();

主要作用就是监听你的私信,有人给你发,就直接弹窗提示你,可以直接点弹窗到私信进行回复。

板娘(利用他人Github数据库完成

我是折叠框
JavaScript
// ==UserScript==
// @name         洛谷左下角 Live2D 看板娘
// @namespace    local.luogu.live2d
// @version      1.0.0
// @description  在洛谷页面左下角显示 Live2D 看板娘(整合自 Amazing-Luogu 的 Live2D 看板娘功能)
// @author       Crepuscule_oublie
// @match        *://www.luogu.com.cn/*
// @match        *://www.luogu.com/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @connect      *
// @run-at       document-start
// ==/UserScript==

(function () {
	"use strict";

	// ============================================================
	// 开关:默认关闭。开启方式:
	//   GM_setValue("amlLive2DEnabled", true)  (或改下面默认值为 true)
	// ============================================================
	let live2DInited = false;

	function startLive2D() {
		if (!GM_getValue("amlLive2DEnabled", true) || live2DInited) return;
		live2DInited = true;

		(function () {
			// live2d-widgets 库及资源 CDN 根地址
			const CDN = 'https://fastly.jsdelivr.net/npm/live2d-widgets@1.0.1/dist/';
			const L2D_CONFIG = {
				waifuPath: CDN + 'waifu-tips.json',
				cubism2Path: CDN + 'live2d.min.js',
				cubism5Path: 'https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js',
				tools: ['switch-model', 'switch-texture', 'photo', 'info'],
				logLevel: 'warn',
				drag: false
			};
			const CUSTOM_MODELS = null;
			// 资源下载镜像:把 jsdelivr / raw.githubusercontent 的 live2d_api 换到可访问镜像
			const GH_MIRROR = 'https://cdn.amlg.top/amlg/live2dapi/';
			// 模型缓存有效期:7 天
			const L2D_CACHE_TTL = 7 * 24 * 60 * 60 * 1000;
			const L2D_CACHE_DB = 'aml_l2d_cache';
			const L2D_CACHE_STORE = 'files';
			const l2dInflight = Object.create(null);

			// ---------- IndexedDB 缓存(避免重复下载模型/脚本) ----------
			function openCacheDB() {
				return new Promise(function (resolve, reject) {
					var req = indexedDB.open(L2D_CACHE_DB, 1);
					req.onupgradeneeded = function () {
						var db = req.result;
						if (!db.objectStoreNames.contains(L2D_CACHE_STORE)) {
							db.createObjectStore(L2D_CACHE_STORE, { keyPath: 'url' });
						}
					};
					req.onsuccess = function () { resolve(req.result); };
					req.onerror = function () { reject(req.error); };
				});
			}
			function readCache(url) {
				return openCacheDB().then(function (db) {
					return new Promise(function (resolve, reject) {
						var tx = db.transaction(L2D_CACHE_STORE, 'readonly');
						var req = tx.objectStore(L2D_CACHE_STORE).get(url);
						req.onsuccess = function () {
							var entry = req.result;
							if (!entry) return resolve(null);
							if (Date.now() - entry.ts > L2D_CACHE_TTL) return resolve(null);
							resolve(entry.data);
						};
						req.onerror = function () { reject(req.error); };
					});
				}).catch(function () { return null; });
			}
			function writeCache(url, data) {
				if (data && data.buffer && data.byteOffset !== undefined) {
					data = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
				}
				openCacheDB().then(function (db) {
					return new Promise(function (resolve, reject) {
						var tx = db.transaction(L2D_CACHE_STORE, 'readwrite');
						tx.objectStore(L2D_CACHE_STORE).put({ url: url, ts: Date.now(), data: data });
						tx.oncomplete = function () { resolve(); };
						tx.onerror = function () { reject(tx.error); };
					});
				}).catch(function () { });
			}

			// ---------- 统一资源地址:jsdelivr / GitHub 镜像替换 ----------
			function normalizeUrl(url) {
				if (!/^https?:/i.test(url)) return url;
				if (url.indexOf(GH_MIRROR) === 0) return url;
				url = url.replace(/^https:\/\/(?:fastly|cdn)\.jsdelivr\.net\/gh\/fghrsh\/live2d_api\//, GH_MIRROR);
				url = url.replace(/^https:\/\/raw\.githubusercontent\.com\/fghrsh\/live2d_api\/(?:\d+\.\d+\.\d+\/)?/, GH_MIRROR);
				return url;
			}

			// ---------- GM 拉取(带缓存 + 并发去重) ----------
			function gmFetch(url) {
				url = normalizeUrl(url);
				if (l2dInflight[url]) return l2dInflight[url];
				var p = readCache(url).then(function (cached) {
					if (cached) return cached;
					return new Promise(function (resolve, reject) {
						GM_xmlhttpRequest({
							method: 'GET',
							url: url,
							timeout: 20000,
							responseType: 'arraybuffer',
							onload: function (r) {
								if (r.status >= 200 && r.status < 300) {
									writeCache(url, r.response);
									resolve(r.response);
								} else {
									console.error('[L2D] GM 拉取失败 HTTP ' + r.status + ' ' + url);
									reject(new Error('HTTP ' + r.status + ' ' + url));
								}
							},
							onerror: function () {
								console.error('[L2D] GM 网络错误 ' + url);
								reject(new Error('NETWORK ' + url));
							},
							ontimeout: function () {
								console.error('[L2D] GM 超时 ' + url);
								reject(new Error('TIMEOUT ' + url));
							}
						});
					});
				});
				l2dInflight[url] = p;
				p.then(function () { delete l2dInflight[url]; }, function () { delete l2dInflight[url]; });
				return p;
			}
			function gmText(url) {
				return gmFetch(url).then(function (buf) {
					var bytes = new Uint8Array(buf);
					try {
						return new TextDecoder('utf-8').decode(bytes);
					} catch (e) {
						var s = '';
						var CHUNK = 0x8000;
						for (var i = 0; i < bytes.length; i += CHUNK) {
							s += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
						}
						return s;
					}
				});
			}

			// ---------- 把 ES Module 代码转换为普通脚本执行 ----------
			function demodule(code, moduleUrl) {
				var out = code.replace(/import\{([^}]*)\}from"([^"]+)"/g, function (m, names, from) {
					var abs = new URL(from, moduleUrl).href;
					var destructured = names.replace(/(\w+)\s+as\s+(\w+)/g, function (mm, v, k) {
						return v + ':' + k;
					});
					return 'const{' + destructured + '}=window.__l2dExports[' + JSON.stringify(abs) + '];';
				});
				out = out.replace(/export\{([^}]*)\};/g, function (m, body) {
					var named = body.replace(/(\w+)\s+as\s+(\w+)/g, function (mm, v, k) {
						return k + ':' + v;
					});
					return 'window.__l2dExports[' + JSON.stringify(moduleUrl) + ']={' + named + '};';
				});
				out = out.replace(/import\(/g, '__l2dImport(');
				out = out.replace(
					's=document.createElement("script"),s.src=e,s&&(s.onload=()=>t(e),s.onerror=()=>o(e),document.head.appendChild(s))',
					'__l2dLoadScript(e).then(()=>t(e),o)'
				);
				return out;
			}
			window.__l2dExports = window.__l2dExports || {};
			var __l2dBase = CDN + 'waifu-tips.js';
			function __l2dImport(url) {
				var full = /^https?:/i.test(url) ? url : new URL(url, __l2dBase).href;
				return gmText(full).then(function (code) {
					if (/^\s*</.test(code)) {
						throw new Error('非 JS 内容(可能 404 或 CDN 错误页): ' + full);
					}
					__l2dBase = full;
					if (/export\{/.test(code) || /import\{/.test(code)) {
						var conv = demodule(code, full);
						eval(conv);
						return window.__l2dExports[full] || {};
					}
					eval(code);
					return {};
				});
			}
			function __l2dLoadScript(url) {
				return __l2dImport(url).then(function () { return url; });
			}
			window.__l2dImport = __l2dImport;
			window.__l2dLoadScript = __l2dLoadScript;

			// ---------- 把页面 fetch 改为走 GM 代理(解决 CORS) ----------
			var NativeFetch = window.fetch ? window.fetch.bind(window) : null;
			window.fetch = function (input, init) {
				var url = typeof input === 'string' ? input : (input && input.url) || '';
				if (/^https?:/i.test(url)) {
					return gmFetch(url).then(function (buf) {
						return new Response(buf, { status: 200, statusText: 'OK' });
					});
				}
				if (NativeFetch) return NativeFetch(input, init);
				return Promise.reject(new Error('fetch disabled for ' + url));
			};

			// ---------- 把 Image 换成 canvas 模拟(解决图片跨域) ----------
			var NativeImage = window.Image;
			function gmImage() {
				var canvas = document.createElement('canvas');
				var listeners = [];
				var completed = false;
				var currentSrc = '';
				var origAdd = canvas.addEventListener.bind(canvas);
				canvas.addEventListener = function (type, cb, opts) {
					if (type === 'load') { listeners.push(cb); return; }
					return origAdd(type, cb, opts);
				};
				canvas.removeEventListener = function (type, cb, opts) {
					if (type === 'load') {
						listeners = listeners.filter(function (x) { return x !== cb; });
						return;
					}
					return origAdd(type, cb, opts);
				};
				Object.defineProperty(canvas, 'crossOrigin', { value: 'anonymous', writable: true });
				Object.defineProperty(canvas, 'complete', { get: function () { return completed; } });
				Object.defineProperty(canvas, 'naturalWidth', {
					get: function () { return canvas.width; },
					configurable: true
				});
				Object.defineProperty(canvas, 'naturalHeight', {
					get: function () { return canvas.height; },
					configurable: true
				});
				Object.defineProperty(canvas, 'src', {
					get: function () { return currentSrc; },
					set: function (url) {
						currentSrc = url;
						if (!url) return;
						gmFetch(url)
							.then(function (buf) { return createImageBitmap(new Blob([buf])); })
							.then(function (bmp) {
								canvas.width = bmp.width;
								canvas.height = bmp.height;
								var ctx = canvas.getContext('2d');
								if (ctx) ctx.drawImage(bmp, 0, 0);
								completed = true;
								if (typeof canvas.onload === 'function') {
									try { canvas.onload(); } catch (e) { }
								}
								listeners.slice().forEach(function (cb) {
									try { cb(); } catch (e) { }
								});
							})
							.catch(function () {
								if (typeof canvas.onerror === 'function') {
									try { canvas.onerror(); } catch (e) { }
								}
							});
					}
				});
				return canvas;
			}
			window.Image = gmImage;
			window.Image.prototype = NativeImage.prototype;

			// ---------- 注入样式 ----------
			function injectCSS(cssText) {
				if (typeof CSSStyleSheet !== 'undefined' && 'replaceSync' in CSSStyleSheet.prototype) {
					var sheet = new CSSStyleSheet();
					sheet.replaceSync(cssText);
					document.adoptedStyleSheets = Array.prototype.slice.call(document.adoptedStyleSheets || []).concat(sheet);
					return;
				}
				var style = document.createElement('style');
				document.head.appendChild(style);
				var rules = cssText.match(/[^{}]+{[^}]+}/g) || [];
				for (var i = 0; i < rules.length; i++) {
					try { style.sheet.insertRule(rules[i].trim()); } catch (e) { }
				}
			}

			window.addEventListener('unhandledrejection', function (ev) {
				var r = ev.reason;
				console.error('[L2D] 未捕获的 Promise 失败:', r && r.message ? r.message : r);
				ev.preventDefault();
			});

			// ---------- 加载并初始化看板娘 ----------
			__l2dImport(CDN + 'waifu-tips.js')
				.then(function () {
					if (typeof window.initWidget !== 'function') {
						console.error('[L2D] initWidget 未定义');
						return;
					}
					if (CUSTOM_MODELS) {
						L2D_CONFIG.waifuPath = undefined;
						L2D_CONFIG.models = CUSTOM_MODELS;
					}
					window.initWidget(L2D_CONFIG);
				})
				.catch(function (e) {
					console.error('[L2D] 初始化失败', e);
				});
			gmText(CDN + 'waifu.css').then(injectCSS).catch(function (e) {
				console.error('[L2D] CSS 加载失败', e);
			});

			// 看板娘固定到页面左下角,并隐藏切换按钮
			GM_addStyle('#waifu{left:64px !important;}#waifu-toggle{display:none !important;left:80px !important;}');
		})();
	}

	// 等 DOM 就绪后再装载看板娘(waifu 需要向 body 插入 #waifu 容器)
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', startLive2D);
	} else {
		startLive2D();
	}
})();

而今我终于写成了,哈哈哈哈哈哈!!!!

原文