dsh-annotator 0.0.0-stage → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/overlay.js ADDED
@@ -0,0 +1,862 @@
1
+ /**
2
+ * In-page picker overlay.
3
+ *
4
+ * Injected twice: as `Page.addScriptToEvaluateOnNewDocument` (so it survives
5
+ * navigation) and immediately via `Runtime.evaluate` for the page already open.
6
+ * It talks back through a CDP `Runtime.addBinding` function, which keeps the
7
+ * channel independent of CORS / mixed content / page CSP.
8
+ */
9
+
10
+ /** Name of the CDP binding the page calls to report a pick. */
11
+ export const BINDING_NAME = '__dshVisualPicker';
12
+
13
+ /** Runs in the page's main world. Keep it dependency-free and idempotent. */
14
+ export const OVERLAY_SCRIPT = String.raw`(() => {
15
+ var W = window;
16
+ // Bumped whenever the page-side logic changes: the script is injected twice per
17
+ // document (new-document preload + evaluate on the open page), so a newer build
18
+ // must be able to take over an older instance instead of leaving its listeners
19
+ // in charge for the rest of the page's life.
20
+ var REV = 12;
21
+ var HOST_ID = '__dsh-vp-root';
22
+ if (W.__DSH_VP__ && W.__DSH_VP__.rev === REV) { try { W.__DSH_VP__.reattach(); } catch (e) {} return; }
23
+ if (W.__DSH_VP__) { try { if (W.__DSH_VP__.dispose) W.__DSH_VP__.dispose(); } catch (e) {} }
24
+ var stale = document.getElementById(HOST_ID);
25
+ if (stale && stale.parentNode) { try { stale.parentNode.removeChild(stale); } catch (e) {} }
26
+
27
+ var BINDING = '${BINDING_NAME}';
28
+ var state = { version: 3, rev: REV, mode: 'off', seq: 0, count: null, locked: false, target: null, anchor: null, clicks: 0, moves: 0, guarded: 0, restored: 0 };
29
+ var nodes = {};
30
+ // macOS 的 Option 是组合键:按 Option+A 产出的是 å 而非 a,快捷键判定要按物理键
31
+ // code=KeyA,提示文案也要按平台区分(⌥Option+A / Alt+A)。
32
+ var MAC = /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent || '');
33
+ var HOTKEY = MAC ? '⌥ A' : 'Alt A';
34
+ var bound = [];
35
+ var lastFocused = null;
36
+ var hlTimer = 0;
37
+ var focusTimer = 0;
38
+ var noteTimer = 0;
39
+
40
+ function on(target, type, fn, capture) {
41
+ target.addEventListener(type, fn, !!capture);
42
+ bound.push([target, type, fn, !!capture]);
43
+ }
44
+
45
+ function dispose() {
46
+ for (var i = 0; i < bound.length; i++) {
47
+ try { bound[i][0].removeEventListener(bound[i][1], bound[i][2], bound[i][3]); } catch (e) {}
48
+ }
49
+ bound.length = 0;
50
+ stopFocusKeeper();
51
+ if (hlTimer) { clearTimeout(hlTimer); hlTimer = 0; }
52
+ if (nodes.host && nodes.host.parentNode) { try { nodes.host.parentNode.removeChild(nodes.host); } catch (e) {} }
53
+ nodes = {};
54
+ state.locked = false;
55
+ state.target = null;
56
+ state.mode = 'off';
57
+ }
58
+
59
+ function send(payload) {
60
+ var fn = W[BINDING];
61
+ if (typeof fn === 'function') {
62
+ try { fn(JSON.stringify(payload)); return true; } catch (e) {}
63
+ }
64
+ var q = W.__DSH_VP_QUEUE__ = W.__DSH_VP_QUEUE__ || [];
65
+ q.push(payload);
66
+ return false;
67
+ }
68
+
69
+ function flush() {
70
+ var q = W.__DSH_VP_QUEUE__ = W.__DSH_VP_QUEUE__ || [];
71
+ if (!q.length) return;
72
+ var fn = W[BINDING];
73
+ if (typeof fn !== 'function') return;
74
+ var items = q.splice(0, q.length);
75
+ for (var i = 0; i < items.length; i++) { try { fn(JSON.stringify(items[i])); } catch (e) {} }
76
+ }
77
+
78
+ function cssPath(el) {
79
+ if (!el || el.nodeType !== 1) return '';
80
+ if (el.id) return '#' + (W.CSS && CSS.escape ? CSS.escape(el.id) : el.id);
81
+ var parts = [];
82
+ var node = el;
83
+ while (node && node.nodeType === 1 && parts.length < 6) {
84
+ var part = node.localName;
85
+ if (node.classList && node.classList.length) {
86
+ var cls = [];
87
+ for (var i = 0; i < node.classList.length && cls.length < 2; i++) {
88
+ var c = node.classList[i];
89
+ if (c && c.length < 32) cls.push(W.CSS && CSS.escape ? CSS.escape(c) : c);
90
+ }
91
+ if (cls.length) part += '.' + cls.join('.');
92
+ }
93
+ var parent = node.parentElement;
94
+ if (parent) {
95
+ var same = [];
96
+ for (var j = 0; j < parent.children.length; j++) {
97
+ if (parent.children[j].localName === node.localName) same.push(parent.children[j]);
98
+ }
99
+ if (same.length > 1) part += ':nth-of-type(' + (same.indexOf(node) + 1) + ')';
100
+ }
101
+ parts.unshift(part);
102
+ if (parent && parent.id) { parts.unshift('#' + (W.CSS && CSS.escape ? CSS.escape(parent.id) : parent.id)); break; }
103
+ node = parent;
104
+ }
105
+ return parts.join(' > ');
106
+ }
107
+
108
+ /**
109
+ * 页面上只要有一个祖先带了 transform / filter / will-change / contain,
110
+ * 我们那些 fixed 定位的子元素就不再以视口为参照,而是以那个祖先为参照:
111
+ * host 自己的矩形会跟着偏(滚动后 host.top 变成 -scrollY 之类),
112
+ * 高亮框、卡片于是整体错位,甚至跑到视口外只剩左上角一点。
113
+ * 统一用 host 的矩形原点做换算,把「相对包含块」的坐标还原成「相对视口」。
114
+ */
115
+ function hostOrigin() {
116
+ var host = nodes.host;
117
+ if (!host || !host.getBoundingClientRect) return { x: 0, y: 0 };
118
+ var r = host.getBoundingClientRect();
119
+ return { x: r.left || 0, y: r.top || 0 };
120
+ }
121
+
122
+ /** 按视口坐标摆放一个 fixed 元素;祖先建了包含块时先减掉 host 原点。 */
123
+ function place(node, left, top) {
124
+ if (!node) return;
125
+ var o = hostOrigin();
126
+ node.style.left = (left - o.x) + 'px';
127
+ node.style.top = (top - o.y) + 'px';
128
+ }
129
+
130
+ function describe(el) {
131
+ var rect = el.getBoundingClientRect();
132
+ var text = '';
133
+ try {
134
+ text = (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '').trim();
135
+ } catch (e) { text = ''; }
136
+ var classes = [];
137
+ try { for (var i = 0; i < el.classList.length && i < 8; i++) classes.push(el.classList[i]); } catch (e) {}
138
+ var html = '';
139
+ try { html = el.outerHTML.slice(0, 600); } catch (e) {}
140
+ return {
141
+ kind: 'pick',
142
+ selector: cssPath(el),
143
+ tag: el.localName,
144
+ id: el.id || '',
145
+ classes: classes,
146
+ text: text.slice(0, 200),
147
+ html: html,
148
+ rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
149
+ pageRect: { x: rect.x + W.scrollX, y: rect.y + W.scrollY, width: rect.width, height: rect.height },
150
+ url: location.href,
151
+ title: document.title,
152
+ dpr: W.devicePixelRatio || 1
153
+ };
154
+ }
155
+
156
+ function ensureUI() {
157
+ if (document.getElementById(HOST_ID)) return true;
158
+ if (!document.body) return false;
159
+ var host = document.createElement('div');
160
+ host.id = HOST_ID;
161
+ host.setAttribute('data-dsh-visual-annotator', '1');
162
+ host.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;pointer-events:none;';
163
+ var shadow = host.attachShadow({ mode: 'open' });
164
+ shadow.innerHTML = [
165
+ '<style>',
166
+ ':host{--vp-acc:#ff7a45;--vp-acc-warm:#ffb08a;--vp-fg:#f6efe7;--vp-line:rgba(255,196,160,.16);--vp-ease:cubic-bezier(.16,1,.3,1);--vp-sans:ui-sans-serif,-apple-system,"Segoe UI Variable Text","Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;--vp-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace}',
167
+ // 拾取高亮:暖朱砂细线 + 柔和填空 + 左上/右下两个裁切标记,像设计工具而不是调试框。
168
+ '.box{position:fixed;pointer-events:none;display:none;box-sizing:border-box;border:1.5px solid var(--vp-acc);border-radius:7px;background:rgba(255,122,69,.09);box-shadow:0 12px 30px -12px rgba(255,122,69,.55)}',
169
+ '.box::before,.box::after{content:"";position:absolute;width:9px;height:9px;border:2px solid var(--vp-acc)}',
170
+ '.box::before{left:-4px;top:-4px;border-right:0;border-bottom:0;border-radius:3px 0 0 0}',
171
+ '.box::after{right:-4px;bottom:-4px;border-left:0;border-top:0;border-radius:0 0 3px 0}',
172
+ // 标注中保持高亮:hover 框会被 render() 清掉,用户打字时就看不见自己点的是哪个元素了。
173
+ '.mark{position:fixed;pointer-events:none;display:none;box-sizing:border-box;border:1.5px solid var(--vp-acc);border-radius:7px;background:rgba(255,122,69,.1);box-shadow:0 0 0 4px rgba(255,122,69,.1)}',
174
+ '.lbl{position:fixed;pointer-events:none;display:none;max-width:64vw;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:600 12px/1.35 var(--vp-mono);letter-spacing:.01em;padding:5px 9px;border-radius:8px;color:#ffc9b4;background:#1b1210;border:1px solid rgba(255,122,69,.42);box-shadow:0 8px 20px -8px rgba(0,0,0,.6)}',
175
+ '.hud{position:fixed;right:16px;bottom:16px;display:none;font:13px/1.35 var(--vp-sans);color:var(--vp-fg);-webkit-font-smoothing:antialiased}',
176
+ '.cluster,.pill{pointer-events:auto;white-space:nowrap;border:1px solid var(--vp-line);background:linear-gradient(180deg,rgba(38,29,24,.94),rgba(22,16,14,.96));-webkit-backdrop-filter:blur(18px) saturate(150%);backdrop-filter:blur(18px) saturate(150%);box-shadow:0 20px 48px -18px rgba(0,0,0,.8),0 1px 0 rgba(255,255,255,.06) inset}',
177
+ '.cluster{display:none;align-items:center;gap:9px;padding:7px 7px 7px 14px;border-radius:15px}',
178
+ '.cluster .met{display:flex;align-items:center;gap:7px;font-size:12px;color:#c2b5a8;letter-spacing:.01em}',
179
+ '.cluster .dot{width:7px;height:7px;border-radius:50%;background:var(--vp-acc);box-shadow:0 0 0 3px rgba(255,122,69,.16)}',
180
+ '.cluster .cnt{color:var(--vp-fg);font-weight:650;font-variant-numeric:tabular-nums}',
181
+ '.pill{display:none;align-items:center;gap:9px;padding:9px 13px;border-radius:13px;cursor:pointer;transition:transform .16s var(--vp-ease),border-color .16s var(--vp-ease)}',
182
+ '.pill:hover{transform:translateY(-1px);border-color:rgba(255,122,69,.5)}',
183
+ '.pill .go{font-weight:600;color:var(--vp-fg)}',
184
+ '.pill .go::before{content:"";display:inline-block;width:7px;height:7px;margin-right:8px;border-radius:50%;background:var(--vp-acc);box-shadow:0 0 0 3px rgba(255,122,69,.16);vertical-align:1px}',
185
+ '.pill .c{margin-left:2px;padding-left:11px;border-left:1px solid rgba(255,255,255,.11);color:#8e8378;font-size:11.5px}',
186
+ '.hud .k{font:600 10.5px/1 var(--vp-mono);letter-spacing:.04em;color:#c2b5a8;padding:3px 6px;border-radius:6px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.14)}',
187
+ '.hud button{font:inherit;font-size:12px;font-weight:550;color:#ede3d9;padding:7px 11px;border-radius:9px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.1);cursor:pointer;transition:background .14s,border-color .14s,transform .14s}',
188
+ '.hud button .k{margin-left:6px;background:rgba(0,0,0,.22);border-color:rgba(255,255,255,.12);color:#ffc9b4}',
189
+ '.hud button:hover:not(:disabled){background:rgba(255,255,255,.11);border-color:rgba(255,255,255,.2)}',
190
+ '.hud button:active:not(:disabled){transform:translateY(1px)}',
191
+ '.hud button.pri{color:#1b1108;font-weight:650;background:var(--vp-acc);border-color:transparent;box-shadow:0 8px 18px -10px rgba(255,122,69,.9)}',
192
+ '.hud button.pri:hover:not(:disabled){background:#ff8f5f}',
193
+ '.hud button.pri .k{background:rgba(0,0,0,.16);border-color:rgba(0,0,0,.14);color:#3a1c0e}',
194
+ '.hud button:disabled{opacity:.4;cursor:default}',
195
+ '.hud button:focus-visible,.pill:focus-visible{outline:2px solid var(--vp-acc-warm);outline-offset:2px}',
196
+ // 标注卡固定一套暖墨切面:跟随页面明暗会在深色站点糊成一片,也让卡片失去自己的身份。
197
+ '.card{position:fixed;pointer-events:auto;display:none;box-sizing:border-box;width:min(364px,calc(100vw - 24px));padding:16px;border-radius:16px;color:var(--vp-fg);font:13.5px/1.55 var(--vp-sans);background:linear-gradient(180deg,#261d18 0%,#191210 100%);border:1px solid var(--vp-line);box-shadow:0 30px 68px -20px rgba(0,0,0,.85),0 2px 10px rgba(0,0,0,.35),0 1px 0 rgba(255,255,255,.07) inset;animation:vpCardIn .18s var(--vp-ease);-webkit-font-smoothing:antialiased}',
198
+ '@keyframes vpCardIn{from{opacity:0;transform:translateY(7px) scale(.985)}to{opacity:1;transform:none}}',
199
+ // 小尖角把卡片和目标元素连起来:卡片可能在元素上方或下方,两种朝向都要能贴边。
200
+ '.card::before{content:"";position:absolute;width:12px;height:12px;transform:rotate(45deg);display:none}',
201
+ '.card.below::before,.card.above::before{display:block}',
202
+ '.card.below::before{top:-6.5px;left:var(--vp-notch,24px);background:#261d18;border-left:1px solid var(--vp-line);border-top:1px solid var(--vp-line)}',
203
+ '.card.above::before{bottom:-6.5px;left:var(--vp-notch,24px);background:#191210;border-right:1px solid var(--vp-line);border-bottom:1px solid var(--vp-line)}',
204
+ '@media (prefers-reduced-motion:reduce){.card{animation:none}.pill,.hud button,.card textarea{transition:none}}',
205
+ '.card .hd{display:flex;align-items:center;gap:8px;margin-bottom:10px}',
206
+ '.card .idx{font:650 11.5px/1 var(--vp-mono);letter-spacing:.06em;font-variant-numeric:tabular-nums;color:#ffc9b4;padding:5px 7px;border-radius:7px;background:rgba(255,122,69,.14);border:1px solid rgba(255,122,69,.32)}',
207
+ '.card .tag{font:600 12px/1 var(--vp-mono);color:var(--vp-fg);padding:5px 8px;border-radius:7px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);max-width:40%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
208
+ '.card .dim{font:12px/1 var(--vp-mono);font-variant-numeric:tabular-nums;letter-spacing:.02em;color:#a2958a}',
209
+ '.card .copy{margin-left:auto;font:600 12px/1 var(--vp-sans);color:#cbbdae;height:26px;padding:0 10px;border-radius:8px;background:transparent;border:1px solid rgba(255,255,255,.1);cursor:pointer;transition:color .14s,border-color .14s,background .14s}',
210
+ '.card .copy:hover{color:#fff;border-color:rgba(255,122,69,.5);background:rgba(255,122,69,.1)}',
211
+ '.card .sel{font:12px/1.5 var(--vp-mono);color:#c0b2a4;word-break:break-all;max-height:40px;overflow:hidden;margin-bottom:10px;padding:6px 9px;border-radius:8px;background:rgba(255,255,255,.045);border:1px solid rgba(255,255,255,.06)}',
212
+ '.card .quote{position:relative;display:none;font:13px/1.55 var(--vp-sans);color:#cfc1b3;padding:8px 11px 8px 27px;margin-bottom:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:9px;background:rgba(255,255,255,.04);box-shadow:inset 0 0 0 1px rgba(255,255,255,.045)}',
213
+ '.card .quote::before{content:"\\201C";position:absolute;left:10px;top:4px;font:700 24px/1 Georgia,"Songti SC","Times New Roman",serif;color:rgba(255,122,69,.78)}',
214
+ '.card textarea{display:block;width:100%;min-height:80px;max-height:200px;box-sizing:border-box;padding:10px 12px;border-radius:11px;resize:none;outline:none;font:13.5px/1.6 var(--vp-sans);color:var(--vp-fg);background:rgba(9,6,5,.5);border:1px solid rgba(255,255,255,.1);caret-color:var(--vp-acc);transition:border-color .14s,box-shadow .14s}',
215
+ '.card textarea::placeholder{color:#8b7f73}',
216
+ '.card textarea:focus{border-color:rgba(255,122,69,.55);box-shadow:0 0 0 3px rgba(255,122,69,.15)}',
217
+ '.card .row{display:flex;align-items:center;gap:8px;margin-top:14px}',
218
+ // 取消与添加同高 42px:此前一个 42 一个 45,边缘各差 1.5px,看着像没对齐。
219
+ '.card .row button{height:42px}',
220
+ '.card .hint{display:inline-flex;align-items:center;margin-right:auto;font:12px/1.35 var(--vp-sans);color:#c2b4a6;white-space:nowrap}',
221
+ '.card button{font:inherit;font-size:13px;font-weight:550;display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;padding:0 16px;line-height:1;border-radius:10px;color:#ede3d9;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);cursor:pointer;transition:background .14s,border-color .14s,transform .14s}',
222
+ '.card button:active{transform:translateY(1px)}',
223
+ '.card button.cancel{padding:0 14px;color:#c9bcae;background:transparent;border-color:rgba(255,255,255,.09)}',
224
+ '.card button.cancel:hover{color:var(--vp-fg);background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.16)}',
225
+ '.card button.pri{padding:0 15px;color:#1b1108;font-weight:650;background:var(--vp-acc);border-color:transparent;box-shadow:0 10px 22px -12px rgba(255,122,69,.95)}',
226
+ '.card button.pri:hover{background:#ff8f5f}',
227
+ '.card .keys{display:inline-flex;align-items:center;gap:4px;margin-left:9px}',
228
+ '.card button .k{display:inline-flex;align-items:center;height:20px;padding:0 7px;font:650 12px/1 var(--vp-mono);border-radius:6px;background:rgba(0,0,0,.3);border:1px solid rgba(0,0,0,.22);color:#ffeadd}',
229
+ '.card button .k.sym{font:600 13px/1 var(--vp-sans);padding:0 6px;letter-spacing:0}',
230
+ '.card .hint .k{font:600 11px/1 var(--vp-mono);padding:4px 6px;border-radius:6px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.13);color:#d8cabc}',
231
+ '.card button:focus-visible{outline:2px solid var(--vp-acc-warm);outline-offset:2px}',
232
+ '.note{position:fixed;right:16px;bottom:62px;display:none;max-width:70vw;pointer-events:none;font:12px/1.4 var(--vp-sans);color:var(--vp-fg);padding:7px 12px;border-radius:10px;background:#1b1210;border:1px solid var(--vp-line);box-shadow:0 14px 30px -14px rgba(0,0,0,.8)}',
233
+ 'html.__dsh-vp-pick,html.__dsh-vp-pick *{cursor:crosshair !important}',
234
+ '</style>',
235
+ '<div class="box"></div>',
236
+ '<div class="mark"></div>',
237
+ '<div class="lbl"></div>',
238
+ '<div class="hud">',
239
+ '<div class="cluster" role="toolbar" aria-label="标注控制台">',
240
+ '<span class="met"><span class="dot"></span>已标注 <b class="cnt">0</b> 处</span>',
241
+ '<button class="pause" type="button" title="暂停标注(Esc)">暂停<span class="k">Esc</span></button>',
242
+ '<button class="undo" type="button" title="撤销最近一条标注">撤销</button>',
243
+ '<button class="pri done" type="button" title="把全部标注插入 DSH 对话">完成并插入</button>',
244
+ '</div>',
245
+ '<div class="pill" role="button" tabindex="0" aria-label="开启标注模式" title="开启标注模式:点击页面元素即可标注(快捷键 ' + HOTKEY + ')">',
246
+ '<span class="go">开启标注</span>',
247
+ '<span class="k">' + HOTKEY + '</span>',
248
+ '<span class="c">已标注 <b class="pcnt">0</b> 处</span>',
249
+ '</div>',
250
+ '</div>',
251
+ '<div class="note"></div>',
252
+ '<div class="card" role="dialog" aria-label="页面元素标注">',
253
+ '<div class="hd"><span class="idx">01</span><span class="tag"></span><span class="dim"></span><button class="copy" type="button" title="复制选择器">复制</button></div>',
254
+ '<div class="sel"></div>',
255
+ '<div class="quote"></div>',
256
+ '<textarea autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="说明怎么改:字号 / 间距 / 颜色 / 文案 / 布局…"></textarea>',
257
+ '<div class="row"><span class="hint" title="按 Esc 取消这次标注"><span class="k">Esc</span></span><button class="cancel" type="button">取消</button><button class="pri" type="button">添加标注<span class="keys"></span></button></div>',
258
+ '</div>',
259
+ ].join('');
260
+ document.body.appendChild(host);
261
+ nodes.host = host;
262
+ nodes.box = shadow.querySelector('.box');
263
+ nodes.mark = shadow.querySelector('.mark');
264
+ nodes.lbl = shadow.querySelector('.lbl');
265
+ nodes.hud = shadow.querySelector('.hud');
266
+ nodes.cluster = shadow.querySelector('.cluster');
267
+ nodes.cnt = shadow.querySelector('.cnt');
268
+ nodes.pill = shadow.querySelector('.pill');
269
+ nodes.pcnt = shadow.querySelector('.pcnt');
270
+ nodes.pauseBtn = shadow.querySelector('button.pause');
271
+ nodes.undoBtn = shadow.querySelector('button.undo');
272
+ nodes.doneBtn = shadow.querySelector('button.done');
273
+ nodes.note = shadow.querySelector('.note');
274
+ nodes.card = shadow.querySelector('.card');
275
+ nodes.sel = shadow.querySelector('.sel');
276
+ nodes.idx = shadow.querySelector('.idx');
277
+ nodes.tag = shadow.querySelector('.tag');
278
+ nodes.dim = shadow.querySelector('.dim');
279
+ nodes.quote = shadow.querySelector('.quote');
280
+ nodes.copyBtn = shadow.querySelector('button.copy');
281
+ nodes.text = shadow.querySelector('textarea');
282
+ // 卡片里的两个键位提示按平台渲染,避免 macOS 上写成 Ctrl 让人按错。
283
+ // 提交快捷键拆成独立键帽:⌘ 与 ↵ 挤在一个键帽里会糊成一块,看不清是什么键。
284
+ // ↵(U+21B5)在 12px 等宽字体里细得几乎看不出是个键,Mac 用更粗的 ⏎(U+23CE)。
285
+ var keys = MAC ? ['⌘', '⏎'] : ['Ctrl', 'Enter'];
286
+ var keysHTML = keys.map(function (k) { return '<span class="k' + (k.length === 1 ? ' sym' : '') + '">' + k + '</span>'; }).join('');
287
+ shadow.querySelector('.card .keys').innerHTML = keysHTML;
288
+ shadow.querySelector('.card button.pri').title = '提交这张标注(' + (MAC ? '⌘ Enter' : 'Ctrl Enter') + ')';
289
+ on(shadow.querySelector('.cancel'), 'click', function (e) { e.preventDefault(); cancel(); }, false);
290
+ on(nodes.copyBtn, 'click', function (e) { e.preventDefault(); e.stopPropagation(); copySelector(); }, false);
291
+ on(nodes.text, 'input', autosizeText, false);
292
+ // 必须限定 .card:HUD 的完成按钮也带 .pri 且排在卡片按钮之前,
293
+ // 裸的 '.pri' 会把提交事件绑到完成按钮上,「添加标注」就没了反应。
294
+ on(shadow.querySelector('.card button.pri'), 'click', function (e) { e.preventDefault(); commit(); }, false);
295
+ on(nodes.text, 'keydown', onTextKey, false);
296
+ on(nodes.text, 'beforeinput', onBeforeInput, false);
297
+ on(nodes.card, 'keydown', onCardKey, false);
298
+ // Clicks inside the card belong to the card: page-level "click outside" handlers
299
+ // must not close modals or navigate while the user is writing an annotation.
300
+ var keepLocal = function (e) { e.stopPropagation(); };
301
+ on(nodes.card, 'mousedown', keepLocal, false);
302
+ on(nodes.card, 'mouseup', keepLocal, false);
303
+ on(nodes.card, 'click', keepLocal, false);
304
+ // HUD 交互与标注卡同理:点按事件留在控件里,页面自己的弹层/跳转不能被触发。
305
+ // Esc / 暂停 / 折叠胶囊走 setMode(经 binding 上报 host);撤销与完成直接发消息。
306
+ on(nodes.pauseBtn, 'click', function (e) { e.preventDefault(); e.stopPropagation(); setMode('off'); }, false);
307
+ on(nodes.undoBtn, 'click', function (e) { e.preventDefault(); e.stopPropagation(); send({ kind: 'undo' }); }, false);
308
+ on(nodes.doneBtn, 'click', function (e) { e.preventDefault(); e.stopPropagation(); send({ kind: 'consume' }); }, false);
309
+ on(nodes.pill, 'click', function (e) { e.preventDefault(); e.stopPropagation(); setMode('pick'); }, false);
310
+ on(nodes.pill, 'keydown', function (e) {
311
+ if (e.key !== 'Enter' && e.key !== ' ') return;
312
+ e.preventDefault();
313
+ e.stopPropagation();
314
+ setMode('pick');
315
+ }, false);
316
+ var keepHud = function (e) { e.stopPropagation(); };
317
+ on(nodes.hud, 'mousedown', keepHud, false);
318
+ on(nodes.hud, 'mouseup', keepHud, false);
319
+ on(nodes.hud, 'click', keepHud, false);
320
+ render();
321
+ return true;
322
+ }
323
+
324
+ function ready() {
325
+ if (nodes.host) return true;
326
+ return ensureUI();
327
+ }
328
+
329
+ /**
330
+ * True when the event was produced inside our shadow card. Shadow DOM retargets
331
+ * events to the host element as they cross the boundary, so the page sees a plain
332
+ * <div> instead of the textarea it expects.
333
+ */
334
+ function inCard(e) {
335
+ var host = nodes.host;
336
+ if (!host) return false;
337
+ if (typeof e.composedPath === 'function') {
338
+ var path = e.composedPath();
339
+ for (var i = 0; i < path.length; i++) if (path[i] === host) return true;
340
+ return false;
341
+ }
342
+ var node = e.target;
343
+ while (node) {
344
+ if (node === host) return true;
345
+ node = node.parentNode || node.host || null;
346
+ }
347
+ return false;
348
+ }
349
+
350
+ /**
351
+ * Page shortcut layers decide "ignore keys while typing in an input" by looking at
352
+ * event.target — which shadow retargeting turns into our host div — so they treat
353
+ * the annotation keystrokes as page shortcuts and may preventDefault() them. The
354
+ * card then shows a caret but swallows every character. This script runs at
355
+ * document start, so its capture listener is normally first: stop the page from
356
+ * seeing keystrokes that belong to the card. Default text insertion is not a
357
+ * propagation effect, so typing still lands in the textarea.
358
+ */
359
+ function guardCardKeys(e) {
360
+ if (!nodes.host || !state.locked || !inCard(e)) return;
361
+ if (e.type === 'keydown') {
362
+ if (e.key === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); cancel(); return; }
363
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); e.stopImmediatePropagation(); commit(); return; }
364
+ if (e.key === 'Tab') { e.preventDefault(); e.stopImmediatePropagation(); moveCardFocus(e.shiftKey); return; }
365
+ }
366
+ // A page listener registered before this one already cancelled the default
367
+ // action. Swallowing the event here would hide that from the card's own
368
+ // fallback handler, so let it through and let the textarea restore the edit.
369
+ if (e.defaultPrevented) return;
370
+ state.guarded++;
371
+ e.stopImmediatePropagation();
372
+ }
373
+
374
+ /** Apply an edit ourselves, for pages that already cancelled the default action. */
375
+ function applyEdit(kind, text) {
376
+ var ta = nodes.text;
377
+ if (!ta) return false;
378
+ var start = ta.selectionStart == null ? ta.value.length : ta.selectionStart;
379
+ var end = ta.selectionEnd == null ? ta.value.length : ta.selectionEnd;
380
+ if (kind === 'insert') { ta.setRangeText(String(text), start, end, 'end'); return true; }
381
+ if (kind === 'backspace') {
382
+ if (start !== end) { ta.setRangeText('', start, end, 'end'); return true; }
383
+ if (start > 0) { ta.setRangeText('', start - 1, end, 'end'); return true; }
384
+ return false;
385
+ }
386
+ if (kind === 'delete') {
387
+ if (start !== end) { ta.setRangeText('', start, end, 'end'); return true; }
388
+ if (end < ta.value.length) { ta.setRangeText('', start, end + 1, 'end'); return true; }
389
+ return false;
390
+ }
391
+ return false;
392
+ }
393
+
394
+ function onTextKey(e) {
395
+ if (e.key === 'Escape') { e.preventDefault(); cancel(); return; }
396
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); commit(); return; }
397
+ // A page listener registered before our guard may have cancelled the default
398
+ // action already; restore the edit so no keystroke is silently lost.
399
+ if (e.defaultPrevented && !e.isComposing) {
400
+ state.restored++;
401
+ if (e.key === 'Backspace') { e.preventDefault(); applyEdit('backspace'); return; }
402
+ if (e.key === 'Delete') { e.preventDefault(); applyEdit('delete'); return; }
403
+ if (e.key === 'Enter') { e.preventDefault(); applyEdit('insert', '\n'); return; }
404
+ if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) { e.preventDefault(); applyEdit('insert', e.key); return; }
405
+ }
406
+ e.stopPropagation();
407
+ }
408
+
409
+ function onBeforeInput(e) {
410
+ if (!e.defaultPrevented || e.isComposing) return;
411
+ state.restored++;
412
+ var type = e.inputType || '';
413
+ if (type === 'insertText') { e.preventDefault(); applyEdit('insert', e.data || ''); return; }
414
+ if (type === 'insertLineBreak' || type === 'insertParagraph') { e.preventDefault(); applyEdit('insert', '\n'); return; }
415
+ if (type === 'deleteContentBackward') { e.preventDefault(); applyEdit('backspace'); return; }
416
+ if (type === 'deleteContentForward') { e.preventDefault(); applyEdit('delete'); }
417
+ }
418
+
419
+ /** Keep the caret inside the card even when the page grabs focus on click or timer. */
420
+ function keepCardFocus() {
421
+ if (!state.locked || !nodes.text || !nodes.card) return;
422
+ if (document.hidden) return;
423
+ if (nodes.card.style.display === 'none') return;
424
+ var shadow = nodes.host && nodes.host.shadowRoot;
425
+ var active = shadow ? shadow.activeElement : null;
426
+ if (active === nodes.text) return;
427
+ if (active && nodes.card.contains(active)) return; // the user tabbed to a card button
428
+ try { nodes.text.focus({ preventScroll: true }); } catch (e) { try { nodes.text.focus(); } catch (err) {} }
429
+ }
430
+
431
+ function startFocusKeeper() {
432
+ if (focusTimer) return;
433
+ focusTimer = setInterval(keepCardFocus, 200);
434
+ }
435
+
436
+ function stopFocusKeeper() {
437
+ if (!focusTimer) return;
438
+ clearInterval(focusTimer);
439
+ focusTimer = 0;
440
+ unlockPageFocus();
441
+ }
442
+
443
+ /**
444
+ * While the card is open it behaves like a modal dialog, so page code must not be
445
+ * able to pull the caret away. Several apps focus() their own widget from a click,
446
+ * focusin or timer handler; the annotation then quietly lands in that widget while
447
+ * the card still looks focused. Redirect such calls to the card instead.
448
+ */
449
+ var nativeFocus = null;
450
+ var focusProto = null;
451
+
452
+ function lockPageFocus() {
453
+ if (nativeFocus) return;
454
+ var proto = W.HTMLElement && W.HTMLElement.prototype;
455
+ if (!proto || typeof proto.focus !== 'function') return;
456
+ focusProto = proto;
457
+ nativeFocus = proto.focus;
458
+ proto.focus = function (opts) {
459
+ if (state.locked && nodes.text && nodes.card && !nodes.card.contains(this)) {
460
+ try { nodes.text.focus({ preventScroll: true }); return; } catch (e) { try { nodes.text.focus(); return; } catch (err) {} }
461
+ }
462
+ return nativeFocus.call(this, opts);
463
+ };
464
+ }
465
+
466
+ function unlockPageFocus() {
467
+ if (!nativeFocus || !focusProto) return;
468
+ try { focusProto.focus = nativeFocus; } catch (e) {}
469
+ nativeFocus = null;
470
+ focusProto = null;
471
+ }
472
+
473
+ /** 批注序号补零:卡片左上角的 01/02 是给人看的顺序,不是内部 id。 */
474
+ function pad2(n) {
475
+ var s = String(n);
476
+ return s.length < 2 ? '0' + s : s;
477
+ }
478
+
479
+ /** 评论框随内容长高(上限 190px),长批注不用在小窗里来回滚。 */
480
+ function autosizeText() {
481
+ var ta = nodes.text;
482
+ if (!ta) return;
483
+ ta.style.height = 'auto';
484
+ ta.style.height = Math.min(190, Math.max(74, ta.scrollHeight)) + 'px';
485
+ // 卡片高度变了,向上翻转时可能压到目标元素,重新摆一次位;正在输入的焦点不受影响。
486
+ followTarget();
487
+ }
488
+
489
+ /** 复制选择器:剪贴板被页面策略拒绝时明确说出来,而不是静默失败。 */
490
+ function copySelector() {
491
+ var value = nodes.sel ? nodes.sel.textContent : '';
492
+ if (!value) return;
493
+ var done = function () { if (W.__DSH_VP__) W.__DSH_VP__.flash('已复制选择器'); };
494
+ var fail = function () { if (W.__DSH_VP__) W.__DSH_VP__.flash('复制失败:浏览器未授权剪贴板'); };
495
+ try {
496
+ if (navigator.clipboard && navigator.clipboard.writeText) {
497
+ navigator.clipboard.writeText(value).then(done, fail);
498
+ return;
499
+ }
500
+ } catch (e) {}
501
+ fail();
502
+ }
503
+
504
+ function render() {
505
+ if (!nodes.host) return;
506
+ var on = state.mode === 'pick';
507
+ document.documentElement.classList.toggle('__dsh-vp-pick', on);
508
+ // Host 是计数真相源:sync() 推来的 count 优先,还没同步过才退回本地 seq。
509
+ var n = state.count !== null ? state.count : state.seq;
510
+ nodes.box.style.display = 'none';
511
+ nodes.lbl.style.display = 'none';
512
+ // 容器在 CSS 里是隐藏的初始态(避免首帧闪一下),真正可见由这里决定:
513
+ // off 模式显示折叠胶囊,pick 模式显示控制台,两者都由 render() 切换。
514
+ if (nodes.hud) nodes.hud.style.display = 'block';
515
+ nodes.cluster.style.display = on ? 'flex' : 'none';
516
+ nodes.pill.style.display = on ? 'none' : 'flex';
517
+ nodes.cnt.textContent = String(n);
518
+ nodes.pcnt.textContent = String(n);
519
+ nodes.undoBtn.disabled = nodes.doneBtn.disabled = n === 0;
520
+ if (!on) hideCard();
521
+ }
522
+
523
+ /** 选中后一直亮着:用户写批注时不至于忘了自己指的是哪个元素。 */
524
+ function showMark(rect) {
525
+ if (!nodes.mark || !rect) return;
526
+ nodes.mark.style.display = 'block';
527
+ place(nodes.mark, rect.x, rect.y);
528
+ nodes.mark.style.width = rect.width + 'px';
529
+ nodes.mark.style.height = rect.height + 'px';
530
+ }
531
+
532
+ function hideMark() {
533
+ if (nodes.mark) nodes.mark.style.display = 'none';
534
+ }
535
+
536
+ /**
537
+ * 页面滚动或改窗口大小时,高亮框和卡片要跟着目标元素走:
538
+ * 卡片是 fixed 定位的,不跟就会停在已经无关的位置上。
539
+ */
540
+ function followTarget() {
541
+ if (!state.target || !state.targetEl || !state.targetEl.isConnected) return;
542
+ var rect = state.targetEl.getBoundingClientRect();
543
+ state.target.rect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
544
+ showMark(state.target.rect);
545
+ if (nodes.card && nodes.card.style.display !== 'none') positionCard(state.target.rect, state.anchor);
546
+ }
547
+
548
+ function closeCard() {
549
+ stopFocusKeeper();
550
+ hideMark();
551
+ if (nodes.card) nodes.card.style.display = 'none';
552
+ var restore = lastFocused;
553
+ lastFocused = null;
554
+ // restore.focus() 默认会把目标元素滚进视口:Windows 上点按钮会先给它焦点,
555
+ // 提交后这一下 focus 就可能把页面滚走一点,看起来像「插完标注浏览器抖一下」。
556
+ if (restore && typeof restore.focus === 'function') {
557
+ try { restore.focus({ preventScroll: true }); } catch (e) { try { restore.focus(); } catch (err) {} }
558
+ }
559
+ }
560
+
561
+ function hideCard() {
562
+ state.locked = false;
563
+ state.target = null;
564
+ state.targetEl = null;
565
+ closeCard();
566
+ render();
567
+ }
568
+
569
+ function cancel() { hideCard(); }
570
+
571
+ function commit() {
572
+ if (!state.target) return hideCard();
573
+ var payload = state.target;
574
+ payload.comment = (nodes.text && nodes.text.value || '').trim();
575
+ payload.seq = ++state.seq;
576
+ state.locked = false;
577
+ state.target = null;
578
+ state.targetEl = null;
579
+ // 先把卡片藏起来再清内容:反过来的话,多行备注会让卡片先缩回单行高度、下一帧才消失,
580
+ // 用户看到的就是提交瞬间「闪/抖」一下。隐藏后再改 textarea,页面只渲染最终态。
581
+ closeCard();
582
+ nodes.text.value = '';
583
+ nodes.text.style.height = '';
584
+ nodes.box.style.display = 'none';
585
+ nodes.lbl.style.display = 'none';
586
+ send(payload);
587
+ render();
588
+ }
589
+
590
+ function placeCard(rect, anchor) {
591
+ lastFocused = document.activeElement;
592
+ state.anchor = anchor || null;
593
+ nodes.card.style.display = 'block';
594
+ positionCard(rect, state.anchor);
595
+ lockPageFocus();
596
+ try { nodes.text.focus({ preventScroll: true }); } catch (e) { nodes.text.focus(); }
597
+ startFocusKeeper();
598
+ }
599
+
600
+ /**
601
+ * 只算几何:滚动、改窗口、批注变长时复用,避免重复聚焦和重播入场动画。
602
+ *
603
+ * 早先只有「下方 / 上方」两种摆法,下方放不下时取 top = max(8, rect.y - h - 8):
604
+ * 目标贴着视口顶部、或者目标本身就是一大块(页面里选个大容器很常见)时,
605
+ * top 会落到 8 —— 卡片直接跳到视口左上角,正好盖住刚点中的元素,
606
+ * 看起来就是「标注框跳到左上角、形状被遮挡」。现在先把卡片夹进视口再摆,
607
+ * 只是贴着目标,不会再整张跑到角落里去。
608
+ */
609
+ function positionCard(rect, anchor) {
610
+ var card = nodes.card;
611
+ if (!card || !rect) return;
612
+ var vw = W.innerWidth || 1200;
613
+ var vh = W.innerHeight || 800;
614
+ // 用 offsetWidth/offsetHeight 而不是 getBoundingClientRect():入场动画期间卡片
615
+ // 带着 scale(.985),rect 量出来是缩小后的尺寸,定位会差几个像素。
616
+ var w = card.offsetWidth || 308;
617
+ var h = card.offsetHeight || 190;
618
+ var gap = 8;
619
+ var maxLeft = Math.max(gap, vw - w - gap);
620
+ var maxTop = Math.max(gap, vh - h - gap);
621
+ var clampLeft = function (x) { return Math.min(Math.max(gap, x), maxLeft); };
622
+ var clampTop = function (y) { return Math.min(Math.max(gap, y), maxTop); };
623
+ // 下方优先;下方放不下就看上方;上下都放不下(目标很高)时选空间更大的一侧,
624
+ // 再夹进视口——于是最坏情况只是压住目标的一条边,而不是跳到左上角。
625
+ var roomBelow = vh - gap - (rect.y + rect.height + gap);
626
+ var roomAbove = rect.y - gap - gap;
627
+ var below;
628
+ if (roomBelow >= h) below = true;
629
+ else if (roomAbove >= h) below = false;
630
+ else if (anchor && anchor.y >= 0) {
631
+ // 上下都放不下(目标几乎占满视口,或者比视口还高):往鼠标点的反方向放。
632
+ // 用户点在上半屏就把卡片压到视口底部,别正好盖住他正在看的那一块。
633
+ below = anchor.y < vh / 2;
634
+ } else below = roomBelow >= roomAbove;
635
+ var left = clampLeft(rect.x + rect.width / 2 - w / 2);
636
+ var top = clampTop(below ? rect.y + rect.height + gap : rect.y - h - gap);
637
+ place(card, left, top);
638
+ // 尖角对准元素的水平中心,但夹在卡片圆角之内,免得跑到边框外面。
639
+ var notch = Math.max(18, Math.min(w - 30, rect.x + rect.width / 2 - left - 6));
640
+ card.style.setProperty('--vp-notch', notch + 'px');
641
+ // 尖角朝向按实际几何决定:卡片整体在目标下方才朝上指,在上方才朝下指;
642
+ // 两者都不成立(夹回来之后和目标的边重叠)就不画尖角,免得指向不相干的方向。
643
+ var intersectsX = left + w > rect.x && left < rect.x + rect.width;
644
+ card.classList.toggle('below', intersectsX && top >= rect.y + rect.height - 1);
645
+ card.classList.toggle('above', intersectsX && top + h <= rect.y + 1);
646
+ }
647
+
648
+ function cardFocusables() {
649
+ if (!nodes.card) return [];
650
+ var list = [];
651
+ var els = nodes.card.querySelectorAll('textarea, button');
652
+ for (var i = 0; i < els.length; i++) list.push(els[i]);
653
+ return list;
654
+ }
655
+
656
+ function moveCardFocus(back) {
657
+ var items = cardFocusables();
658
+ if (!items.length) return;
659
+ var shadow = nodes.host && nodes.host.shadowRoot;
660
+ var active = shadow ? shadow.activeElement : null;
661
+ var index = -1;
662
+ for (var i = 0; i < items.length; i++) if (items[i] === active) index = i;
663
+ if (index < 0) index = back ? 0 : items.length - 1;
664
+ var next = back ? (index - 1 + items.length) % items.length : (index + 1) % items.length;
665
+ try { items[next].focus(); } catch (e) {}
666
+ }
667
+
668
+ function onCardKey(e) {
669
+ if (e.key !== 'Tab') return;
670
+ e.preventDefault();
671
+ moveCardFocus(e.shiftKey);
672
+ }
673
+
674
+ function clearHover() {
675
+ if (!nodes.box) return;
676
+ nodes.box.style.display = 'none';
677
+ nodes.lbl.style.display = 'none';
678
+ }
679
+
680
+ function highlight(opts) {
681
+ opts = opts || {};
682
+ if (!ready()) return false;
683
+ var rect = null;
684
+ if (opts.selector) {
685
+ var el = null;
686
+ try { el = document.querySelector(String(opts.selector)); } catch (e) { el = null; }
687
+ if (el && el.nodeType === 1) {
688
+ try { el.scrollIntoView({ block: 'center' }); } catch (e) {}
689
+ rect = el.getBoundingClientRect();
690
+ }
691
+ }
692
+ if (!rect && opts.pageRect) {
693
+ var pr = opts.pageRect;
694
+ try { W.scrollTo(pr.x - 120, pr.y - 120); } catch (e) {}
695
+ rect = { x: pr.x - W.scrollX, y: pr.y - W.scrollY, width: pr.width, height: pr.height };
696
+ }
697
+ if (!rect || !rect.width || !rect.height) return false;
698
+ nodes.box.style.display = 'block';
699
+ place(nodes.box, rect.x, rect.y);
700
+ nodes.box.style.width = rect.width + 'px';
701
+ nodes.box.style.height = rect.height + 'px';
702
+ nodes.lbl.style.display = 'block';
703
+ nodes.lbl.textContent = String(opts.label || '');
704
+ var lblTop = rect.y - 22;
705
+ place(nodes.lbl, Math.max(4, rect.x), lblTop < 4 ? rect.y + 2 : lblTop);
706
+ if (hlTimer) { clearTimeout(hlTimer); hlTimer = 0; }
707
+ hlTimer = setTimeout(function () {
708
+ nodes.box.style.display = 'none';
709
+ nodes.lbl.style.display = 'none';
710
+ hlTimer = 0;
711
+ }, 1800);
712
+ return true;
713
+ }
714
+
715
+ function onMove(e) {
716
+ if (state.mode !== 'pick' || state.locked) return;
717
+ if (!ready()) return;
718
+ var el = e.target;
719
+ if (!el || el.nodeType !== 1 || el === nodes.host) return;
720
+ if (el.id === HOST_ID || (el.closest && el.closest('#' + HOST_ID))) return;
721
+ var rect = el.getBoundingClientRect();
722
+ nodes.box.style.display = 'block';
723
+ place(nodes.box, rect.x, rect.y);
724
+ nodes.box.style.width = rect.width + 'px';
725
+ nodes.box.style.height = rect.height + 'px';
726
+ nodes.lbl.style.display = 'block';
727
+ nodes.lbl.textContent = el.localName + (el.id ? '#' + el.id : '') + ' · ' + Math.round(rect.width) + '×' + Math.round(rect.height);
728
+ var lblTop = rect.y - 22;
729
+ place(nodes.lbl, Math.max(4, rect.x), lblTop < 4 ? rect.y + 2 : lblTop);
730
+ }
731
+
732
+ function onClick(e) {
733
+ state.clicks++;
734
+ if (state.mode !== 'pick' || state.locked) return;
735
+ if (!ready()) return;
736
+ var el = e.target;
737
+ if (!el || el.nodeType !== 1 || el.id === HOST_ID) return;
738
+ e.preventDefault();
739
+ e.stopPropagation();
740
+ try {
741
+ state.target = describe(el);
742
+ state.targetEl = el;
743
+ state.locked = true;
744
+ nodes.sel.textContent = state.target.selector;
745
+ showMark(state.target.rect);
746
+ nodes.idx.textContent = pad2((state.count !== null ? state.count : state.seq) + 1);
747
+ nodes.tag.textContent = state.target.tag || 'node';
748
+ nodes.dim.textContent =
749
+ Math.round(state.target.rect.width) + '×' + Math.round(state.target.rect.height);
750
+ // 把点中的元素文字摘一句贴在卡上:确认「点的是不是这个」比读选择器快得多。
751
+ var snippet = String(state.target.text || '').replace(/\s+/g, ' ').trim().slice(0, 90);
752
+ nodes.quote.textContent = snippet;
753
+ nodes.quote.style.display = snippet ? 'block' : 'none';
754
+ nodes.text.value = '';
755
+ nodes.text.style.height = '';
756
+ // 记下点击位置:目标很大时靠它决定卡片往哪边躲。
757
+ placeCard(state.target.rect, { x: e.clientX, y: e.clientY });
758
+ render();
759
+ } catch (err) {
760
+ state.locked = false;
761
+ state.target = null;
762
+ W.__DSH_VP_LAST_ERROR__ = String((err && err.stack) || err);
763
+ }
764
+ }
765
+
766
+ function onKey(e) {
767
+ // 页面里直接 Alt+A 切换标注模式:经 binding 上报 host,面板与其它标签页同步。
768
+ // macOS 的 Option+A 会把 e.key 组合成 å,必须按物理键 e.code === 'KeyA' 判定。
769
+ if (e.altKey && !e.ctrlKey && !e.metaKey && (e.code === 'KeyA' || e.key === 'a' || e.key === 'A')) {
770
+ if (state.locked) return;
771
+ e.preventDefault();
772
+ e.stopPropagation();
773
+ setMode(state.mode === 'pick' ? 'off' : 'pick');
774
+ return;
775
+ }
776
+ if (e.key !== 'Escape') return;
777
+ if (state.locked) { e.preventDefault(); e.stopPropagation(); cancel(); return; }
778
+ if (state.mode === 'pick') { e.preventDefault(); e.stopPropagation(); setMode('off'); }
779
+ }
780
+
781
+ function setMode(mode, fromHost) {
782
+ mode = mode === 'pick' ? 'pick' : 'off';
783
+ var changed = state.mode !== mode;
784
+ state.mode = mode;
785
+ // 用户来源(Esc / HUD 按钮 / 折叠胶囊)必须上报 host,让面板与其它标签页同步;
786
+ // host 下发的变更带 fromHost=true,否则两边会对同一个模式互相回显、打乒乓。
787
+ if (!fromHost && changed) send({ kind: 'mode', mode: mode });
788
+ if (state.mode === 'pick') ready();
789
+ if (state.mode !== 'pick') hideCard();
790
+ if (nodes.host) {
791
+ nodes.host.style.pointerEvents = 'none';
792
+ clearHover();
793
+ }
794
+ render();
795
+ if (state.mode === 'pick') flush();
796
+ }
797
+
798
+ function reattach() {
799
+ if (document.body) ensureUI();
800
+ render();
801
+ flush();
802
+ }
803
+
804
+ W.__DSH_VP__ = {
805
+ version: 3,
806
+ rev: REV,
807
+ setMode: setMode,
808
+ dispose: dispose,
809
+ getMode: function () { return state.mode; },
810
+ reattach: reattach,
811
+ flush: flush,
812
+ highlight: highlight,
813
+ // Host -> page 的唯一同步口:mode 归 host 管,已标注数也由 host 推送,
814
+ // 页面只做展示,不再维护第二份会漂移的计数。
815
+ sync: function (info) {
816
+ info = info || {};
817
+ if (typeof info.count === 'number') state.count = info.count;
818
+ if (info.mode === 'pick' || info.mode === 'off') setMode(info.mode, true);
819
+ else if (nodes.host) render();
820
+ },
821
+ flash: function (message) {
822
+ if (!nodes.note) return;
823
+ nodes.note.textContent = String(message || '');
824
+ nodes.note.style.display = 'block';
825
+ if (noteTimer) clearTimeout(noteTimer);
826
+ noteTimer = setTimeout(function () { nodes.note.style.display = 'none'; }, 2000);
827
+ }
828
+ };
829
+
830
+ W.__DSH_VP_DEBUG__ = function () {
831
+ return {
832
+ rev: REV,
833
+ mode: state.mode,
834
+ locked: state.locked,
835
+ seq: state.seq,
836
+ count: state.count,
837
+ clicks: state.clicks,
838
+ guarded: state.guarded,
839
+ restored: state.restored,
840
+ ui: !!nodes.host,
841
+ error: W.__DSH_VP_LAST_ERROR__ || null
842
+ };
843
+ };
844
+
845
+ on(W, 'mousemove', onMove, true);
846
+ on(W, 'click', onClick, true);
847
+ on(W, 'keydown', onKey, true);
848
+ // capture 的 scroll 才能收到内层滚动容器的滚动事件。
849
+ on(W, 'scroll', followTarget, true);
850
+ on(W, 'resize', followTarget, false);
851
+ // Registered here, at document start, so these capture listeners run before the
852
+ // page's own shortcut layers and can shield the card's keystrokes from them.
853
+ on(W, 'keydown', guardCardKeys, true);
854
+ on(W, 'keypress', guardCardKeys, true);
855
+ on(W, 'beforeinput', guardCardKeys, true);
856
+ on(W, 'compositionstart', guardCardKeys, true);
857
+ on(W, 'compositionupdate', guardCardKeys, true);
858
+ on(W, 'compositionend', guardCardKeys, true);
859
+ on(W, 'focusin', function () { if (state.locked) keepCardFocus(); }, true);
860
+
861
+ if (document.body) ensureUI(); else document.addEventListener('DOMContentLoaded', function () { ensureUI(); }, { once: true });
862
+ })();`;