跳到正文

算法·理论

洛谷代码仓库 (Luogu Code Repository)

CD小狼2015约 118 分钟
原文
文章信息与版本

文章信息

发布
2026年11月13日
收录
2026年11月15日
更新
2026年11月21日
篇幅
约 118 分钟

版本

  1. v1当前

起因是作者觉得每次做相同的题想要复制之前的模板要翻来翻去,并且无法随身做笔记,所以做出来了这款创建插件。

主要功能

  1. 收录常用的模板和代码
  2. 随时记录题目笔记
  3. 更高效的写代码
代码(油猴可用)
Java
// ==UserScript==
// @name         洛谷代码仓库 (Luogu Code Repository)
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  见专栏
// @author       You
// @match        https://www.luogu.com.cn/*
// @grant        none
// @require      https://fastly.jsdelivr.net/npm/marked@12.0.1/marked.min.js
// @require      https://fastly.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js
// @require      https://fastly.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js
// @run-at       document-idle
// ==/UserScript==

(function () {
	'use strict';

	const STORAGE_KEY = 'luogu_code_repo';
	const BRANCH_KEY = 'luogu_code_repo_branches';
	const NOTE_KEY = 'luogu_problem_notes';
	const NOTE_BRANCH_KEY = 'luogu_note_branches';
	const PANEL_WIDTH = '50vw';
	const Z_PANEL = 2147483646;
	const Z_BTN = 2147483645;
	const Z_DIALOG = 2147483647;

	const ICON_REPO = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V9z"></path><path d="M3 15a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3v-3z"></path></svg>`;
	const ICON_BRANCH = `<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="6" y1="3" x2="6" y2="15"></line><circle cx="18" cy="6" r="3"></circle><circle cx="6" cy="18" r="3"></circle><path d="M18 9a9 9 0 0 1-9 9"></path></svg>`;
	const ICON_INBOX = `<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"></polyline><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"></path></svg>`;
	const ICON_SEARCH = `<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>`;
	const ICON_NOTE = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>`;
	const ICON_NOTE_LG = `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>`;
	const ICON_PLUS_LG = `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>`;

	/* ==================== 依赖管理与动态加载 ==================== */
	let libsLoaded = false;
	let libsPromise = null;

	function injectCSS() {
		if (!document.getElementById('luogu-katex-css')) {
			const link = document.createElement('link');
			link.id = 'luogu-katex-css';
			link.rel = 'stylesheet';
			link.href = 'https://fastly.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css';
			document.head.appendChild(link);
		}
		if (!document.getElementById('luogu-note-style')) {
			const style = document.createElement('style');
			style.id = 'luogu-note-style';
			style.textContent = `
#note-preview-wrap { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
#note-preview-wrap h1 { margin: 16px 0 10px 0; color: #89b4fa; font-size: 18px; border-bottom: 1px solid #313244; padding-bottom: 4px; }
#note-preview-wrap h2 { margin: 14px 0 8px 0; color: #89b4fa; font-size: 16px; }
#note-preview-wrap h3 { margin: 12px 0 6px 0; color: #89b4fa; font-size: 14px; }
#note-preview-wrap p { margin: 8px 0; line-height: 1.6; }
#note-preview-wrap ul, #note-preview-wrap ol { margin: 8px 0; padding-left: 20px; }
#note-preview-wrap li { margin-bottom: 4px; }
#note-preview-wrap blockquote { border-left: 4px solid #45475a; padding-left: 12px; color: #a6adc8; margin: 8px 0; background: #181825; padding: 8px 12px; border-radius: 4px; }
#note-preview-wrap pre { background: #181825; padding: 10px; border-radius: 6px; overflow-x: auto; border: 1px solid #313244; margin-bottom: 8px; }
#note-preview-wrap code { font-family: monospace; }
#note-preview-wrap :not(pre) > code { background: #313244; padding: 2px 6px; border-radius: 4px; font-size: 13px; color: #a6e3a1; }
#note-preview-wrap a { color: #89b4fa; text-decoration: none; }
#note-preview-wrap a:hover { text-decoration: underline; }
#note-preview-wrap table { border-collapse: collapse; width: 100%; margin: 8px 0; }
#note-preview-wrap th, #note-preview-wrap td { border: 1px solid #45475a; padding: 6px 12px; }
#note-preview-wrap th { background: #262637; }
.katex-display { margin: 1em 0; overflow-x: auto; overflow-y: hidden; }

/* IDE垂直工具栏样式 */
#luogu-ide-vertical-tools {
	position: fixed; right: 20px; top: 15%; z-index: ${Z_BTN};
	width: 140px; background: #11111b; border: 1px solid #313244; border-radius: 8px;
	box-shadow: 0 4px 15px rgba(0,0,0,0.5); display: flex; flex-direction: column;
	transition: width 0.2s; overflow: hidden; font-family: -apple-system, sans-serif;
}
#luogu-ide-vertical-tools.collapsed { width: 110px; }
#luogu-ide-vertical-tools .luogu-tools-header {
	padding: 8px; background: #1e1e2e; cursor: pointer; display: flex; align-items: center; justify-content: center;
	font-size: 12px; font-weight: bold; color: #a6adc8; user-select: none; border-bottom: 1px solid #313244;
}
#luogu-ide-vertical-tools .luogu-tools-header:hover { background: #313244; color: #cdd6f4; }
#luogu-ide-vertical-tools .luogu-tools-header .arrow {
	margin-right: 5px; font-size: 10px; transition: transform 0.2s;
}
#luogu-ide-vertical-tools.collapsed .luogu-tools-header .arrow { transform: rotate(-90deg); }
#luogu-ide-vertical-tools .luogu-tools-body {
	display: flex; flex-direction: column; gap: 8px; padding: 10px;
}
#luogu-ide-vertical-tools.collapsed .luogu-tools-body { display: none; }

