版本比较
如何更轻松的使用emoji
正文
增加 463 行删除 262 行
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186185 行未改动全部展开3723733743753763773783799 行未改动3893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304316 行未改动43843944044144244344444541 行未改动48748848949049149249349449549649712 行未改动51051151251351451551651751851952052152252352452552630 行未改动55755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160247 行未改动65065165265365465565665765865966081 行未改动7427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797802 行未改动78378478578678778878979079179279379479579679779879980080180280380480580680780880981081181221 行未改动83483583683783883984084114 行未改动85685785885986086186286386415 行未改动# 给洛谷编辑器装一个 emoji 面板## 前言洛谷的 Markdown 一直不能正常显示 emoji。之前在学术版看到 [Kyousuk](https://www.luogu.com.cn/user/1073459) 大佬的[《如何在洛谷讨论区发送 emoji 表情》](https://www.luogu.com.cn/article/77npr5w9),才知道可以用 HTML 实体语法绕过去:想发 🤫,只要在正文里写 `🤫`,浏览器渲染时就会把它解码成表情。但手动查 Unicode 再敲实体实在太麻烦了——每次都要开一个 emoji 编码表对着抄。所以我写了一个油猴(Tampermonkey)脚本:在洛谷的文章编辑页上加一个表情按钮,点开是一个支持中文/拼音检索的表情面板,选中后自动把 `😀` 这样的实体插到光标位置。交互参考了微软拼音输入法的表情面板:网格布局、方向键移动、回车确认、Esc 关闭。这篇文章记录整个开发过程,重点不是"我做了一个多厉害的东西",而是**我怎么在看不到源码的情况下,一步步摸清洛谷编辑器的内部结构**——毕竟洛谷前端不开源,编辑器又刚从 CodeMirror 5 换成了 CodeMirror 6,网上几乎找不到现成资料。(本文的写作结构参考了[《预测你的等级分曲线!》](https://www.luogu.com.cn/article/438gx0rt)这类工程分享文的组织方式,在此一并致谢。)## 效果展示功能一览:- **入口按钮**:有 `@` 按钮的页面直接克隆它插在右侧(样式与原生一致);没有工具栏的页面(比如现在的 `/discuss/new`)在编辑器右上角放一个低调的小按钮;- **面板**:8 个分类、460+ 个表情,底部预览条显示表情、名字和将插入的实体;- **检索**:支持中文(`笑哭`)、全拼(`xiaoku`)、拼音首字母(`xk`)三种方式;- **键盘操作**:方向键移动、回车插入、Esc 关闭,全程不需要碰鼠标;- **焦点保持**:打开面板、插入表情的过程中,编辑器光标位置不会丢,可以连续插入;- **插入语法可切换**:面板底部可以在「实体 `😂`」和「字符 😂」之间切换,应对不同渲染器。## 原理:为什么是 `&#x` 实体洛谷会把正文里直接输入的 emoji 字符处理成乱码(具体现象见 Kyousuk 的[文章](https://www.luogu.com.cn/article/77npr5w9)),但 HTML 实体 `😂` 是纯 ASCII 文本,存储和传输都不会出问题,浏览器渲染时再解码成表情。所以脚本的插入策略默认走实体:```jsfunction toEntities(ch) {let out = '';for (const cp of ch) out += '&#x' + cp.codePointAt(0).toString(16).toUpperCase() + ';';return out;}```注意要用 `codePointAt` 而不是 `charCodeAt`——emoji 大多在 U+1F300 以上,超过 BMP,`charCodeAt` 会把它们拆成两个代理对,拼出来的实体就是坏的。多码位表情(比如 `🧑🚀` 是三个码位用零宽连接符拼起来的)要逐码位生成 `🧑‍🚀`。## 设计与实现### 按钮注入:别自己画,去克隆要让自己加的按钮看起来像洛谷自带的,最省事也最稳的办法不是模仿 CSS,而是**直接克隆现成按钮的 DOM**:```jsbtn = at.cloneNode(true); // 克隆「@」按钮 → 类名/尺寸/圆角/间距/圆角/间距全部继承btn.innerHTML = SMILE_SVG; // 只把内容换成描边风格的笑脸图标at.parentNode.insertBefore(btn, at.nextSibling);````cloneNode` 不会复制事件监听器,所以不用担心点到克隆按钮触发洛谷的 @ 提及弹窗。### 焦点保持:一个 `preventDefault` 的事表情面板要在「点击按钮」和「点击表情格子」时都**不抢走编辑器的焦点**,否则每选一次表情,光标就丢了。诀窍是在按钮和格子的 `mousedown` 上 `preventDefault()`——焦点转移发生在 mousedown 默认行为里,阻止它之后,点击仍会触发 `click` 事件,但焦点留在原地。这样面板全程记得光标位置,插入完可以直接继续打字。### 拼音检索:全拼和首字母都要能搜每个表情存三项:字符、中文名、空格分隔的拼音串。检索时同时匹配四种情况:```jsALL.filter(it =>it.name.includes(q) || // 中文:笑哭it.full.includes(q) || // 全拼:xiaokuit.abbr.startsWith(q) || // 首字母:xkit.py.split(' ').some(s => s.startsWith(q))) // 单音节:ku```首字母缩写(`xk`)是在脚本加载时从拼音串自动算出来的,不用手写第二份数据。### 静默约束脚本 `@match` 的是整个 `www.luogu.com.cn/*`,但只在**发布/编辑文章的路径**(`/discuss/new*`、`/discuss/<id>/edit*`、`/article/*`、`/team/*`)且页面上确实存在编辑器时才注入按钮。题目详情页、讨论浏览页等一律不出现任何 UI。这一点很重要:洛谷的题目提交框和文章编辑器用的是同一套 CodeMirror,如果不加路径白名单,做题页面会莫名其妙多出一个笑脸按钮。## 踩坑实录(本文重点)这部分是我想详写的。三个大坑,每一个都让脚本"完全没反应",而且每个的排查方式都不太一样。### 坑一:编辑页根本不在 `/article` 下第一版我按 `/article/new` 写了路径白名单,结果在任何编辑页都看不到按钮。第一反应是代码有 bug,翻了两遍都没找到问题——后来才想起来洛谷把文章发布页迁到了 `/discuss/new?forum=xxx`,团队文章也一样。教训:**写 `@match` 之前先在目标页面上看一眼地址栏**,不要凭旧印象写。### 坑二:洛谷编辑器是 CodeMirror 6,不是 5这是最大的一个坑。我默认洛谷用的还是 CodeMirror 5,所以插入代码写的是:```jsconst cm = document.querySelector('.CodeMirror').CodeMirror; // CM5 把实例挂在 DOM 上cm.replaceSelection(text);```结果页面上既没有 `.CodeMirror` 类,也没有 `textarea`(CM6 直接用一个 `contenteditable` 的 div),这段代码查无此人,静默失败。CodeMirror 5 和 6 是两套几乎不兼容的 API:CM5 把实例挂在 DOM 元素的 `.CodeMirror` 属性上,有 `replaceSelection`;CM6 是全新架构,**没有公开的实例入口**,官方推荐的用法是你自己持有 `EditorView` 引用——对一个只能往别人页面里注入代码的油猴脚本来说,这等于无解。摸索出来的方案是三级降级:```js// ① 从 DOM 反查 CM6 的 EditorView:// CM6 会在内部 DOM 节点上挂 cmView(ContentView),顺着它摸到 viewfunction cm6View(el) {let n = el, guard = 0;while (n && guard++ < 40) {if (n.cmView && n.cmView.view && n.cmView.view.dispatch) return n.cmView.view;n = n.parentElement;}return null;}// 拿到 view 之后用官方 dispatch 接口插入,光标位置精确:view.dispatch({changes: { from: sel.from, to: sel.to, insert: text },selection: { anchor: sel.from + text.length },scrollIntoView: true});// ② 拿不到 view 就用 execCommand,CM6 会捕获 beforeinput 事件同步状态:document.execCommand('insertText', false, text);// ③ 都不行再手动操作 Selection/Range(一般编辑器的兜底)。````cmView` 这个属性在 CodeMirror 6 的[官方文档](https://codemirror.net/docs/ref/)里没有作为公开 API 记载,是读它的源码(`view/index.ts` 里 `syncDecorations` 一带会把 `ContentView` 挂到节点上)确认的,所以保留了 ②③ 两级保险,防止哪次更新把这个内部属性去掉。### 坑三:`.cm-scroller` 被我自己的启发式判成了"工具栏"为了决定按钮插哪儿,我写了一个启发式:从编辑区往上找"长得像工具栏"的节点(类名含 toolbar,或内部按钮数 ≥ 3)。结果它把 `.cm-scroller` 认成了工具栏——因为 CM6 的滚动容器把整个文档的行结构都装在里面,按钮计数自然超标。修法是给启发式加一条:**类名以 `cm-` 开头的节点一律跳过**,它们全是 CodeMirror 的内部结构,不可能是给用户看的工具栏。写启发式时"看起来能跑"和"真的对"之间的差距,比想象中大得多。### 排查方法论:先给脚本装"行车记录仪"上面三个坑能比较快地定位,靠的不是反复读代码,而是脚本里内置的一个诊断函数。在浏览器控制台执行 `LGE_DIAG()`,会输出当前 URL、路径是否在白名单、页面用的是 CM5 还是 CM6、能不能反查到 EditorView、探测到的编辑区/工具栏/按钮的类名,以及页面上前 30 个按钮的清单。比如坑二就是靠这一行输出定位的:```editable: "DIV.cm-content cm-lineWrapping" ← CodeMirror 6 的编辑区hasCodeMirror: false ← 没有 CM5 的类textareas: 0 ← 也没有 textarea```看到这个输出,编辑器是什么框架、卡在哪一步一目了然。给油猴脚本内置一个这样的诊断入口,让"页面和我之间"有一条明确的反馈通道,比每次出问题就盲改代码要高效得多——这一点在后来调试其他 OJ 爬虫脚本时也一再被验证。## 怎么测试:jsdom 冒烟油猴脚本没法直接跑单测,我的做法是把脚本丢进 Node 的 jsdom 里真实执行:构造一个假的编辑器 DOM(连 CM6 的 `.cm-editor/.cm-scroller/.cm-content` 三层结构和 `cmView` 挂载都模拟出来),再模拟点击按钮、输入搜索词、按下回车,最后断言 `view.dispatch` 收到的文本是不是 `😂`:```jscontent.cmView = { view }; // 模拟 CM6 的内部挂载myBtn.click();inp.value = 'xk';inp.dispatchEvent(new Event('input', { bubbles: true }));inp.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));assert(got === '😂');```这套跑起来之后,每次改探测逻辑都能立刻知道有没有把旧场景改坏(比如给团队页加的兜底,会不会误伤题目提交框的静默)。顺带一提,jsdom 有两个坑:它没有布局引擎,`offsetParent` 永远是 `null`;也不实现 `scrollIntoView`。脚本里对这两处都做了存在性检查,正好也提升了健壮性。## 安装与使用1. 浏览器装好 Tampermonkey;2. 新建脚本,把文末附录的完整源码粘进去保存(或直接导入 `.user.js` 文件);3. 打开洛谷的「发表文章」或编辑文章页面;4. 有 `@` 按钮的页面,笑脸按钮就在 `@` 右边;现在的 `/discuss/new` 页面则在编辑器右上角;5. 点开面板,搜索或浏览,回车插入。若发现插入实体后正文里不渲染,点面板底部的「实体」切换成「字符」模式再试。## 附录:完整源码> 约 660 行,含 460+ 条表情数据表。核心逻辑上文已拆解,数据表部分就是纯粹的 `[字符, 中文名, 拼音]` 三元组数组。:::success[点击展开完整源码(v1.2.0,约 660 行)]```javascript// ==UserScript==// @name 洛谷文章 emoji 表情插入助手// @namespace https://www.luogu.com.cn/// @version 1.2.0// @description 在洛谷文章编辑器「@」按钮右侧添加原生风格表情按钮:分类浏览 + 中文/拼音检索 + 键盘导航,按 luogu@ 方式在光标处插入 &#x....; 实体语法。仅在文章编辑页出现,其他页面静默。// @author WorkBuddy// @match https://www.luogu.com.cn/*// @run-at document-idle185 行未改动全部展开/* ====================== 编辑器探测(多策略,兼容各种模板) ====================== */let lastEditable = null; // 最近聚焦的可编辑目标let ED = null; // 探测结果 {editable, root, toolbar, at}function editableEl() {// CodeMirror 6(洛谷现用):.cm-content[contenteditable]const cm6 = document.querySelector('.cm-content[contenteditable="true"], .cm-content');9 行未改动max = max || 10;while (n && n !== document.body && i++ < max) { if (pred(n)) return n; n = n.parentElement; }return null;}function looksLikeToolbar(node) {if (!node || !node.querySelectorAll) return false;const cls = typeof node.className === 'string' ? node.className : '';if (/cm-|cmEditor|ͼ/.test(cls)) return false; // CodeMirror 6 内部结构不算工具栏if (/toolbar|tool-bar|ed-header|ed-groups|editor-bar|ed-wrapper/i.test(cls)) return true;return node.querySelectorAll('button, [class*="ed-btn"], [role="button"]').length >= 3;}function detectEditor() {const editable = editableEl();if (!editable) return null;const cmRoot = editable.closest ? (editable.closest('.cm-editor') || editable.closest('.CodeMirror')) : null;const root = cmRoot || upTo(editable, looksLikeToolbar) || editable.parentElement;// 工具栏:只在明确的工具栏容器(而非 body 之类的大容器)里认,避免误挂const searchBase = cmRoot ? (cmRoot.parentElement || root) : root;let toolbar = null;if (searchBase && searchBase.querySelectorAll) {const hit = [].slice.call(searchBase.querySelectorAll('*')).filter(n => {const c = typeof n.className === 'string' ? n.className : '';return /toolbar|tool-bar|ed-header|ed-groups|editor-bar/i.test(c) && n.tagName !== 'BODY';});toolbar = hit[0] || null;}const scope = searchBase || root || document;let at = null;const cands = scope.querySelectorAll('button, [class*="ed-btn"], a, span[role="button"]');for (const b of cands) {const txt = (b.textContent || '').trim();const label = (b.getAttribute && (b.getAttribute('title') || '') + ' ' + (b.getAttribute('aria-label') || '')) || '';if (txt === '@' || (txt.length <= 2 && txt.indexOf('@') >= 0) || /@|提及|mention/i.test(label)) {if (b.children.length <= 2) { at = b; break; }}}const host = toolbar || (cmRoot && cmRoot.parentElement) || root || editable.parentElement;return { editable, root, toolbar, at, host, hasToolbar: !!toolbar };}// CodeMirror 6:从 DOM 反查 EditorView(node.cmView → ContentView → .view)function cm6View(el) {let n = el;6 行未改动return null;}function editorTarget() {if (lastEditable && document.contains(lastEditable)) return lastEditable;if (ED && ED.editable && document.contains(ED.editable)) return ED.editable;const d = detectEditor();return d ? d.editable : null;41 行未改动return true;}// ② execCommand:CodeMirror 6 会捕获 beforeinput 并同步状态target.focus();let ok = false;try { ok = document.execCommand('insertText', false, text); } catch (e) {}if (ok) { target.dispatchEvent(new InputEvent('input', { bubbles: true })); return true; }// ③ 手动 Range 兜底let sel = window.getSelection();if (!sel.rangeCount || !target.contains(sel.anchorNode)) {sel = null;12 行未改动range.deleteContents();range.insertNode(document.createTextNode(text));range.collapse(false);sel.removeAllRanges(); sel.addRange(range);target.dispatchEvent(new InputEvent('input', { bubbles: true }));target.focus();return true;}} catch (err) { /* 插入失败保持静默 */ }return false;}let savedRange = null;/* ====================== 样式(仅作用于自有节点,前缀 lge-) ====================== */const CSS = `.lge-panel{position:fixed;z-index:2147483000;width:352px;background:#fff;border:1px solid #d0d7de;border-radius:8px;box-shadow:0 6px 24px rgba(0,0,0,.16);font:13px/1.4 -apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;30 行未改动/* ====================== 面板 ====================== */const SMILE_SVG = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>';let btn = null, panel = null, searchInput = null, bodyEl = null, footEl = null;let cells = [], selIdx = -1, curTab = -1 /* -1=全部 */, open = false;function attachButton(d) {injectStyle();if (d.at) { // 有「@」按钮:克隆它 → 样式与原生完全一致btn = d.at.cloneNode(true);btn.removeAttribute('id');btn.removeAttribute('aria-label');btn.removeAttribute('title');btn.innerHTML = SMILE_SVG;d.at.parentNode.insertBefore(btn, d.at.nextSibling);} else if (d.toolbar) { // 找不到 @ 按钮:自建一个尽量低调的按钮放到工具栏末尾btn = document.createElement('button');btn.type = 'button';btn.innerHTML = SMILE_SVG;btn.style.cssText = 'background:none;border:none;cursor:pointer;padding:0 4px;margin:0 2px;line-height:1;color:inherit;opacity:.75;vertical-align:middle';d.toolbar.appendChild(btn);} else if (d.host) {// 找不到 @ 按钮(CodeMirror 6 页面常见):在编辑器容器右上角放一个低调按钮btn = document.createElement('button');btn.type = 'button';btn.innerHTML = SMILE_SVG;btn.style.cssText = 'position:absolute;z-index:9999;background:#fff;border:1px solid #d0d7de;' +'border-radius:6px;cursor:pointer;padding:3px 5px;line-height:1;color:#555;box-shadow:0 1px 4px rgba(0,0,0,.08)';const host = d.host;if (getComputedStyle(host).position === 'static') host.style.position = 'relative';btn.style.right = '10px';btn.style.top = '8px';host.appendChild(btn);} else {return false;}btn.title = '插入 emoji 表情';btn.setAttribute('data-lge-btn', '1');btn.addEventListener('mousedown', e => e.preventDefault()); // 不抢编辑器焦点,保留光标btn.addEventListener('click', e => { e.preventDefault(); open ? closePanel(true) : openPanel(); });return true;}function buildPanel() {panel = document.createElement('div');47 行未改动panel.addEventListener('mouseover', e => {const cell = e.target.closest('.lge-cell');if (cell) showFoot(cell.dataset.ch, cell.dataset.name);});panel.addEventListener('focusout', () => {setTimeout(() => { if (open && !panel.contains(document.activeElement)) closePanel(false); }, 0);});}function render() {const q = searchInput.value;81 行未改动break;}}function pick(ch, code) {if (insertText(code, btn)) closePanel(true);else closePanel(false);}function openPanel() {if (!panel) buildPanel();panel.style.display = 'flex';render();const r = btn.getBoundingClientRect();const W = 352, H = Math.min(360, panel.offsetHeight || 360);let left = Math.min(r.left, window.innerWidth - W - 8);left = Math.max(8, left);let top = r.bottom + 6;if (top + H > window.innerHeight - 8) top = Math.max(8, r.top - H - 6);panel.style.left = left + 'px';panel.style.top = top + 'px';open = true;setTimeout(() => searchInput.focus(), 0);setTimeout(() => document.addEventListener('mousedown', onDocDown, true), 0);}function onDocDown(e) {if (!open) return;if (panel.contains(e.target) || btn.contains(e.target)) return;closePanel(false);}function closePanel(refocus) {if (!open) return;open = false;panel.style.display = 'none';document.removeEventListener('mousedown', onDocDown, true);if (refocus) refocusEditor();}function refocusEditor() {const t = editorTarget();2 行未改动else if (t.focus) t.focus();}/* ====================== 生命周期:仅在编辑页注入,其他时候静默 ====================== */// 发布/编辑页路径:现为 /discuss/new*、/discuss/<id>/edit*,另有 /article/*、/team/* 等变体function allowedPage() {const p = location.pathname;return /^\/discuss\/new(\/|$)/.test(p) ||/^\/discuss\/[^\/]+\/(edit|new)(\/|$)/.test(p) ||/\/article(\/|$)/.test(p) ||/^\/team\//.test(p);}let pending = false;function ensure() {if (pending) return;pending = true;setTimeout(() => {pending = false;if (btn && document.contains(btn)) return; // 已注入且仍在文档中if (btn) { closePanel(false); btn = null; } // 工具栏被销毁 → 清理if (!allowedPage()) return;const d = detectEditor();ED = d;if (!d) return; // 无编辑器 → 完全静默attachButton(d);}, 200);}/* ====================== 诊断:控制台执行 LGE_DIAG() 可查看详情 ====================== */21 行未改动host: d.host ? (d.host.tagName + '.' + (typeof d.host.className === 'string' ? d.host.className : '')).slice(0, 60) : null,atBtn: d.at ? (d.at.tagName + '.' + (typeof d.at.className === 'string' ? d.at.className : '')).slice(0, 60) : null} : null,buttons: btns,insertMode: (function () { try { return localStorage.getItem('lge-mode') || 'entity'; } catch (e) { return 'entity'; } })()};};} catch (e) {}14 行未改动if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);else start();})();```:::## AI 使用说明15 行未改动1234567891011185 行未改动全部展开1971981992002012022032042052069 行未改动2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343356 行未改动34234334434534634734834935035141 行未改动39339439539639739839940040140240340412 行未改动41741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645730 行未改动48848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967047 行未改动71871972072172272372472572672781 行未改动8098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329332 行未改动93693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498521 行未改动100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104314 行未改动1058105910601061106210631064106515 行未改动:::success[点击展开完整源码(v1.4.1,约 1060 行)]```javascript// ==UserScript==// @name 洛谷文章 emoji 表情插入助手// @namespace https://www.luogu.com.cn/// @version 1.4.1// @description 在洛谷文章编辑器「@」按钮右侧添加原生风格表情按钮:分类浏览 + 中文/拼音检索 + 键盘导航,按 luogu@ 方式在光标处插入 &#x....; 实体语法。仅在文章编辑页出现,其他页面静默。// @author WorkBuddy// @match https://www.luogu.com.cn/*// @run-at document-idle185 行未改动全部展开/* ====================== 编辑器探测(多策略,兼容各种模板) ====================== */let lastEditable = null; // 最近聚焦的可编辑目标let ED = null; // 探测结果 {editable, root, toolbar, at}let activeD = null; // 当前面板对应的编辑器(由被点击的按钮决定)let BTNS = []; // 一页多个编辑框 → 多个按钮 [{btn, d}]function editableEl() {// CodeMirror 6(洛谷现用):.cm-content[contenteditable]const cm6 = document.querySelector('.cm-content[contenteditable="true"], .cm-content');9 行未改动max = max || 10;while (n && n !== document.body && i++ < max) { if (pred(n)) return n; n = n.parentElement; }return null;}// 两个节点的 DOM 距离(到共同祖先的层数之和),用来挑“离编辑器最近”的按钮/工具栏function domDistance(a, b) {if (!a || !b) return 999;if (a === b) return 0;const chain = new Map();let n = a, i = 0;while (n) { chain.set(n, i++); n = n.parentElement; }n = b; let j = 0;while (n) { if (chain.has(n)) return chain.get(n) + j; n = n.parentElement; j++; }return 999;}function isCmInternals(cls) { return /cm-|cmEditor|ͼ/.test(cls || ''); }// 候选可点击元素每轮只收集一次(页面元素很多,别每个编辑框都查一遍)function collectClickables() {return [].slice.call(document.querySelectorAll('button, a, span, i, div, [role="button"], [class*="btn"]'));}// 几何检查:候选必须在编辑框附近(上方 240px / 下方 120px / 重叠),避免把远处的一行认成工具栏function geomOK(el, ed) {try {const a = el.getBoundingClientRect(), b = ed.getBoundingClientRect();if (!a.height || !b.height) return true; // 无布局信息时不限制if (a.bottom <= b.top + 8) return (b.top - a.bottom) < 240;if (a.top >= b.bottom - 8) return (a.top - b.bottom) < 120;return true;} catch (e) { return true; }}// 「@」按钮:全文档搜索(不限编辑器子树),取离目标编辑器最近的一个function findAtButton(ed, cands) {cands = cands || collectClickables();let best = null, bestD = Infinity;for (const b of cands) {if (b.hasAttribute && b.hasAttribute('data-lge-btn')) continue;if (b.closest && b.closest('.lge-panel, .lge-bar')) continue;const txt = (b.textContent || '').trim();if (txt.length > 4) continue;const label = ((b.getAttribute && b.getAttribute('title')) || '') + ' ' + ((b.getAttribute && b.getAttribute('aria-label')) || '');const isAt = txt === '@' || (txt.length <= 2 && txt.indexOf('@') >= 0) || /@|提及|mention/i.test(label);if (!isAt) continue;if (b.children && b.children.length > 3) continue;// 排除“容器”:子元素里已经有文字的(如整页 div 的 textContent 也含 @),只认叶子节点if (txt !== '@' && b.children && b.children.length) {let childHasText = false;for (const c of b.children) { if ((c.textContent || '').trim()) { childHasText = true; break; } }if (childHasText) continue;}if (!geomOK(b, ed)) continue;const d = domDistance(b, ed);if (d < bestD) { bestD = d; best = b; }}return best;}// 在 root 子树里找一行“工具栏”:类名像工具栏,或含有 ≥2 个小图标/按钮function scanForRow(root, exclude) {const nodes = [].slice.call(root.querySelectorAll('div, ul, nav, header, span'));let best = null, bestD = Infinity;for (const el of nodes) {const c = typeof el.className === 'string' ? el.className : '';if (!c || isCmInternals(c)) continue;if (el.contains && el.contains(exclude)) continue;if (el.querySelector && el.querySelector('.lge-bar, [data-lge-btn]')) continue;const btns = el.querySelectorAll('button, [role="button"], svg').length;const icons = el.querySelectorAll('[class*="icon"], [class*="btn"], [class*="item"]').length;const isBar = /toolbar|tool-bar|ed-header|ed-groups|editor-bar|md-tools|md-editor|markdown/i.test(c);if (!isBar && btns < 2 && icons < 2) continue;if (btns + icons > 40) continue; // 太大 → 不是工具栏if (!geomOK(el, exclude)) continue; // 离编辑框太远 → 不是它的工具栏const d = domDistance(el, exclude);if (d < bestD) { bestD = d; best = el; }}return best;}// 工具栏:优先 @ 所在行;否则从编辑器往上逐层找最近的一行function findToolbar(ed, at) {if (at && at.parentElement && at.parentElement !== document.body && at.parentElement !== document.documentElement) return at.parentElement;let n = ed, i = 0;while (n && n !== document.body && i++ < 8) {const hit = scanForRow(n, ed);if (hit) return hit;n = n.parentElement;}return null;}function describeEditor(ed, cands) {const cmRoot = ed.closest ? (ed.closest('.cm-editor') || ed.closest('.CodeMirror')) : null;const at = findAtButton(ed, cands);const toolbar = findToolbar(ed, at);const host = (cmRoot && cmRoot.parentElement) || ed.parentElement;return { editable: ed, cmRoot, root: cmRoot || host, toolbar, at, host };}// 一页可能有多个编辑框(新建题目页就有好几个),全都识别出来function detectEditors() {const list = [];const add = (el) => { if (el && list.indexOf(el) < 0 && document.contains(el)) list.push(el); };[].slice.call(document.querySelectorAll('.cm-content[contenteditable="true"], .cm-content')).forEach(add);[].slice.call(document.querySelectorAll('.CodeMirror')).forEach(add);[].slice.call(document.querySelectorAll('textarea')).forEach(t => {if (t.readOnly || t.disabled) return;if (t.closest && t.closest('.CodeMirror, .cm-editor')) return; // CM 的隐藏 textarea 不算add(t);});if (!list.length) {const ce = document.querySelector('[contenteditable="true"], [contenteditable=""]');if (ce) add(ce);}const cands = collectClickables();return list.map(ed => describeEditor(ed, cands));}function detectEditor() {const ds = detectEditors();return ds.length ? ds[0] : null;}// CodeMirror 6:从 DOM 反查 EditorView(node.cmView → ContentView → .view)function cm6View(el) {let n = el;6 行未改动return null;}function editorTarget() {// 面板是从哪个按钮打开的,就插入到那个按钮对应的编辑框(一页多编辑框时尤其重要)if (activeD && activeD.editable && document.contains(activeD.editable)) return activeD.editable;if (lastEditable && document.contains(lastEditable)) return lastEditable;if (ED && ED.editable && document.contains(ED.editable)) return ED.editable;const d = detectEditor();return d ? d.editable : null;41 行未改动return true;}// ② execCommand:CodeMirror 6 会捕获 beforeinput 并同步状态target.focus();restoreCaret(target);let ok = false;try { ok = document.execCommand('insertText', false, text); } catch (e) {}if (ok) { saveCaret(); target.dispatchEvent(new InputEvent('input', { bubbles: true })); return true; }// ③ 手动 Range 兜底let sel = window.getSelection();if (!sel.rangeCount || !target.contains(sel.anchorNode)) {sel = null;12 行未改动range.deleteContents();range.insertNode(document.createTextNode(text));range.collapse(false);sel.removeAllRanges(); sel.addRange(range);try { savedRange = range.cloneRange(); } catch (e) {}target.dispatchEvent(new InputEvent('input', { bubbles: true }));target.focus();return true;}} catch (err) { /* 插入失败保持静默 */ }return false;}let savedRange = null;// 面板打开时记住编辑器光标:之后焦点在搜索框里也能连续插入到同一位置function saveCaret() {const t = editorTarget();if (!t) return;try {if (t.tagName === 'TEXTAREA' || t.CodeMirror) return; // 这两类的选区自己会保留const sel = window.getSelection();if (sel && sel.rangeCount && t.contains(sel.anchorNode)) savedRange = sel.getRangeAt(0).cloneRange();} catch (e) {}}// 焦点被搜索框抢走时,把 contenteditable 的光标恢复回来function restoreCaret(target) {if (!savedRange || !target) return false;try {if (!target.contains(savedRange.startContainer)) return false;const sel = window.getSelection();if (sel.rangeCount && target.contains(sel.anchorNode) && !sel.isCollapsed) return false;sel.removeAllRanges();sel.addRange(savedRange);return true;} catch (e) { return false; }}/* ====================== 样式(仅作用于自有节点,前缀 lge-) ====================== */const CSS = `.lge-panel{position:fixed;z-index:2147483000;width:352px;background:#fff;border:1px solid #d0d7de;border-radius:8px;box-shadow:0 6px 24px rgba(0,0,0,.16);font:13px/1.4 -apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;30 行未改动/* ====================== 面板 ====================== */const SMILE_SVG = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>';let btn = null, activeBtn = null, panel = null, searchInput = null, bodyEl = null, footEl = null;let cells = [], selIdx = -1, curTab = -1 /* -1=全部 */, open = false;// 让注入的按钮始终与「@」等原生按钮同一行水平并排:// 优先克隆样本按钮(类名/尺寸/圆角/间距/字体全部继承),实在没有样本才手搓样式。function makeButton(sample) {let b;if (sample && sample.tagName === 'BUTTON') {b = sample.cloneNode(true);b.removeAttribute('id');b.removeAttribute('aria-label');b.removeAttribute('data-v-');b.innerHTML = SMILE_SVG;} else {b = document.createElement('button');b.type = 'button';b.innerHTML = SMILE_SVG;// 手搓兜底:视觉贴近洛谷工具栏图标按钮b.style.cssText = 'display:inline-flex;align-items:center;justify-content:center;' +'background:none;border:none;cursor:pointer;padding:4px;margin:0 2px;line-height:1;' +'font-size:14px;color:inherit;opacity:.8;border-radius:4px;vertical-align:middle';}// 强制水平排布:不换行、不被 flex 拉伸、与相邻按钮中线对齐const st = b.style;st.display = 'inline-flex';st.alignItems = 'center';st.justifyContent = 'center';st.verticalAlign = 'middle';st.flex = '0 0 auto';st.whiteSpace = 'nowrap';st.boxSizing = 'border-box';if (!st.marginLeft && !st.marginRight) st.margin = '0 2px';return b;}// 工具栏里用于克隆样式的样本按钮:优先「@」,其次图标型小按钮(避免克隆到「发表」这类大按钮)function sampleButton(scope) {if (!scope || !scope.querySelectorAll) return null;const all = [].slice.call(scope.querySelectorAll('button')).filter(b => !b.hasAttribute('data-lge-btn'));if (!all.length) return null;const score = (b) => {const txt = (b.textContent || '').trim();let s = 0;if (txt === '@') s += 100;if (b.querySelector('svg')) s += 30;if (txt.length <= 2) s += 20;if (/发表|发布|提交|保存|预览/.test(txt)) s -= 100;try { const w = b.getBoundingClientRect().width; if (w && w < 48) s += 15; if (w > 96) s -= 40; } catch (e) {}return s;};return all.sort((a, b) => score(b) - score(a))[0];}// 保证宿主行是水平排布(工具栏若是 flex 且不换行则无需处理)function ensureRow(row) {if (!row) return null;const cs = getComputedStyle(row);if (cs.display === 'flex' || cs.display === 'inline-flex') {if (cs.flexWrap === 'wrap') row.style.flexWrap = 'nowrap';row.style.alignItems = row.style.alignItems || 'center';}return row;}// 两个元素是否在同一行(用几何实测,最可靠)function sameLine(a, b) {if (!a.height || !b.height) return true; // 拿不到布局信息时不折腾return Math.abs(a.top - b.top) <= Math.max(4, Math.min(a.height, b.height) * 0.5);}// 候选“行”里其实装了多行(比如外层工具栏套了两条子行)→ 退回到参照按钮的直接父级function refineRow(row, ref) {if (!row || !ref || !ref.getBoundingClientRect) return row;const rr = ref.getBoundingClientRect();if (!rr.height) return row;const kids = [].slice.call(row.children);if (!kids.length || kids.length > 14) return ref.parentElement || row;for (const k of kids) {const kr = k.getBoundingClientRect();if (kr.height && Math.abs(kr.top - rr.top) > 6) return ref.parentElement || row;}return row;}// 插入后校正:必须和参照按钮(@)在同一行,否则逐级修布局function alignRow(b, ref) {if (!b || !ref) return;if (sameLine(b.getBoundingClientRect(), ref.getBoundingClientRect())) return;const row = b.parentElement;if (!row) return;const cs = getComputedStyle(row);if (cs.display === 'flex' || cs.display === 'inline-flex') {row.style.flexWrap = 'nowrap'; // ① 换行导致的 → 不换行row.style.alignItems = row.style.alignItems || 'center';} else if (cs.display === 'grid') {row.style.gridAutoFlow = 'column'; // ② grid 列数固定 → 加一列if (cs.gridTemplateColumns && cs.gridTemplateColumns !== 'none') {row.style.gridTemplateColumns = cs.gridTemplateColumns + ' auto';}} else if (/^(block|inline-block|inline|list-item)$/.test(cs.display) && row.children.length <= 14) {row.style.display = 'flex'; // ③ 块级容器 → 改成不换行的 flex 行row.style.flexWrap = 'nowrap';row.style.alignItems = 'center';}if (sameLine(b.getBoundingClientRect(), ref.getBoundingClientRect())) return;// ④ 参照按钮自己是块级 → 改成 inline-flex(尺寸不变,只是不再独占一行)const rs = getComputedStyle(ref);if (rs.display === 'block' || rs.display === 'list-item') {ref.style.display = 'inline-flex';ref.style.verticalAlign = 'middle';if (sameLine(b.getBoundingClientRect(), ref.getBoundingClientRect())) return;}// ⑤ 兜底:绝对定位钉在参照行的末尾(视觉上同一行、最右侧)try {const rr = ref.getBoundingClientRect(), hr = row.getBoundingClientRect();if (!rr.height || !hr.height) return;if (getComputedStyle(row).position === 'static') row.style.position = 'relative';b.style.position = 'absolute';b.style.margin = '0';b.style.zIndex = '9999';const h = b.getBoundingClientRect().height || 24;b.style.top = Math.round(rr.top - hr.top + (rr.height - h) / 2) + 'px';b.style.left = Math.round(rr.right - hr.left + 4) + 'px';b.dataset.lgeAbs = '1';} catch (e) {}}// @ 可能只是按钮里的一个 span/i → 归一到真正的外层按钮function normalizeAt(el) {if (!el) return el;if (el.tagName === 'BUTTON' || (el.getAttribute && el.getAttribute('role') === 'button')) return el;const up = el.closest ? el.closest('button, [role="button"], a') : null;return up || el;}function attachButton(d) {injectStyle();if (d.at) { // 有「@」按钮:克隆它,挂到 @ 所在那一行的末尾const at = normalizeAt(d.at);const row = refineRow(at.parentElement, at) || at.parentElement;btn = makeButton(at.tagName === 'BUTTON' ? at : sampleButton(row));ensureRow(row);row.appendChild(btn);alignRow(btn, at);} else if (d.toolbar) { // 有工具栏但没有 @:克隆行内的图标按钮,挂到同一行末尾const sample = sampleButton(d.toolbar);const row = refineRow(d.toolbar, sample) || d.toolbar;btn = makeButton(sample);ensureRow(row);row.appendChild(btn);alignRow(btn, sample || row.firstElementChild);} else if (d.host) {// 连工具栏都没有(新建题目页、部分 CM6 页面):在编辑框容器右上角放一条水平按钮条const host = d.host;if (getComputedStyle(host).position === 'static') host.style.position = 'relative';const bar = document.createElement('div');bar.className = 'lge-bar';bar.style.cssText = 'position:absolute;right:10px;top:8px;z-index:9999;display:inline-flex;' +'align-items:center;gap:2px;background:#fff;border:1px solid #d0d7de;border-radius:6px;' +'padding:2px 4px;box-shadow:0 1px 4px rgba(0,0,0,.08);line-height:1';btn = makeButton(null);btn.style.margin = '0';btn.style.opacity = '.85';bar.appendChild(btn);host.appendChild(bar);btn = bar.firstElementChild;bar.setAttribute('data-lge-bar', '1');} else {return null;}btn.title = '插入 emoji 表情(可连续插入,Esc 或点击空白处关闭)';btn.setAttribute('data-lge-btn', '1');btn._lgeD = d; // 记住这个按钮对应哪个编辑框btn.addEventListener('mousedown', e => e.preventDefault()); // 不抢编辑器焦点,保留光标btn.addEventListener('click', e => {e.preventDefault();activeD = d;if (open && activeBtn === btn) closePanel(true);else openPanel(btn, d);});return btn;}function buildPanel() {panel = document.createElement('div');47 行未改动panel.addEventListener('mouseover', e => {const cell = e.target.closest('.lge-cell');if (cell) showFoot(cell.dataset.ch, cell.dataset.name);});// 注意:不再监听 focusout 自动关闭 —— 插入后焦点在编辑器与搜索框之间来回,// 会误关面板。面板只由「点击外部空白」或 Esc 关闭。}function render() {const q = searchInput.value;81 行未改动break;}}// 插入后面板保持打开,方便连续点选多个表情function pick(ch, code) {const ok = insertText(code, btn);if (!panel) return;const foot = panel.querySelector('.lge-foot-name');if (ok) {flash(foot, '已插入 ' + ch + ',可继续选择');} else {flash(foot, '插入失败:请先点一下编辑区确定光标位置');}// 焦点还给搜索框,方向键/继续输入都可用;编辑器内的光标位置由插入逻辑保留if (open) setTimeout(() => { if (open && searchInput) searchInput.focus(); }, 0);}let flashTimer = null;function flash(el, text) {if (!el) return;const old = el.textContent;el.textContent = text;el.style.color = '#2d6ecf';clearTimeout(flashTimer);flashTimer = setTimeout(() => { el.textContent = old; el.style.color = ''; }, 1200);}/* ---------- 面板定位:按「@ 键所在工具栏/按钮行是否贴近页面底部」动态决定弹出方向 ---------- */const GAP = 6, EDGE = 8;let lastDir = 'down';// 定位锚点:优先按钮所在的整个工具栏行(这样判断“工具栏是否贴底”更准),退化为按钮自身function anchorRect() {const b = activeBtn || btn;let row = null;if (b) {const p = b.parentElement;if (p && p !== document.body) row = p;}// 若按钮确实挂在探测到的工具栏里,用整行工具栏做锚点(判断“是否贴底”更准)if (activeD && activeD.toolbar && b && activeD.toolbar.contains(b)) row = activeD.toolbar;const el = row || b;return el ? el.getBoundingClientRect() : null;}function positionPanel() {if (!panel || !btn || !open) return;const r = anchorRect();if (!r) return;const W = panel.offsetWidth || 352;const H = panel.offsetHeight || 360;const vw = document.documentElement.clientWidth || window.innerWidth;const vh = document.documentElement.clientHeight || window.innerHeight;// 方向判定:下方剩余空间够 → 向下;否则(工具栏贴底)向上;两边都不够 → 取空间大的一侧并夹在视口内const spaceBelow = vh - r.bottom - EDGE;const spaceAbove = r.top - EDGE;let dir = (spaceBelow >= H + GAP) ? 'down' : (spaceAbove >= H + GAP ? 'up': (spaceAbove >= spaceBelow ? 'up' : 'down'));let top;if (dir === 'up') top = r.top - H - GAP;else top = r.bottom + GAP;// 边界夹紧(防止上方/下方越界)if (top + H > vh - EDGE) top = Math.max(EDGE, vh - H - EDGE);if (top < EDGE) top = EDGE;let left = r.left;if (left + W > vw - EDGE) left = vw - W - EDGE;if (left < EDGE) left = EDGE;panel.style.left = Math.round(left) + 'px';panel.style.top = Math.round(top) + 'px';panel.dataset.lgeDir = dir; // 'down' | 'up',便于诊断lastDir = dir;}// 视口/尺寸变化时重算;用 rAF 节流let rafId = 0;function reposition() {if (!open || rafId) return;rafId = requestAnimationFrame(() => {rafId = 0;if (!open) return;const r = anchorRect();// 锚点被滚出视口 → 直接关闭,避免面板悬空if (r && (r.bottom < 0 || r.top > window.innerHeight)) { closePanel(false); return; }positionPanel();});}function openPanel(clickedBtn, d) {if (clickedBtn) { btn = clickedBtn; activeBtn = clickedBtn; }if (d) activeD = d;else if (btn && btn._lgeD) activeD = btn._lgeD;if (!panel) buildPanel();saveCaret(); // 记住编辑器当前光标,供后续连续插入panel.style.display = 'flex';render();open = true;positionPanel();// 同步注册监听(本函数由 click 触发,同一次点击的 mousedown 已结束,不会误关)document.addEventListener('mousedown', onDocDown, true);window.addEventListener('resize', reposition);window.addEventListener('scroll', reposition, true);setTimeout(() => searchInput.focus(), 0);}function onDocDown(e) {if (!open) return;// 点击面板内部、任一已注入的表情按钮都不关闭;只有点击面板之外的区域才关闭if (panel.contains(e.target)) return;for (const it of BTNS) if (it.btn.contains(e.target)) return;if (btn && btn.contains(e.target)) return;closePanel(false);}function closePanel(refocus) {if (!open) return;open = false;panel.style.display = 'none';document.removeEventListener('mousedown', onDocDown, true);window.removeEventListener('resize', reposition);window.removeEventListener('scroll', reposition, true);if (refocus) refocusEditor();}function refocusEditor() {const t = editorTarget();2 行未改动else if (t.focus) t.focus();}/* ====================== 生命周期:仅在编辑页注入,其他时候静默 ====================== */// 明确的“内容编辑类”路径:即使没找到工具栏,也允许自建按钮条function isEditPath(p) {return /^\/discuss\/new(\/|$)/.test(p) ||/^\/discuss\/[^\/]+\/(edit|new)(\/|$)/.test(p) ||/\/article(\/|$)/.test(p) ||/^\/team\//.test(p) ||/^\/problem\/(new|[^/]+\/edit)(\/|$)/.test(p) || // 新建题目 / 编辑题目/^\/(contest|training|blog|paste)\/(new|[^/]+\/edit)(\/|$)/.test(p);}// 是否在该编辑框上注入:// ① 找到了工具栏或「@」按钮 → 任何页面都注入(新建题目页的多段 Markdown 也走这条)// ② 只有光秃秃的编辑框 → 仅在明确的编辑类路径下自建按钮条// (题目提交框那种无工具栏的代码编辑器依旧保持静默)function allowInjection(d) {if (d.toolbar || d.at) return true;return isEditPath(location.pathname);}function allowedPage() { return true; }let pending = false;function ensure() {if (pending) return;pending = true;setTimeout(() => {pending = false;// 清掉已被 SPA 销毁的按钮for (let i = BTNS.length - 1; i >= 0; i--) {if (!document.contains(BTNS[i].btn)) {if (activeBtn === BTNS[i].btn) closePanel(false);BTNS.splice(i, 1);}}if (BTNS.length) return; // 已注入const ds = detectEditors();ED = ds[0] || null;if (!ds.length) return; // 无编辑器 → 完全静默for (const d of ds) {if (!allowInjection(d)) continue;const b = attachButton(d);if (b) BTNS.push({ btn: b, d: d });}if (BTNS.length && !btn) { btn = BTNS[0].btn; activeBtn = btn; activeD = BTNS[0].d; }}, 200);}/* ====================== 诊断:控制台执行 LGE_DIAG() 可查看详情 ====================== */21 行未改动host: d.host ? (d.host.tagName + '.' + (typeof d.host.className === 'string' ? d.host.className : '')).slice(0, 60) : null,atBtn: d.at ? (d.at.tagName + '.' + (typeof d.at.className === 'string' ? d.at.className : '')).slice(0, 60) : null} : null,buttons: btns,// 编辑框附近所有“像一行”的容器,按距离排序:判错工具栏时看这个一眼定位nearbyRows: (function () {const d0 = detectEditors()[0];if (!d0) return [];const rows = [];let n = d0.editable, i = 0;while (n && n !== document.body && i++ < 8) {[].slice.call(n.querySelectorAll('div, ul, nav, header')).forEach(el => {const c = typeof el.className === 'string' ? el.className : '';if (!c || /cm-|cmEditor|ͼ/.test(c)) return;if (el.contains(d0.editable)) return;const k = el.querySelectorAll('button, [role="button"], svg, [class*="icon"], [class*="btn"], [class*="item"]').length;if (k >= 1) rows.push({ el: (el.tagName + '.' + c).slice(0, 50), kids: k, dist: domDistance(el, d0.editable) });});n = n.parentElement;}return rows.sort((a, b) => a.dist - b.dist).slice(0, 8);})(),editors: detectEditors().map(x => ({editable: (x.editable.tagName + '.' + (typeof x.editable.className === 'string' ? x.editable.className : '')).slice(0, 40),toolbar: x.toolbar ? (x.toolbar.tagName + '.' + (typeof x.toolbar.className === 'string' ? x.toolbar.className : '')).slice(0, 40) : null,at: x.at ? (x.at.tagName + '.' + (typeof x.at.className === 'string' ? x.at.className : '')).slice(0, 30) : null})),injectedCount: BTNS.length,panel: panel ? { open: open, dir: lastDir, left: panel.style.left, top: panel.style.top } : null,btnRow: btn && btn.parentElement? (btn.parentElement.tagName + '.' + (typeof btn.parentElement.className === 'string' ? btn.parentElement.className : '')).slice(0, 60): null,sameRowAsAt: !!(btn && d && d.at && btn.parentElement === d.at.parentElement),insertMode: (function () { try { return localStorage.getItem('lge-mode') || 'entity'; } catch (e) { return 'entity'; } })()};};} catch (e) {}14 行未改动if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);else start();})();:::## AI 使用说明15 行未改动