.luogu-tool-btn {
	height: 32px; border-radius: 6px; border: 1px solid #313244; background: #181825;
	color: #cdd6f4; font-size: 13px; font-weight: 600; cursor: pointer;
	display: flex; align-items: center; justify-content: center; gap: 6px;
	font-family: inherit; transition: all 0.15s; width: 100%; box-sizing: border-box; white-space: nowrap;
}
.luogu-tool-btn:hover {
	background: #313244; color: #fff; border-color: #45475a;
}
.luogu-tool-btn svg { width: 14px; height: 14px; }
			`;
			document.head.appendChild(style);
		}
	}
	injectCSS();

	function loadDependencies() {
		if (libsLoaded) return Promise.resolve();
		if (libsPromise) return libsPromise;

		const loadScript = (src) => new Promise((resolve, reject) => {
			const s = document.createElement('script');
			s.src = src;
			s.onload = resolve;
			s.onerror = reject;
			document.head.appendChild(s);
		});

		libsPromise = Promise.all([
			window.marked ? Promise.resolve() : loadScript('https://fastly.jsdelivr.net/npm/marked@12.0.1/marked.min.js'),
			window.katex ? Promise.resolve() : loadScript('https://fastly.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js'),
			window.renderMathInElement ? Promise.resolve() : loadScript('https://fastly.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js')
		]).then(() => {
			libsLoaded = true;
			window.dispatchEvent(new Event('luogu-libs-ready'));
		}).catch(err => {
			console.error('渲染库加载失败:', err);
			libsPromise = null;
		});
		return libsPromise;
	}

	/* ==================== 存储与工具 ==================== */
	function loadRepo() {
		try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); }
		catch { return []; }
	}
	function saveRepo(r) {
		localStorage.setItem(STORAGE_KEY, JSON.stringify(r));
	}

	function loadBranches() {
		try { return JSON.parse(localStorage.getItem(BRANCH_KEY) || '[]'); }
		catch { return []; }
	}
	function saveBranches(b) {
		localStorage.setItem(BRANCH_KEY, JSON.stringify(b));
	}

	function loadNoteBranches() {
		try { return JSON.parse(localStorage.getItem(NOTE_BRANCH_KEY) || '[]'); }
		catch { return []; }
	}
	function saveNoteBranches(b) {
		localStorage.setItem(NOTE_BRANCH_KEY, JSON.stringify(b));
	}

	function loadNotes() {
		try { return JSON.parse(localStorage.getItem(NOTE_KEY) || '{}'); }
		catch { return {}; }
	}
	function saveNote(id, content, name, branchId) {
		const notes = loadNotes();
		const old = notes[id];
		notes[id] = {
			content: content,
			time: Date.now(),
			name: name || (old && old.name) || id,
			branchId: branchId !== undefined ? branchId : (old ? old.branchId : undefined)
		};
		localStorage.setItem(NOTE_KEY, JSON.stringify(notes));
	}
	function deleteNote(id) {
		const notes = loadNotes();
		if (Object.prototype.hasOwnProperty.call(notes, id)) {
			delete notes[id];
			localStorage.setItem(NOTE_KEY, JSON.stringify(notes));
		}
	}
	function getNote(id) {
		const notes = loadNotes();
		const n = notes[id];
		if (!n) return '';
		if (typeof n === 'string') return n;
		return n.content || '';
	}
	function getNoteTime(id) {
		const notes = loadNotes();
		const n = notes[id];
		if (n && typeof n === 'object') return n.time || 0;
		return 0;
	}
	function getNoteName(id) {
		const notes = loadNotes();
		const n = notes[id];
		if (!n) return id;
		if (typeof n === 'string') return id;
		return n.name || id;
	}

	function genId() {
		return Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
	}
	function formatTime(ts) {
		try {
			return new Date(ts).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
		} catch { return ''; }
	}
	function escHtml(s) {
		return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
	}
	function escAttr(s) {
		return escHtml(s).replace(/'/g, '&#39;');
	}

	function highlightText(text, q) {
		text = String(text == null ? '' : text);
		if (!q) return escHtml(text);
		const lower = text.toLowerCase();
		let i = 0, out = '';
		let found = false;
		while (true) {
			const j = lower.indexOf(q, i);
			if (j === -1) {
				out += escHtml(text.slice(i));
				break;
			}
			found = true;
			out += escHtml(text.slice(i, j));
			out += '<mark>' + escHtml(text.slice(j, j + q.length)) + '</mark>';
			i = j + q.length;
		}
		return found ? out : escHtml(text);
	}

	function toast(msg, type) {
		const t = document.createElement('div');
		t.textContent = msg;
		t.style.cssText = `position:fixed;top:20px;left:50%;transform:translateX(-50%);background:${type === 'error' ? '#f38ba8' : '#a6e3a1'};color:#1e1e2e;padding:10px 20px;border-radius:6px;font-size:14px;font-weight:600;z-index:${Z_DIALOG};box-shadow:0 4px 12px rgba(0,0,0,.3);font-family:-apple-system,sans-serif;transition:opacity .3s;pointer-events:none;`;
		document.body.appendChild(t);
		setTimeout(() => { t.style.opacity = '0'; }, 1800);
		setTimeout(() => t.remove(), 2200);
	}

	/* ==================== Markdown & LaTeX 渲染 ==================== */
	function renderMarkdownLocal(text) {
		if (!text) return '*暂无内容*';
		if (!window.marked || !window.renderMathInElement) {
			loadDependencies();
			return `<div style="color:#f9e2af;text-align:center;padding:20px;font-size:14px;">正在加载渲染引擎,请稍候...<br><small style="color:#6c7086;font-size:12px;">(如果长时间无响应,请刷新页面)</small></div>`;
		}
		try {
			let html = marked.parse(text, { breaks: true, gfm: true });
			const tempDiv = document.createElement('div');
			tempDiv.innerHTML = html;
			renderMathInElement(tempDiv, {
				delimiters: [
					{ left: '$$', right: '$$', display: true },
					{ left: '$', right: '$', display: false },
					{ left: '\\(', right: '\\)', display: false },
					{ left: '\\[', right: '\\]', display: true }
				],
				throwOnError: false,
				strict: false,
				ignoredTags: ["script", "noscript", "style", "textarea", "pre", "code"]
			});
			return tempDiv.innerHTML;
		} catch (err) {
			return `<div style="color:#f38ba8;">渲染出错:${escHtml(err.message)}</div>`;
		}
	}

	/* ==================== 编辑器与题目信息 ==================== */
	function getEditor() {
		if (window.monaco?.editor) {
			const editors = window.monaco.editor.getEditors ? window.monaco.editor.getEditors() : [];
			if (editors && editors.length > 0) {
				let best = editors[0], maxLen = -1;
				for (const e of editors) {
					const len = (e.getValue() || '').length;
					if (len > maxLen) { maxLen = len; best = e; }
				}
				return { setValue: (code) => best.setValue(code), getValue: () => best.getValue(), trigger: () => {}, refresh: () => {} };
			}
			const models = window.monaco.editor.getModels();
			if (models && models.length > 0) {
				let bestModel = models[0], maxLen = -1;
				for (const m of models) {
					if (m.isDisposed()) continue;
					const len = (m.getValue() || '').length;
					if (len > maxLen) { maxLen = len; bestModel = m; }
				}
				return { setValue: (code) => bestModel.setValue(code), getValue: () => bestModel.getValue(), trigger: () => {}, refresh: () => {} };
			}
		}
		const cm = document.querySelector('.CodeMirror');
		if (cm) {
			if (cm.CodeMirror?.setValue) return cm.CodeMirror;
			if (cm.__vue__?.editor?.setValue) return cm.__vue__.editor;
		}
		if (window.editor?.setValue) return window.editor;
		for (const ta of document.querySelectorAll('textarea')) {
			if (ta.CodeMirror?.setValue) return ta.CodeMirror;
			if (ta.__vue__?.editor?.setValue) return ta.__vue__.editor;
		}
		const ed = document.querySelector('[contenteditable="true"]');
		if (ed) return { setValue: (code) => { ed.innerText = code; }, getValue: () => ed.innerText };
		for (const ta of document.querySelectorAll('textarea')) {
			if (ta.offsetParent !== null && ta.type !== 'hidden') {
				return { setValue: (code) => { ta.value = code; ta.dispatchEvent(new Event('input', { bubbles: true })); }, getValue: () => ta.value };
			}
		}
		return null;
	}

	function getEditorCode() {
		const editor = getEditor();
		if (!editor) return '';
		try { return editor.getValue() || ''; } catch (_) { return ''; }
	}

	function setEditorCode(code) {
		const editor = getEditor();
		if (!editor) return false;
		try {
			if (editor.setValue) {
				editor.setValue('');
				editor.setValue(code);
			} else if (editor.setContent) {
				editor.setContent(code);
			} else {
				return false;
			}
			if (editor.trigger) {
				editor.trigger('change');
				editor.trigger('input');
			}
			if (editor.refresh) {
				editor.refresh();
				setTimeout(() => editor.refresh(), 50);
			}
			const cmEl = document.querySelector('.CodeMirror');
			if (cmEl) {
				cmEl.dispatchEvent(new Event('input', { bubbles: true }));
				cmEl.dispatchEvent(new Event('change', { bubbles: true }));
			}
			return true;
		} catch (_) {
			return false;
		}
	}

	function getProblemId() {
		const url = new URL(location.href);
		const pid = url.searchParams.get('pid') || url.searchParams.get('problem')
			|| (location.pathname.match(/\/problem\/([A-Za-z0-9_]+)/) || [])[1];
		if (pid) return pid;
		const t = document.title.replace(/\s*-\s*洛谷.*$/, '').trim();
		return t || 'unknown';
	}

	function getProblemName() {
		const url = new URL(location.href);
		const pid = url.searchParams.get('pid') || url.searchParams.get('problem')
			|| (location.pathname.match(/\/problem\/([A-Za-z0-9_]+)/) || [])[1];

		let name = '';
		if (url.pathname.includes('/problem/') || url.hash.includes('ide')) {
			const titleEl = document.querySelector('.problem-title') || document.querySelector('h1') || document.querySelector('.title');
			if (titleEl) {
				let t = titleEl.textContent.trim();
				if (t && t !== '洛谷' && t !== '主页' && t !== '首页' && t !== '题目列表' && t.length > (pid ? pid.length : 0)) {
					name = t;
				}
			}
			if (!name) {
				let title = document.title.replace(/\s*-\s*洛谷.*$/, '').trim();
				if (title && title !== '洛谷' && title !== '主页') name = title;
			}
			if (!name) {
				const h1s = document.querySelectorAll('h1');
				for (const h of h1s) {
					let t = h.textContent.trim();
					if (t && pid && t.includes(pid) && t.length > pid.length) { name = t; break; }
				}
			}
		}

		if (!name) {
			for (const sel of ['.problem-title', '[class*="problem-title"]', 'h1', '.title']) {
				const el = document.querySelector(sel);
				if (el) {
					const t = el.textContent.trim();
					if (t && t.length < 120 && !['洛谷', '首页', '题目列表', '主页'].includes(t)) { name = t; break; }
				}
			}
		}
		if (!name) {
			const t = document.title.replace(/\s*-\s*洛谷.*$/, '').trim();
			if (t && t !== '洛谷' && t !== '主页') name = t;
		}

		name = name || pid || '未命名';
		return name;
	}

	/* ==================== 笔记弹窗 (左右对比) ==================== */
	function showNoteDialog(mode, _pid, _name) {
		if (document.getElementById('luogu-note-dialog')) return;
		const pid = _pid || getProblemId();

		let name = _name;
		if (!name) {
			name = getProblemName();
			if (name === pid) {
				const realName = getProblemName();
				if (realName && realName !== pid) name = realName;
			}
		}

		const existingNote = getNote(pid);
		const isView = mode === 'view';

		const overlay = document.createElement('div');
		overlay.id = 'luogu-note-dialog';
		overlay.style.cssText = `position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;z-index:${Z_DIALOG};`;

		const modal = document.createElement('div');
		modal.style.cssText = `background:#1e1e2e;border:1px solid #45475a;border-radius:8px;padding:20px;width:90%;max-width:900px;height:80vh;color:#cdd6f4;display:flex;flex-direction:column;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;box-sizing:border-box;`;

		modal.innerHTML = `
			<h3 style="margin:0 0 12px 0;font-size:16px;flex-shrink:0;">${isView ? '查看笔记' : '编辑笔记'} - ${escHtml(name)}</h3>

			<div style="display:flex; flex:1; gap:16px; overflow:hidden; margin-bottom:16px;">
				${isView ? '' : `
				<div style="flex:1; display:flex; flex-direction:column; min-width:0;">
					<label style="font-size:12px;color:#a6adc8;margin-bottom:4px;">源码 (Markdown / LaTeX)</label>
					<textarea id="note-input" placeholder="支持 Markdown 和 LaTeX..." style="flex:1; width:100%; resize:none; padding:10px; background:#181825; border:1px solid #45475a; border-radius:6px; color:#cdd6f4; font-family:monospace; font-size:13px; outline:none; line-height:1.5;">${escHtml(existingNote)}</textarea>
				</div>
				`}
				<div style="flex:1; display:flex; flex-direction:column; min-width:0;">
					<label style="font-size:12px;color:#a6adc8;margin-bottom:4px;">预览</label>
					<div id="note-preview-wrap" style="flex:1; width:100%; padding:10px 14px; background:#181825; border:1px solid #45475a; border-radius:6px; color:#cdd6f4; overflow-y:auto; font-size:14px; line-height:1.6; word-wrap:break-word;"></div>
				</div>
			</div>

			<div style="display:flex; gap:8px; justify-content:flex-end; flex-shrink:0;">
				${isView ? '' : '<button id="note-del" style="padding:8px 20px;background:#f38ba8;border:none;border-radius:6px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:14px;margin-right:auto;">删除</button>'}
				<button id="note-cancel" style="padding:8px 20px;background:#313244;border:none;border-radius:6px;color:#cdd6f4;cursor:pointer;font-weight:600;font-size:14px;">关闭</button>
				<button id="note-fill" style="padding:8px 20px;background:#89b4fa;border:none;border-radius:6px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:14px;">填入编辑器</button>
				${isView ? '' : '<button id="note-save" style="padding:8px 20px;background:#a6e3a1;border:none;border-radius:6px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:14px;">保存</button>'}
			</div>
		`;
		overlay.appendChild(modal);
		document.body.appendChild(overlay);

		const inputEl = modal.querySelector('#note-input');
		const previewEl = modal.querySelector('#note-preview-wrap');

		const renderMarkdown = () => {
			if (previewEl) previewEl.innerHTML = renderMarkdownLocal(inputEl ? inputEl.value : existingNote);
		};

		const closeDlg = () => {
			window.removeEventListener('luogu-libs-ready', renderMarkdown);
			if (overlay.parentNode) overlay.remove();
		};

		window.addEventListener('luogu-libs-ready', renderMarkdown);
		modal.querySelector('#note-cancel').addEventListener('click', closeDlg);
		overlay.addEventListener('click', (e) => { if (e.target === overlay) closeDlg(); });

		modal.querySelector('#note-fill').addEventListener('click', () => {
			const txt = inputEl ? inputEl.value : existingNote;
			if (setEditorCode(txt)) {
				toast('已回填到编辑器');
				closeDlg();
			} else {
				toast('未找到IDE编辑器', 'error');
			}
		});

		if (!isView) {
			inputEl.addEventListener('input', renderMarkdown);
			setTimeout(() => inputEl.focus(), 100);

			modal.querySelector('#note-del').addEventListener('click', () => {
				if (!confirm('确定删除这篇笔记?')) return;
				deleteNote(pid);
				toast('笔记已删除');
				if (panelVisible) renderRepoList();
				closeDlg();
			});

			modal.querySelector('#note-save').addEventListener('click', () => {
				saveNote(pid, inputEl.value, name);
				toast('笔记已保存');
				if (panelVisible) renderRepoList();
				closeDlg();
			});
		}

		renderMarkdown();
	}

	/* ==================== 代码仓库与分支弹窗 ==================== */
	function showItemDialog(item, mode) {
		if (document.getElementById('luogu-repo-dialog')) return;
		const isView = mode === 'view';
		const isEdit = mode === 'edit';

		const overlay = document.createElement('div');
		overlay.id = 'luogu-repo-dialog';
		overlay.style.cssText = `position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;z-index:${Z_DIALOG};`;

		const modal = document.createElement('div');
		modal.style.cssText = `background:#1e1e2e;border:1px solid #45475a;border-radius:8px;padding:20px;width:90%;max-width:520px;color:#cdd6f4;display:flex;flex-direction:column;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;box-sizing:border-box;`;

		const title = isView ? '查看代码' : (isEdit ? '编辑仓库项' : '新建仓库项');
		const nameVal = item ? item.name : '';
		const codeVal = item ? item.code : '';

		modal.innerHTML = `
			<h3 style="margin:0 0 12px 0;font-size:15px;">${title}</h3>
			<label style="display:block;font-size:12px;color:#a6adc8;margin-bottom:4px;">名称</label>
			<input id="dlg-name" type="text" placeholder="题目名称" value="${escAttr(nameVal)}" ${isView ? 'readonly' : ''} style="width:100%;box-sizing:border-box;padding:8px;margin-bottom:12px;background:#181825;border:1px solid #45475a;border-radius:4px;color:${isView ? '#6c7086' : '#cdd6f4'};font-size:14px;outline:none;">
			<label style="display:block;font-size:12px;color:#a6adc8;margin-bottom:4px;">代码</label>
			<textarea id="dlg-code" placeholder="暂无代码" ${isView ? 'readonly' : ''} style="width:100%;box-sizing:border-box;height:220px;padding:8px;margin-bottom:12px;background:#181825;border:1px solid #45475a;border-radius:4px;color:${isView ? '#a6adc8' : '#cdd6f4'};font-family:monospace;font-size:13px;resize:vertical;outline:none;">${escHtml(codeVal)}</textarea>
			<div style="display:flex;gap:8px;justify-content:flex-end;">
				${isEdit ? '<button id="dlg-del" style="padding:6px 16px;background:#f38ba8;border:none;border-radius:4px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:13px;">删除</button>' : ''}
				<button id="dlg-cancel" style="padding:6px 16px;background:#313244;border:none;border-radius:4px;color:#cdd6f4;cursor:pointer;font-weight:600;font-size:13px;">关闭</button>
				${isView ? '<button id="dlg-fill" style="padding:6px 16px;background:#89b4fa;border:none;border-radius:4px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:13px;">填入编辑器</button>' : ''}
				${!isView ? '<button id="dlg-save" style="padding:6px 16px;background:#89b4fa;border:none;border-radius:4px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:13px;">保存</button>' : ''}
			</div>
		`;
		overlay.appendChild(modal);
		document.body.appendChild(overlay);

		const nameInput = modal.querySelector('#dlg-name');
		const codeInput = modal.querySelector('#dlg-code');
		const closeDlg = () => { if (overlay.parentNode) overlay.remove(); };

		modal.querySelector('#dlg-cancel').addEventListener('click', closeDlg);
		overlay.addEventListener('click', (e) => { if (e.target === overlay) closeDlg(); });

		if (isView) {
			modal.querySelector('#dlg-fill').addEventListener('click', () => {
				if (setEditorCode(codeVal)) {
					toast('已回填到编辑器');
					closeDlg();
				} else {
					toast('未找到IDE编辑器', 'error');
				}
			});
		} else {
			modal.querySelector('#dlg-save').addEventListener('click', () => {
				const name = nameInput.value.trim();
				const code = codeInput.value;
				if (!name) { toast('名称不能为空', 'error'); nameInput.focus(); return; }
				const repo = loadRepo();
				if (isEdit && item) {
					const target = repo.find(r => r.id === item.id);
					if (target) { target.name = name; target.code = code; saveRepo(repo); toast('已更新'); }
				} else {
					repo.push({ id: genId(), name, code, time: Date.now() });
					saveRepo(repo);
					toast('已保存');
				}
				renderRepoList();
				closeDlg();
			});

			if (isEdit) {
				modal.querySelector('#dlg-del').addEventListener('click', () => {
					if (!confirm('确定删除?')) return;
					saveRepo(loadRepo().filter(r => r.id !== item.id));
					renderRepoList();
					closeDlg();
					toast('已删除');
				});
			}
			setTimeout(() => { nameInput.focus(); nameInput.select(); }, 50);
		}
	}

	function showBranchDialog(branch, type = 'repo') {
		const dlgId = type === 'note' ? 'luogu-note-branch-dialog' : 'luogu-repo-branch-dialog';
		if (document.getElementById(dlgId)) return;
		const isEdit = !!branch;

		const overlay = document.createElement('div');
		overlay.id = dlgId;
		overlay.style.cssText = `position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;z-index:${Z_DIALOG};`;

		const modal = document.createElement('div');
		modal.style.cssText = `background:#1e1e2e;border:1px solid #45475a;border-radius:8px;padding:20px;width:90%;max-width:400px;color:#cdd6f4;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;box-sizing:border-box;`;

		modal.innerHTML = `
			<h3 style="margin:0 0 12px 0;font-size:15px;display:flex;align-items:center;gap:6px;">
				<span style="color:#89b4fa;display:inline-flex;">${ICON_BRANCH}</span>
				${isEdit ? '编辑' : '新建'}${type === 'note' ? '笔记' : '代码'}分支
			</h3>
			<label style="display:block;font-size:12px;color:#a6adc8;margin-bottom:4px;">分支名称</label>
			<input id="branch-name" type="text" placeholder="例如:动态规划 / 图论" value="${isEdit ? escAttr(branch.name) : ''}" style="width:100%;box-sizing:border-box;padding:8px;margin-bottom:12px;background:#181825;border:1px solid #45475a;border-radius:4px;color:#cdd6f4;font-size:14px;outline:none;">
			<div style="display:flex;gap:8px;justify-content:flex-end;">
				${isEdit ? '<button id="branch-del" style="padding:6px 16px;background:#f38ba8;border:none;border-radius:4px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:13px;">删除</button>' : ''}
				<button id="branch-cancel" style="padding:6px 16px;background:#313244;border:none;border-radius:4px;color:#cdd6f4;cursor:pointer;font-weight:600;font-size:13px;">取消</button>
				<button id="branch-save" style="padding:6px 16px;background:#89b4fa;border:none;border-radius:4px;color:#1e1e2e;cursor:pointer;font-weight:600;font-size:13px;">保存</button>
			</div>
		`;
		overlay.appendChild(modal);
		document.body.appendChild(overlay);

		const nameInput = modal.querySelector('#branch-name');
		const closeDlg = () => { if (overlay.parentNode) overlay.remove(); };

		modal.querySelector('#branch-cancel').addEventListener('click', closeDlg);
		overlay.addEventListener('click', (e) => { if (e.target === overlay) closeDlg(); });

		modal.querySelector('#branch-save').addEventListener('click', () => {
			const name = nameInput.value.trim();
			if (!name) { toast('名称不能为空', 'error'); nameInput.focus(); return; }
			if (type === 'note') {
				const branches = loadNoteBranches();
				if (isEdit) {
					const b = branches.find(x => x.id === branch.id);
					if (b) { b.name = name; saveNoteBranches(branches); toast('已更新分支'); }
				} else {
					branches.push({ id: genId(), name, time: Date.now() });
					saveNoteBranches(branches);
					toast('已创建笔记分支:' + name);
				}
			} else {
				const branches = loadBranches();
				if (isEdit) {
					const b = branches.find(x => x.id === branch.id);
					if (b) { b.name = name; saveBranches(branches); toast('已更新分支'); }
				} else {
					branches.push({ id: genId(), name, time: Date.now() });
					saveBranches(branches);
					toast('已创建代码分支:' + name);
				}
			}
			renderRepoList();
			closeDlg();
		});

		if (isEdit) {
			modal.querySelector('#branch-del').addEventListener('click', () => {
				if (!confirm(`确定删除分支「${branch.name}」?`)) return;
				if (type === 'note') {
					saveNoteBranches(loadNoteBranches().filter(b => b.id !== branch.id));
					const notes = loadNotes();
					let n = 0;
					for (const pid in notes) { if (notes[pid].branchId === branch.id) { delete notes[pid].branchId; n++; } }
					if (n) localStorage.setItem(NOTE_KEY, JSON.stringify(notes));
					collapsedNoteBranches.delete(branch.id);
				} else {
					saveBranches(loadBranches().filter(b => b.id !== branch.id));
					const repo = loadRepo();
					let n = 0;
					for (const it of repo) { if (it.branchId === branch.id) { delete it.branchId; n++; } }
					if (n) saveRepo(repo);
					collapsedBranches.delete(branch.id);
				}
				renderRepoList();
				closeDlg();
				toast('已删除分支');
			});
		}

		setTimeout(() => { nameInput.focus(); nameInput.select(); }, 50);
	}

	/* ==================== 侧边面板管理 ==================== */
	let panelHost = null, shadowRoot = null;
	let panelVisible = false;
	let draggingItemId = null;
	let draggingNotePid = null;
	let suppressClickUntil = 0;

	const collapsedBranches = new Set();
	let rootCollapsed = false;
	const collapsedNoteBranches = new Set();
	let rootNoteCollapsed = false;
	let searchQuery = '';
	let currentView = 'repo';

	function createPanel() {
		if (panelHost) return;
		panelHost = document.createElement('div');
		panelHost.id = 'luogu-code-repo-host';
		panelHost.style.cssText = `position:fixed;top:0;right:0;width:${PANEL_WIDTH};height:100vh;z-index:${Z_PANEL};pointer-events:none;`;
		document.body.appendChild(panelHost);
		shadowRoot = panelHost.attachShadow({ mode: 'open' });

		const style = document.createElement('style');
		style.textContent = `
			* { box-sizing: border-box; margin: 0; padding: 0; }
			.panel { width: 100%; height: 100%; background: #1e1e2e; color: #cdd6f4; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; flex-direction: column; border-left: 1px solid #313244; pointer-events: auto; box-shadow: -4px 0 20px rgba(0, 0, 0, 0.4); transform: translateX(100%); transition: transform .3s cubic-bezier(0.18, 0.89, 0.32, 1.28); position: relative; }
			.panel.open { transform: translateX(0); }
			.header { display: flex; align-items: center; justify-content: space-between; padding: 10px 12px; border-bottom: 1px solid #313244; flex-shrink: 0; }
			.header-actions { display: flex; gap: 6px; align-items: center; }
			.view-tabs { display: flex; gap: 4px; align-items: center; }
			.view-tab { background: transparent; border: none; color: #6c7086; font-size: 13px; font-weight: 600; padding: 6px 10px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 5px; font-family: inherit; transition: background .15s, color .15s; line-height: 1; }
			.view-tab:hover { background: #262637; color: #cdd6f4; }
			.view-tab.active { background: #313244; color: #cdd6f4; }
			.btn-icon { background: none; border: none; color: #cdd6f4; font-size: 20px; cursor: pointer; padding: 2px 8px; border-radius: 4px; line-height: 1; font-family: inherit; display: inline-flex; align-items: center; justify-content: center; height: 28px; }
			.btn-icon:hover { background: #313244; }
			.search-bar { display: flex; align-items: center; gap: 8px; padding: 8px 16px; border-bottom: 1px solid #313244; flex-shrink: 0; }
			.search-bar input { flex: 1; min-width: 0; background: #181825; border: 1px solid #45475a; border-radius: 6px; padding: 6px 8px; color: #cdd6f4; font-size: 13px; outline: none; font-family: inherit; }
			.search-bar input:focus { border-color: #89b4fa; }
			.search-clear { background: none; border: none; color: #6c7086; cursor: pointer; font-size: 18px; line-height: 1; padding: 0 4px; border-radius: 4px; display: none; font-family: inherit; }
			.search-clear.show { display: inline-flex; }
			.repo-list { flex: 1; overflow-y: auto; padding: 8px; }
			.repo-item { padding: 10px 12px; margin-bottom: 6px; background: #181825; border-radius: 6px; cursor: pointer; border: 1px solid transparent; transition: border-color .15s, background .15s; user-select: none; }
			.repo-item:hover { background: #262637; border-color: #45475a; }
			.repo-item.dragging { opacity: .35; }
			.repo-item .name { font-size: 14px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 4px; }
			.repo-item .time { font-size: 11px; color: #6c7086; }
			.empty-tip { text-align: center; padding: 40px 20px; color: #6c7086; font-size: 14px; line-height: 1.9; }
			mark { background: #f9e2af; color: #1e1e2e; border-radius: 2px; padding: 0 1px; }
			.root-zone { margin-bottom: 10px; }
			.branch { margin-bottom: 10px; }
			.branch-header, .root-header { display: flex; align-items: center; gap: 6px; padding: 8px 10px; background: #262637; border-radius: 6px; cursor: pointer; user-select: none; border: 1px solid transparent; transition: background .15s, border-color .15s; }
			.branch-header:hover, .root-header:hover { background: #313244; }
			.branch-header.drag-over, .root-header.drag-over { border-color: #89b4fa; background: #313244; }
			.branch-header .arrow, .root-header .arrow { font-size: 10px; width: 12px; text-align: center; color: #a6adc8; flex-shrink: 0; }
			.branch-header .branch-icon, .root-header .branch-icon { display: inline-flex; color: #89b4fa; flex-shrink: 0; }
			.branch-header .branch-name, .root-header .branch-name { flex: 1; font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
			.branch-header .count, .root-header .count { font-size: 11px; color: #6c7086; background: #181825; padding: 1px 7px; border-radius: 8px; flex-shrink: 0; }
			.branch-body { margin: 4px 0 0 8px; padding-left: 12px; border-left: 2px solid #313244; border-radius: 0 4px 4px 0; transition: background .15s, border-color .15s; }
			.root-body { margin-top: 4px; }
			.root-body.indented { margin-left: 8px; padding-left: 12px; border-left: 2px dashed #313244; border-radius: 0 4px 4px 0; }
			.branch-body.drag-over { border-left-color: #89b4fa; background: rgba(137, 180, 250, 0.07); }
			.root-body.drag-over { border-left-color: #89b4fa; background: rgba(137, 180, 250, 0.07); }
			.branch-empty { padding: 12px; margin: 2px 0; text-align: center; color: #6c7086; font-size: 12px; border: 1px dashed #313244; border-radius: 4px; }
		`;
		shadowRoot.appendChild(style);

		const panel = document.createElement('div');
		panel.className = 'panel';
		panel.id = 'repo-panel';
		panel.innerHTML = `
			<div class="header">
				<div class="view-tabs">
					<button class="view-tab active" id="tab-repo">${ICON_REPO}<span>代码仓库</span></button>
					<button class="view-tab" id="tab-notes">${ICON_NOTE}<span>代码笔记</span></button>
				</div>
				<div class="header-actions">
					<button class="btn-icon" id="btn-new-branch" data-repo-only title="新建代码分支">${ICON_BRANCH}</button>
					<button class="btn-icon" id="btn-new" data-repo-only title="新建仓库项">+</button>
					<button class="btn-icon" id="btn-new-note-branch" data-notes-only title="新建笔记分支" style="display:none">${ICON_BRANCH}</button>
					<button class="btn-icon" id="btn-new-note" data-notes-only title="新建笔记" style="display:none">+</button>
					<button class="btn-icon" id="btn-close" title="关闭">×</button>
				</div>
			</div>
			<div class="search-bar">
				<span>${ICON_SEARCH}</span>
				<input id="search-input" type="text" placeholder="搜索名称或内容…" autocomplete="off" spellcheck="false">
				<button class="search-clear" id="search-clear" title="清空">×</button>
			</div>
			<div class="repo-list" id="repo-list"></div>
		`;
		shadowRoot.appendChild(panel);

		panel.querySelector('#btn-close').addEventListener('click', closePanel);
		panel.querySelector('#btn-new').addEventListener('click', () => showItemDialog(null, 'new'));
		panel.querySelector('#btn-new-branch').addEventListener('click', () => showBranchDialog(null, 'repo'));
		panel.querySelector('#btn-new-note').addEventListener('click', () => showNoteDialog('edit'));
		panel.querySelector('#btn-new-note-branch').addEventListener('click', () => showBranchDialog(null, 'note'));

		panel.querySelector('#tab-repo').addEventListener('click', () => { currentView = 'repo'; updateTabs(); renderRepoList(); });
		panel.querySelector('#tab-notes').addEventListener('click', () => { currentView = 'notes'; updateTabs(); renderRepoList(); });

		const searchInput = panel.querySelector('#search-input');
		const searchClear = panel.querySelector('#search-clear');
		const syncClear = () => searchClear.classList.toggle('show', searchInput.value.length > 0);

		searchInput.addEventListener('input', () => { searchQuery = searchInput.value.trim().toLowerCase(); syncClear(); renderRepoList(); });
		searchInput.addEventListener('keydown', (e) => { if (e.key === 'Escape') { searchInput.value = ''; searchQuery = ''; syncClear(); renderRepoList(); } });
		searchClear.addEventListener('click', () => { searchInput.value = ''; searchQuery = ''; syncClear(); renderRepoList(); searchInput.focus(); });
		syncClear();
		updateTabs();
	}

	function updateTabs() {
		if (!shadowRoot) return;
		const panel = shadowRoot.querySelector('#repo-panel');
		panel.querySelector('#tab-repo').classList.toggle('active', currentView === 'repo');
		panel.querySelector('#tab-notes').classList.toggle('active', currentView === 'notes');
		panel.querySelectorAll('[data-repo-only]').forEach(el => { el.style.display = currentView === 'repo' ? '' : 'none'; });
		panel.querySelectorAll('[data-notes-only]').forEach(el => { el.style.display = currentView === 'notes' ? '' : 'none'; });
	}

	function makeDropZone(el, getBranchId, type) {
		el.addEventListener('dragover', (e) => {
			if (type === 'repo' && !draggingItemId) return;
			if (type === 'note' && !draggingNotePid) return;
			e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'move'; el.classList.add('drag-over');
		});
		el.addEventListener('dragleave', (e) => {
			if (e.relatedTarget && el.contains(e.relatedTarget)) return;
			el.classList.remove('drag-over');
		});
		el.addEventListener('drop', (e) => {
			if (type === 'repo' && !draggingItemId) return;
			if (type === 'note' && !draggingNotePid) return;
			e.preventDefault(); e.stopPropagation(); el.classList.remove('drag-over');
			const id = type === 'repo' ? draggingItemId : draggingNotePid;
			draggingItemId = null; draggingNotePid = null; suppressClickUntil = Date.now() + 300;
			if (type === 'repo') moveItemToBranch(id, getBranchId()); else moveNoteToBranch(id, getBranchId());
		});
	}

	function moveItemToBranch(itemId, branchId) {
		const repo = loadRepo(); const it = repo.find(r => r.id === itemId); if (!it) return;
		if (branchId) { if (it.branchId === branchId) return; it.branchId = branchId; }
		else { if (!it.branchId) return; delete it.branchId; }
		saveRepo(repo); renderRepoList();
		toast(branchId ? '已移动到分支' : '已移出分支');
	}

	function moveNoteToBranch(pid, branchId) {
		const notes = loadNotes(); if (!notes[pid]) return;
		if (branchId) { if (notes[pid].branchId === branchId) return; notes[pid].branchId = branchId; }
		else { if (!notes[pid].branchId) return; delete notes[pid].branchId; }
		localStorage.setItem(NOTE_KEY, JSON.stringify(notes)); renderRepoList();
		toast(branchId ? '笔记已移入分支' : '笔记已移出分支');
	}

	function renderRepoList() {
		if (!shadowRoot) return;
		const listEl = shadowRoot.querySelector('#repo-list');
		listEl.innerHTML = '';

		if (currentView === 'notes') {
			// ===== 笔记视图 =====
			const notes = loadNotes();
			const branches = loadNoteBranches();
			const branchIds = new Set(branches.map(b => b.id));
			let changed = false;
			for (const pid in notes) { if (notes[pid].branchId && !branchIds.has(notes[pid].branchId)) { delete notes[pid].branchId; changed = true; } }
			if (changed) localStorage.setItem(NOTE_KEY, JSON.stringify(notes));

			const items = Object.entries(notes).map(([pid, n]) => {
				let content = '', time = 0, name = pid, branchId = undefined;
				if (typeof n === 'string') { content = n; }
				else if (n && typeof n === 'object') { content = n.content || ''; time = n.time || 0; name = n.name || pid; branchId = n.branchId; }
				return { pid, name, content, time, branchId };
			});

			const q = searchQuery;
			const matches = (it) => !q || (it.name || '').toLowerCase().includes(q) || (it.pid || '').toLowerCase().includes(q) || (it.content || '').toLowerCase().includes(q);

			if (!items.length && !branches.length) {
				listEl.innerHTML = '<div class="empty-tip">还没有笔记<br>点击右上角 + 新建</div>'; return;
			}

			const sorted = [...items].sort((a, b) => b.time - a.time);
			const branchItems = new Map(); const rootItems = [];
			for (const it of sorted) {
				if (!matches(it)) continue;
				if (it.branchId) { if (!branchItems.has(it.branchId)) branchItems.set(it.branchId, []); branchItems.get(it.branchId).push(it); }
				else rootItems.push(it);
			}

			const showRoot = !q || rootItems.length > 0 || branches.length === 0;
			if (showRoot) {
				const rootZone = document.createElement('div'); rootZone.className = 'root-zone';
				if (branches.length > 0) {
					const collapsedRoot = !q && rootNoteCollapsed;
					const rootHeader = document.createElement('div'); rootHeader.className = 'root-header';
					rootHeader.innerHTML = `<span class="arrow">${collapsedRoot ? '▶' : '▼'}</span><span class="branch-icon">${ICON_INBOX}</span><span class="branch-name">未分类</span><span class="count">${rootItems.length}</span>`;
					rootHeader.addEventListener('click', () => { if (Date.now() < suppressClickUntil || q) return; rootNoteCollapsed = !rootNoteCollapsed; renderRepoList(); });
					makeDropZone(rootHeader, () => null, 'note'); rootZone.appendChild(rootHeader);
					if (!collapsedRoot) {
						const rootBody = document.createElement('div'); rootBody.className = 'root-body indented';
						if (!rootItems.length) rootBody.innerHTML = `<div class="branch-empty">将笔记拖到这里可移出分支</div>`;
						for (const it of rootItems) rootBody.appendChild(createNoteItemEl(it, q));
						makeDropZone(rootBody, () => null, 'note'); rootZone.appendChild(rootBody);
					}
				} else {
					const rootBody = document.createElement('div'); rootBody.className = 'root-body';
					for (const it of rootItems) rootBody.appendChild(createNoteItemEl(it, q));
					makeDropZone(rootBody, () => null, 'note'); rootZone.appendChild(rootBody);
				}
				listEl.appendChild(rootZone);
			}

			for (const branch of branches) {
				const items = branchItems.get(branch.id) || [];
				if (q && items.length === 0) continue;
				const collapsed = !q && collapsedNoteBranches.has(branch.id);
				const wrap = document.createElement('div'); wrap.className = 'branch';
				const header = document.createElement('div'); header.className = 'branch-header';
				header.innerHTML = `<span class="arrow">${collapsed ? '▶' : '▼'}</span><span class="branch-icon">${ICON_BRANCH}</span><span class="branch-name">${escHtml(branch.name)}</span><span class="count">${items.length}</span>`;
				header.addEventListener('click', () => { if (Date.now() < suppressClickUntil || q) return; if (collapsedNoteBranches.has(branch.id)) collapsedNoteBranches.delete(branch.id); else collapsedNoteBranches.add(branch.id); renderRepoList(); });
				header.addEventListener('contextmenu', (e) => { e.preventDefault(); showBranchDialog(branch, 'note'); });
				makeDropZone(header, () => branch.id, 'note'); wrap.appendChild(header);
				if (!collapsed) {
					const body = document.createElement('div'); body.className = 'branch-body';
					if (!items.length) body.innerHTML = `<div class="branch-empty">拖拽笔记到此分支</div>`;
					for (const it of items) body.appendChild(createNoteItemEl(it, q));
					makeDropZone(body, () => branch.id, 'note'); wrap.appendChild(body);
				}
				listEl.appendChild(wrap);
			}
			return;
		}

		// ===== 代码仓库视图 =====
		const repo = loadRepo();
		const branches = loadBranches();
		const branchIds = new Set(branches.map(b => b.id));
		let changed = false;
		for (const it of repo) { if (it.branchId && !branchIds.has(it.branchId)) { delete it.branchId; changed = true; } }
		if (changed) saveRepo(repo);

		const q = searchQuery;
		const matches = (it) => !q || (it.name || '').toLowerCase().includes(q) || (it.code || '').toLowerCase().includes(q);

		if (!repo.length && !branches.length) {
			listEl.innerHTML = '<div class="empty-tip">仓库为空<br>点击右侧 + 新建<br>或在 IDE 中点击“收录到仓库”</div>'; return;
		}

		const sorted = [...repo].sort((a, b) => b.time - a.time);
		const branchItems = new Map(); const rootItems = [];
		for (const it of sorted) {
			if (!matches(it)) continue;
			if (it.branchId) { if (!branchItems.has(it.branchId)) branchItems.set(it.branchId, []); branchItems.get(it.branchId).push(it); }
			else rootItems.push(it);
		}

		const showRoot = !q || rootItems.length > 0 || branches.length === 0;
		if (showRoot) {
			const rootZone = document.createElement('div'); rootZone.className = 'root-zone';
			if (branches.length > 0) {
				const collapsedRoot = !q && rootCollapsed;
				const rootHeader = document.createElement('div'); rootHeader.className = 'root-header';
				rootHeader.innerHTML = `<span class="arrow">${collapsedRoot ? '▶' : '▼'}</span><span class="branch-icon">${ICON_INBOX}</span><span class="branch-name">未分类</span><span class="count">${rootItems.length}</span>`;
				rootHeader.addEventListener('click', () => { if (Date.now() < suppressClickUntil || q) return; rootCollapsed = !rootCollapsed; renderRepoList(); });
				makeDropZone(rootHeader, () => null, 'repo'); rootZone.appendChild(rootHeader);
				if (!collapsedRoot) {
					const rootBody = document.createElement('div'); rootBody.className = 'root-body indented';
					if (!rootItems.length) rootBody.innerHTML = `<div class="branch-empty">将仓库项拖到这里可移出分支</div>`;
					for (const it of rootItems) rootBody.appendChild(createItemEl(it, q));
					makeDropZone(rootBody, () => null, 'repo'); rootZone.appendChild(rootBody);
				}
			} else {
				const rootBody = document.createElement('div'); rootBody.className = 'root-body';
				for (const it of rootItems) rootBody.appendChild(createItemEl(it, q));
				makeDropZone(rootBody, () => null, 'repo'); rootZone.appendChild(rootBody);
			}
			listEl.appendChild(rootZone);
		}

		for (const branch of branches) {
			const items = branchItems.get(branch.id) || [];
			if (q && items.length === 0) continue;
			const collapsed = !q && collapsedBranches.has(branch.id);
			const wrap = document.createElement('div'); wrap.className = 'branch';
			const header = document.createElement('div'); header.className = 'branch-header';
			header.innerHTML = `<span class="arrow">${collapsed ? '▶' : '▼'}</span><span class="branch-icon">${ICON_BRANCH}</span><span class="branch-name">${escHtml(branch.name)}</span><span class="count">${items.length}</span>`;
			header.addEventListener('click', () => { if (Date.now() < suppressClickUntil || q) return; if (collapsedBranches.has(branch.id)) collapsedBranches.delete(branch.id); else collapsedBranches.add(branch.id); renderRepoList(); });
			header.addEventListener('contextmenu', (e) => { e.preventDefault(); showBranchDialog(branch, 'repo'); });
			makeDropZone(header, () => branch.id, 'repo'); wrap.appendChild(header);
			if (!collapsed) {
				const body = document.createElement('div'); body.className = 'branch-body';
				if (!items.length) body.innerHTML = `<div class="branch-empty">拖拽仓库项到此分支</div>`;
				for (const it of items) body.appendChild(createItemEl(it, q));
				makeDropZone(body, () => branch.id, 'repo'); wrap.appendChild(body);
			}
			listEl.appendChild(wrap);
		}
	}

	function createItemEl(item, q) {
		const div = document.createElement('div'); div.className = 'repo-item'; div.draggable = true;
		const nameDiv = document.createElement('div'); nameDiv.className = 'name';
		nameDiv.innerHTML = q ? highlightText(item.name, q) : escHtml(item.name);
		const timeDiv = document.createElement('div'); timeDiv.className = 'time'; timeDiv.textContent = formatTime(item.time);
		div.appendChild(nameDiv); div.appendChild(timeDiv);

		let clickTimer = null;
		div.addEventListener('click', () => { if (Date.now() < suppressClickUntil) return; clearTimeout(clickTimer); clickTimer = setTimeout(() => { if (Date.now() < suppressClickUntil) return; showItemDialog(item, 'view'); }, 250); });
		div.addEventListener('dblclick', () => { clearTimeout(clickTimer); if (Date.now() < suppressClickUntil) return; if (setEditorCode(item.code)) { div.style.borderColor = '#a6e3a1'; setTimeout(() => div.style.borderColor = '', 600); toast('已回填:' + item.name); } else { toast('未找到IDE编辑器', 'error'); } });
		div.addEventListener('contextmenu', (e) => { e.preventDefault(); clearTimeout(clickTimer); showItemDialog(item, 'edit'); });
		div.addEventListener('dragstart', (e) => { draggingItemId = item.id; draggingNotePid = null; clearTimeout(clickTimer); suppressClickUntil = Date.now() + 300; div.classList.add('dragging'); e.dataTransfer.effectAllowed = 'move'; try { e.dataTransfer.setData('text/plain', item.id); } catch (_) {} });
		div.addEventListener('dragend', () => { div.classList.remove('dragging'); draggingItemId = null; suppressClickUntil = Date.now() + 300; if (shadowRoot) shadowRoot.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over')); });
		return div;
	}

	function createNoteItemEl(note, q) {
		const div = document.createElement('div'); div.className = 'repo-item'; div.draggable = true;

		let displayName = note.name || note.pid;

		const nameDiv = document.createElement('div'); nameDiv.className = 'name';
		nameDiv.innerHTML = q ? highlightText(displayName, q) : escHtml(displayName);
		const timeDiv = document.createElement('div'); timeDiv.className = 'time'; timeDiv.textContent = note.time ? formatTime(note.time) : '暂无内容';
		div.appendChild(nameDiv); div.appendChild(timeDiv);

		let clickTimer = null;
		div.addEventListener('click', () => { if (Date.now() < suppressClickUntil) return; clearTimeout(clickTimer); clickTimer = setTimeout(() => { if (Date.now() < suppressClickUntil) return; showNoteDialog('view', note.pid, note.name); }, 250); });
		div.addEventListener('dblclick', () => { clearTimeout(clickTimer); if (Date.now() < suppressClickUntil) return; if (note.content && setEditorCode(note.content)) { div.style.borderColor = '#a6e3a1'; setTimeout(() => div.style.borderColor = '', 600); toast('已回填:' + displayName); } else { if (!note.content) toast('笔记内容为空', 'error'); else toast('未找到IDE编辑器', 'error'); } });
		div.addEventListener('contextmenu', (e) => { e.preventDefault(); clearTimeout(clickTimer); showNoteDialog('edit', note.pid, note.name); });
		div.addEventListener('dragstart', (e) => { draggingNotePid = note.pid; draggingItemId = null; clearTimeout(clickTimer); suppressClickUntil = Date.now() + 300; div.classList.add('dragging'); e.dataTransfer.effectAllowed = 'move'; try { e.dataTransfer.setData('text/plain', note.pid); } catch (_) {} });
		div.addEventListener('dragend', () => { div.classList.remove('dragging'); draggingNotePid = null; suppressClickUntil = Date.now() + 300; if (shadowRoot) shadowRoot.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over')); });
		return div;
	}

	function openPanel() { if (!panelHost) createPanel(); if (panelVisible) return; panelVisible = true; renderRepoList(); shadowRoot.querySelector('#repo-panel').classList.add('open'); }
	function closePanel() { if (!panelVisible) return; panelVisible = false; if (shadowRoot) shadowRoot.querySelector('#repo-panel').classList.remove('open'); }
	function togglePanel() { panelVisible ? closePanel() : openPanel(); }

	/* ==================== 按钮挂载与 IDE 大按钮 ==================== */
	function ensureBtnGroup() {
		if (document.getElementById('luogu-repo-trigger')) return;
		const btnGroup = document.createElement('div'); btnGroup.id = 'luogu-repo-buttons';
		btnGroup.style.cssText = `position:fixed;right:16px;top:30%;display:flex;flex-direction:column;gap:10px;z-index:${Z_BTN};`;
		const repoBtn = document.createElement('button'); repoBtn.id = 'luogu-repo-trigger'; repoBtn.title = '代码仓库 / 代码笔记';
		repoBtn.innerHTML = `<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V9z"></path><path d="M3 15a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3v-3z"></path></svg>`;
		applyFloatingStyle(repoBtn); repoBtn.addEventListener('click', togglePanel);
		btnGroup.appendChild(repoBtn); document.body.appendChild(btnGroup);
	}

	function applyFloatingStyle(btn) {
		btn.dataset.inToolbar = 'false';
		btn.style.cssText = `width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:#313244;color:#cdd6f4;border:none;border-radius:10px;cursor:pointer;box-shadow:0 4px 12px rgba(0,0,0,.35);transition:background .15s,transform .15s;`;
		const svg = btn.querySelector('svg'); if (svg) { svg.setAttribute('width', '22'); svg.setAttribute('height', '22'); }
		btn.onmouseenter = () => { if (btn.dataset.inToolbar === 'true') return; btn.style.background = '#45475a'; btn.style.transform = 'scale(1.05)'; };
		btn.onmouseleave = () => { if (btn.dataset.inToolbar === 'true') return; btn.style.background = '#313244'; btn.style.transform = ''; };
	}

	function mountIdeButtons() {
		const isIde = location.hash.includes('ide') || document.querySelector('.monaco-editor, .CodeMirror');
		const repoBtnGroup = document.getElementById('luogu-repo-buttons');
		const topContainer = document.getElementById('luogu-ide-tools-container');
		const verticalTools = document.getElementById('luogu-ide-vertical-tools');

		if (!isIde) {
			// 非 IDE 模式:清理 IDE 元素,恢复原生浮动按钮
			if (topContainer) topContainer.remove();
			if (verticalTools) verticalTools.remove();
			if (repoBtnGroup) repoBtnGroup.style.display = 'flex';
			return;
		}

		// IDE 模式
		if (repoBtnGroup) repoBtnGroup.style.display = 'none'; // 隐藏原来的单个悬浮按钮
		if (topContainer) topContainer.remove(); // 清理旧的顶栏容器

		let container = verticalTools;
		if (!container) {
			container = document.createElement('div');
			container.id = 'luogu-ide-vertical-tools';
			document.body.appendChild(container);
		}

		// 初始化面板结构
		if (!container.querySelector('.luogu-tools-header')) {
			container.innerHTML = `
				<div class="luogu-tools-header" id="luogu-tools-toggle">
					<span class="arrow">▼</span> <span class="title">快捷工具</span>
				</div>
				<div class="luogu-tools-body" id="luogu-tools-body"></div>
			`;
			// 读取记忆状态
			const isCollapsed = localStorage.getItem('luogu_ide_tools_collapsed') === 'true';
			if (isCollapsed) container.classList.add('collapsed');

			container.querySelector('#luogu-tools-toggle').addEventListener('click', () => {
				const collapsed = container.classList.toggle('collapsed');
				localStorage.setItem('luogu_ide_tools_collapsed', collapsed);
			});
		}
		const body = container.querySelector('#luogu-tools-body');

		// 1. 打开侧边栏
		if (!document.getElementById('luogu-btn-sidebar-ide')) {
			const btnSidebar = document.createElement('button');
			btnSidebar.id = 'luogu-btn-sidebar-ide';
			btnSidebar.className = 'luogu-tool-btn';
			btnSidebar.innerHTML = `${ICON_REPO}<span>打开仓库</span>`;
			btnSidebar.onclick = togglePanel;
			body.appendChild(btnSidebar);
		}

		// 2. 收录代码
		if (!document.getElementById('luogu-btn-collect')) {
			const btnCollect = document.createElement('button');
			btnCollect.id = 'luogu-btn-collect';
			btnCollect.className = 'luogu-tool-btn';
			btnCollect.textContent = '收录当前代码';
			btnCollect.onclick = () => {
				const code = getEditorCode(); const name = getProblemName();
				if (!code || !code.trim()) { toast('当前编辑器为空,无法收录', 'error'); return; }
				const repo = loadRepo(); repo.push({ id: genId(), name, code, time: Date.now() }); saveRepo(repo);
				if (panelVisible && currentView === 'repo') renderRepoList(); toast('已收录:' + name);
			};
			body.appendChild(btnCollect);
		}

		// 3. 创建新代码
		if (!document.getElementById('luogu-btn-create-code')) {
			const btnCreateCode = document.createElement('button');
			btnCreateCode.id = 'luogu-btn-create-code';
			btnCreateCode.className = 'luogu-tool-btn';
			btnCreateCode.innerHTML = `<span>+创建新代码</span>`;
			btnCreateCode.onclick = () => showItemDialog(null, 'new');
			body.appendChild(btnCreateCode);
		}

		// 4. 当前题目笔记
		if (!document.getElementById('luogu-btn-note')) {
			const btnNote = document.createElement('button');
			btnNote.id = 'luogu-btn-note';
			btnNote.className = 'luogu-tool-btn';
			btnNote.innerHTML = `${ICON_NOTE_LG}<span>当前题目笔记</span>`;
			btnNote.onclick = () => showNoteDialog('view');
			body.appendChild(btnNote);
		}

		// 5. 创建新笔记
		if (!document.getElementById('luogu-btn-new-note')) {
			const btnNew = document.createElement('button');
			btnNew.id = 'luogu-btn-new-note';
			btnNew.className = 'luogu-tool-btn';
			btnNew.innerHTML = `${ICON_PLUS_LG}<span>查看/创建本题笔记</span>`;
			btnNew.onclick = () => showNoteDialog('edit');
			body.appendChild(btnNew);
		}
	}

	/* ==================== 生命周期 ==================== */
	function refreshUI() {
		ensureBtnGroup();
		mountIdeButtons();
	}

	if (!window.marked || !window.renderMathInElement) { loadDependencies(); } else { libsLoaded = true; }

	setInterval(refreshUI, 1000);

	let moTimer = null;
	new MutationObserver(() => {
		if (moTimer) return;
		moTimer = setTimeout(() => { moTimer = null; refreshUI(); }, 300);
	}).observe(document.body, { childList: true, subtree: true });

	setTimeout(refreshUI, 300);
	refreshUI();

})();

使用deepseek辅助编写,作者并不保证贡献大于AI。

原文