dsh-document-view 1.1.1 → 1.2.1

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.
@@ -31,6 +31,7 @@ export function installDocumentCollaboration(ctx, require) {
31
31
  let storage;
32
32
  try { storage = window.localStorage; } catch {}
33
33
  const model = new CollaborationState(storage);
34
+ const book = new AnnotationBook(storage);
34
35
  const listeners = new Set();
35
36
  let revision = 0, fingerprint = '', raf = 0, disposed = false;
36
37
  let frame, right, center, observedFrame, observedPanel, drag;
@@ -47,7 +48,11 @@ export function installDocumentCollaboration(ctx, require) {
47
48
  [data-fdc-active] { grid-template-columns:var(--fdc-columns) !important; transition:none !important; }
48
49
  [data-fdc-active] > [data-fdc-center] { grid-column:3; grid-row:1; min-width:0; border-radius:0 !important; }
49
50
  [data-fdc-active] > [data-rightbar-col] { grid-column:2; grid-row:1; position:relative; min-width:0; overflow:hidden; }
50
- [data-fdc-active] [data-sidebar-right-panel] { left:0 !important; right:auto !important; top:0 !important; bottom:0 !important; width:100% !important; max-width:none !important; --dsh-sidebar-width:100% !important; }
51
+ [data-fdc-active] [data-sidebar-right-panel] { position:absolute !important; inset:0 !important; left:0 !important; right:0 !important; top:0 !important; bottom:0 !important; width:auto !important; max-width:none !important; --dsh-sidebar-width:100% !important; }
52
+ [data-fdc-active] iframe[data-html-preview] { width:100% !important; height:100% !important; border:0 !important; display:block !important; background:var(--dsw-alias-bg-base,#fff); }
53
+ [data-fdc-active] iframe[data-fdc-html] { position:absolute !important; inset:0 !important; width:100% !important; height:100% !important; border:0 !important; display:block !important; z-index:5 !important; background:var(--dsw-alias-bg-base,#fff); }
54
+ [data-fdc-active] [data-rightbar-col] :has(> iframe[data-html-preview]) { width:100%; height:100%; }
55
+ [data-fdc-active] iframe[data-sidebar-browser-frame] { width:100% !important; height:100% !important; border:0 !important; display:block !important; }
51
56
  [data-fdc-active] > [data-side="rightbar"] { display:none !important; }
52
57
  [data-fdc-active] [data-fdc-center] { --dsh-composer-side-clearance:12px; --dsh-composer-card-max-width:100%; border-left:1px solid var(--dsw-alias-border-l3,#ddd); }
53
58
  [data-fdc-divider] { position:absolute; top:var(--dsh-windows-titlebar-height,0px); bottom:0; width:8px; margin-left:-4px; z-index:30; cursor:col-resize; touch-action:none; }
@@ -88,6 +93,52 @@ export function installDocumentCollaboration(ctx, require) {
88
93
  [data-fdc-compact] button[aria-pressed="true"] { color:var(--dsw-alias-state-business-primary,#2563eb); background:var(--dsw-alias-fill-tsp-secondary,#f0f1f3); }
89
94
  [data-fdc-compact] { position:absolute; top:var(--dsh-windows-titlebar-height,0px); right:8px; height:32px; z-index:35; display:flex; align-items:center; gap:4px; font-size:12px; background:var(--dsw-alias-bg-base,#fff); }
90
95
  [data-fdc-compact][hidden],[data-fdc-divider][hidden] { display:none; }
96
+ /* Annotation marks sit on the host's PDF surface; the page text layer is
97
+ scaled by pdf.js, while percentages keep the marks glued to the page. */
98
+ [data-fdc-anno-layer] { position:absolute; inset:0; pointer-events:none; z-index:3; }
99
+ .fdc-anno-mark { position:absolute; pointer-events:none; border-radius:2px; }
100
+ .fdc-anno-mark.is-delete { color:#b42318; background:rgba(239,68,68,.18); }
101
+ .fdc-anno-mark.is-delete::after { content:""; position:absolute; left:0; right:0; top:54%; border-top:1.5px solid currentColor; opacity:.85; }
102
+ .fdc-anno-mark.is-comment { background:rgba(250,204,21,.36); border-bottom:2px dashed #d97706; }
103
+ .fdc-anno-mark.is-done { background:rgba(22,163,74,.22); border-bottom:2px solid #16a34a; }
104
+ .fdc-anno-mark.is-done::after { content:none; }
105
+ .fdc-anno-mark.is-sent { opacity:.55; }
106
+ .fdc-anno-mark.is-sent.is-done { opacity:1; }
107
+ .fdc-anno-badge { position:absolute; transform:translate(-50%,-50%); min-width:16px; height:16px; box-sizing:border-box; border:0; border-radius:8px; background:#b45309; color:#fff; font:600 10px/16px system-ui,sans-serif; text-align:center; padding:0 3px; pointer-events:auto; cursor:pointer; z-index:4; box-shadow:0 1px 3px #0003; }
108
+ .fdc-anno-badge.is-done { background:#15803d; }
109
+ .fdc-anno-bubble { position:fixed; z-index:1200; display:flex; gap:2px; padding:3px; border:1px solid var(--dsw-alias-border-l3,#ddd); border-radius:8px; background:var(--dsw-alias-bg-base,#fff); box-shadow:0 6px 20px #0002; }
110
+ .fdc-anno-bubble button,.fdc-anno-editor button,.fdc-anno-panel button,.fdc-anno-toast button { font:inherit; font-size:12px; border:0; border-radius:6px; padding:4px 9px; cursor:pointer; background:transparent; color:var(--dsw-alias-label-primary,#333); white-space:nowrap; }
111
+ .fdc-anno-bubble button:hover,.fdc-anno-editor button:hover,.fdc-anno-panel button:hover { background:var(--dsw-alias-fill-tsp-secondary,#f0f1f3); }
112
+ .fdc-anno-bubble button.primary,.fdc-anno-editor button.primary,.fdc-anno-panel button.primary { background:#2563eb; color:#fff; }
113
+ .fdc-anno-bubble button.primary:hover,.fdc-anno-editor button.primary:hover,.fdc-anno-panel button.primary:hover { background:#1d4ed8; }
114
+ .fdc-anno-editor,.fdc-anno-panel { position:fixed; z-index:1201; box-sizing:border-box; border:1px solid var(--dsw-alias-border-l3,#ddd); border-radius:var(--dsw-radius-md,8px); background:var(--dsw-alias-bg-base,#fff); box-shadow:0 8px 28px #0003; color:var(--dsw-alias-label-primary,#333); }
115
+ .fdc-anno-editor { width:min(320px,calc(100vw - 16px)); padding:10px; }
116
+ .fdc-anno-editor .fdc-anno-quote { font-size:12px; color:var(--dsw-alias-label-secondary,#666); background:var(--dsw-alias-fill-tsp-secondary,#f5f5f5); border-radius:5px; padding:5px 7px; margin-bottom:8px; max-height:64px; overflow:auto; line-height:1.5; }
117
+ .fdc-anno-editor textarea { display:block; width:100%; min-height:62px; box-sizing:border-box; resize:vertical; border:1px solid var(--dsw-alias-border-l3,#ccc); border-radius:6px; padding:6px 8px; font:inherit; font-size:12px; line-height:1.55; background:transparent; color:inherit; }
118
+ .fdc-anno-editor .fdc-anno-actions { display:flex; justify-content:flex-end; gap:6px; margin-top:8px; }
119
+ .fdc-anno-panel { width:min(360px,calc(100vw - 16px)); max-height:min(72vh,540px); display:flex; flex-direction:column; }
120
+ .fdc-anno-panel header { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:9px 11px; border-bottom:1px solid var(--dsw-alias-border-l3,#eee); font-size:12px; }
121
+ .fdc-anno-panel header span { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
122
+ .fdc-anno-panel header button { flex:0 0 auto; width:22px; height:22px; padding:0; font-size:16px; line-height:20px; color:var(--dsw-alias-label-secondary,#666); }
123
+ .fdc-anno-panel header b { color:#b45309; }
124
+ .fdc-anno-list { overflow:auto; padding:6px 8px; margin:0; list-style:none; }
125
+ .fdc-anno-item { border:1px solid var(--dsw-alias-border-l3,#eee); border-radius:8px; padding:7px 8px; margin:6px 0; cursor:pointer; }
126
+ .fdc-anno-item.on { border-color:#2563eb; background:rgba(37,99,235,.05); }
127
+ .fdc-anno-item.is-sent { opacity:.62; }
128
+ .fdc-anno-item .fdc-anno-head { display:flex; align-items:center; gap:6px; font-size:11px; color:var(--dsw-alias-label-secondary,#666); }
129
+ .fdc-anno-item .fdc-anno-head em { font-style:normal; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
130
+ .fdc-anno-item .fdc-anno-head b { color:#b45309; font-weight:600; }
131
+ .fdc-anno-item .fdc-anno-text { font-size:12px; line-height:1.55; margin-top:4px; word-break:break-word; }
132
+ .fdc-anno-item .fdc-anno-note { color:var(--dsw-alias-label-secondary,#555); }
133
+ .fdc-anno-item .fdc-anno-tools { display:flex; gap:2px; }
134
+ .fdc-anno-item .fdc-anno-tools button { padding:1px 5px; font-size:11px; }
135
+ .fdc-anno-item textarea { display:block; width:100%; min-height:48px; box-sizing:border-box; margin-top:4px; border:1px solid var(--dsw-alias-border-l3,#ccc); border-radius:6px; padding:5px 7px; font:inherit; font-size:12px; background:transparent; color:inherit; resize:vertical; }
136
+ .fdc-anno-panel footer { display:flex; align-items:center; gap:6px; padding:8px 10px; border-top:1px solid var(--dsw-alias-border-l3,#eee); }
137
+ .fdc-anno-panel footer span { flex:1; min-width:0; font-size:11px; color:var(--dsw-alias-label-secondary,#666); }
138
+ .fdc-anno-empty { padding:18px 10px; text-align:center; font-size:12px; color:var(--dsw-alias-label-secondary,#666); }
139
+ .fdc-anno-toast { position:fixed; left:50%; bottom:28px; transform:translateX(-50%); z-index:1300; max-width:min(420px,calc(100vw - 24px)); padding:8px 12px; border-radius:8px; background:#1f2937; color:#fff; font-size:12px; line-height:1.5; box-shadow:0 8px 24px #0003; }
140
+ .fdc-anno-toast.is-error { background:#b42318; }
141
+ .fdc-anno-bubble[hidden],.fdc-anno-editor[hidden],.fdc-anno-panel[hidden],.fdc-anno-toast[hidden] { display:none !important; }
91
142
  `;
92
143
  document.head.appendChild(style);
93
144
  const notify = value => {
@@ -101,6 +152,705 @@ export function installDocumentCollaboration(ctx, require) {
101
152
  };
102
153
  const currentId = () => sidebar.mounted.getSnapshot();
103
154
  const active = () => { try { return sidebar.active(); } catch { return undefined; } };
155
+ // ---- Document annotations -------------------------------------------
156
+ // Marks ride the host's existing PDF text layer, so the reader keeps the
157
+ // native preview, zoom, paging and auto-refresh; only the marks and the
158
+ // review prompt are ours. Everything is stored per file path.
159
+ const ANNO_PAGE = '[data-pdf-page]';
160
+ const ANNO_TEXT = '[data-pdf-text]';
161
+ const ANNO_SURFACE = '[data-document-zoom-surface]';
162
+ let annoPath = '', annoSession = '', annoTimer = 0;
163
+ let annoBubble, annoEditor, annoPanel, annoToast, annoToastTimer, annoPending;
164
+ const bump = () => {
165
+ if (disposed) return;
166
+ revision++;
167
+ listeners.forEach(listener => listener());
168
+ };
169
+ const annotationCount = () => annoPath ? book.count(annoPath) : 0;
170
+ const annotationPage = () => annoPath ? book.items(annoPath) : [];
171
+ function annotationIndex(textEl) {
172
+ const walker = document.createTreeWalker(textEl, NodeFilter.SHOW_TEXT);
173
+ const nodes = [], starts = [];
174
+ let text = '';
175
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
176
+ if (!node.nodeValue) continue;
177
+ nodes.push(node);
178
+ starts.push(text.length);
179
+ text += node.nodeValue;
180
+ }
181
+ return { nodes, starts, text };
182
+ }
183
+ function annotationPoint(index, offset) {
184
+ let low = 0, high = index.nodes.length - 1;
185
+ while (low < high) {
186
+ const middle = (low + high + 1) >> 1;
187
+ if (index.starts[middle] <= offset) low = middle;
188
+ else high = middle - 1;
189
+ }
190
+ const node = index.nodes[low];
191
+ if (!node) return null;
192
+ return { node, offset: Math.max(0, Math.min(node.nodeValue.length, offset - index.starts[low])) };
193
+ }
194
+ // Flat text offset of a selection boundary inside the page text layer.
195
+ function annotationOffsetOf(textEl, node, offset) {
196
+ const walker = document.createTreeWalker(textEl, NodeFilter.SHOW_TEXT);
197
+ let total = 0;
198
+ for (let current = walker.nextNode(); current; current = walker.nextNode()) {
199
+ if (current === node) return total + Math.min(offset, current.nodeValue.length);
200
+ total += current.nodeValue.length;
201
+ }
202
+ return -1;
203
+ }
204
+ // Collapse whitespace the PDF text layer inserts at line breaks while
205
+ // keeping a map back to the original string, so a quote can be located
206
+ // and converted into a text Range (and therefore into page rectangles).
207
+ function annotationNormalize(text) {
208
+ let out = '', map = [], space = false;
209
+ for (let i = 0; i < text.length; i++) {
210
+ const char = text[i];
211
+ if (/\s/.test(char)) {
212
+ if (!space && out) { out += ' '; map.push(i); space = true; }
213
+ } else { out += char; map.push(i); space = false; }
214
+ }
215
+ let start = 0, end = out.length;
216
+ while (start < end && out[start] === ' ') start++;
217
+ while (end > start && out[end - 1] === ' ') end--;
218
+ return { text: out.slice(start, end), map: map.slice(start, end) };
219
+ }
220
+ function annotationRoot() {
221
+ if (annoSession && right) {
222
+ const panel = right.querySelector(`[data-sidebar-right-session="${CSS.escape(annoSession)}"][data-sidebar-right-panel]`);
223
+ if (panel) return panel;
224
+ }
225
+ return right || document;
226
+ }
227
+ function annotationPct(pageEl, range, baseRect) {
228
+ const surface = pageEl.querySelector(ANNO_SURFACE);
229
+ if (!surface) return [];
230
+ const base = baseRect || surface.getBoundingClientRect();
231
+ if (base.width < 1 || base.height < 1) return [];
232
+ const seen = new Set(), rects = [];
233
+ for (const rect of range.getClientRects()) {
234
+ if (rect.width < 1 || rect.height < 1) continue;
235
+ const value = {
236
+ x: (rect.left - base.left) / base.width,
237
+ y: (rect.top - base.top) / base.height,
238
+ w: rect.width / base.width,
239
+ h: rect.height / base.height,
240
+ };
241
+ const key = [value.x, value.y, value.w, value.h].map(number => Math.round(number * 10000)).join(':');
242
+ if (seen.has(key)) continue;
243
+ seen.add(key);
244
+ rects.push(value);
245
+ }
246
+ return rects.slice(0, 128);
247
+ }
248
+ // One normalized page text per paint pass: a page with ten marks would
249
+ // otherwise rebuild the same text index ten times.
250
+ function annotationPageIndex(pageEl, cache) {
251
+ let entry = cache?.get(pageEl);
252
+ if (!entry) {
253
+ const surface = pageEl.querySelector(ANNO_SURFACE);
254
+ const textEl = pageEl.querySelector(ANNO_TEXT);
255
+ entry = { surface, base: surface?.getBoundingClientRect(), textEl, index: null, normalized: null };
256
+ if (textEl) {
257
+ entry.index = annotationIndex(textEl);
258
+ entry.normalized = annotationNormalize(entry.index.text);
259
+ }
260
+ cache?.set(pageEl, entry);
261
+ }
262
+ return entry;
263
+ }
264
+ function annotationRects(pageEl, item, cache) {
265
+ const entry = annotationPageIndex(pageEl, cache);
266
+ const quote = normalizeQuote(item.quote);
267
+ if (entry.textEl && entry.index && entry.normalized && quote) {
268
+ const { index, normalized } = entry;
269
+ const positions = [];
270
+ for (let at = normalized.text.indexOf(quote); at >= 0; at = normalized.text.indexOf(quote, at + 1)) positions.push(at);
271
+ let chosen = positions[0];
272
+ if (positions.length > 1) {
273
+ let best = -1;
274
+ for (const at of positions) {
275
+ let score = 0;
276
+ if (item.prefix && normalized.text.slice(Math.max(0, at - item.prefix.length), at).endsWith(item.prefix)) score += 2;
277
+ if (item.suffix && normalized.text.slice(at + quote.length, at + quote.length + item.suffix.length).startsWith(item.suffix)) score += 2;
278
+ if (score > best) { best = score; chosen = at; }
279
+ }
280
+ }
281
+ if (chosen !== undefined) {
282
+ const startOffset = normalized.map[chosen];
283
+ const endOffset = normalized.map[chosen + quote.length - 1];
284
+ const start = startOffset === undefined ? null : annotationPoint(index, startOffset);
285
+ const end = endOffset === undefined ? null : annotationPoint(index, endOffset + 1);
286
+ if (start && end) {
287
+ try {
288
+ const range = document.createRange();
289
+ range.setStart(start.node, start.offset);
290
+ range.setEnd(end.node, end.offset);
291
+ const rects = annotationPct(pageEl, range, entry.base);
292
+ if (rects.length) return rects;
293
+ } catch { /* The text layer may be mid-rebuild. */ }
294
+ }
295
+ }
296
+ }
297
+ // If the text layer exists but no longer holds the quote, the document
298
+ // changed; drawing the stored rectangles would point at the wrong line.
299
+ return entry.textEl ? [] : (Array.isArray(item.rects) ? item.rects : []);
300
+ }
301
+ // A zero-length span (the reader deleted the text) has no client rects:
302
+ // draw a thin caret at the seam instead.
303
+ function annotationCaret(entry, offset) {
304
+ const { index, normalized } = entry;
305
+ if (offset === undefined || !normalized || !normalized.text.length || !entry.base) return null;
306
+ const at = Math.min(offset, normalized.text.length - 1);
307
+ const from = normalized.map[at];
308
+ if (from === undefined) return null;
309
+ const start = annotationPoint(index, from), end = annotationPoint(index, from + 1);
310
+ if (!start || !end) return null;
311
+ try {
312
+ const range = document.createRange();
313
+ range.setStart(start.node, start.offset);
314
+ range.setEnd(end.node, end.offset);
315
+ const rect = range.getBoundingClientRect();
316
+ if (!rect.height || !entry.base.width || !entry.base.height) return null;
317
+ return {
318
+ x: (rect.left - entry.base.left) / entry.base.width,
319
+ y: (rect.top - entry.base.top) / entry.base.height,
320
+ w: 2 / entry.base.width,
321
+ h: rect.height / entry.base.height,
322
+ };
323
+ } catch { return null; }
324
+ }
325
+ function annotationSpanRects(pageEl, entry, from, to) {
326
+ const { index, normalized } = entry;
327
+ if (from === undefined || from < 0) return null;
328
+ if (to - from <= 1) {
329
+ const caret = annotationCaret(entry, from);
330
+ return caret ? [caret] : null;
331
+ }
332
+ const startMap = normalized.map[from], endMap = normalized.map[to - 1];
333
+ if (startMap === undefined || endMap === undefined) return null;
334
+ const start = annotationPoint(index, startMap), end = annotationPoint(index, endMap + 1);
335
+ if (!start || !end) return null;
336
+ try {
337
+ const range = document.createRange();
338
+ range.setStart(start.node, start.offset);
339
+ range.setEnd(end.node, end.offset);
340
+ const rects = annotationPct(pageEl, range, entry.base);
341
+ if (rects.length) return rects;
342
+ const caret = annotationCaret(entry, from);
343
+ return caret ? [caret] : null;
344
+ } catch { return null; }
345
+ }
346
+ // After the agent edits the file the marked text is gone, so the mark can
347
+ // no longer be found by its quote. The chars that surrounded it normally
348
+ // survive: highlight the seam between them, which is what changed.
349
+ function annotationAnchorRects(pageEl, item, cache) {
350
+ const entry = annotationPageIndex(pageEl, cache);
351
+ const { index, normalized } = entry;
352
+ if (!entry.textEl || !index || !normalized || !normalized.text) return null;
353
+ const span = locateChangedSpan(normalized.text, item.prefix, item.suffix, item.quote);
354
+ if (!span) return null;
355
+ const rects = annotationSpanRects(pageEl, entry, span.from, span.to);
356
+ return rects ? { rects } : null;
357
+ }
358
+ function annotationLayer(pageEl) {
359
+ const surface = pageEl.querySelector(ANNO_SURFACE);
360
+ if (!surface) return null;
361
+ let layer = surface.querySelector('[data-fdc-anno-layer]');
362
+ if (!layer) {
363
+ layer = document.createElement('div');
364
+ layer.dataset.fdcAnnoLayer = '';
365
+ surface.appendChild(layer);
366
+ }
367
+ return layer;
368
+ }
369
+ function paintAnnotations() {
370
+ if (disposed) return;
371
+ const items = annotationPage();
372
+ const numbers = new Map(items.map((item, index) => [item.id, index + 1]));
373
+ const pageRoot = annotationRoot();
374
+ const pages = [...pageRoot.querySelectorAll(ANNO_PAGE)].filter(element => element.getClientRects().length > 0);
375
+ const pageOf = new Map(pages.map(element => [Number(element.getAttribute('data-pdf-page')), element]));
376
+ const cache = new Map();
377
+ const resolved = [];
378
+ for (const item of items) {
379
+ const stored = Number(item.page) || 1;
380
+ const order = [stored, stored - 1, stored + 1, stored - 2, stored + 2];
381
+ let pageEl = null, rects = [], landed = false;
382
+ // After the agent edits and repaginates the file, the same quote can
383
+ // move a page or two. Follow it instead of pointing at the old line.
384
+ for (const which of order) {
385
+ const candidate = pageOf.get(which);
386
+ if (!candidate) continue;
387
+ const found = annotationRects(candidate, item, cache);
388
+ if (found.length) { pageEl = candidate; rects = found; break; }
389
+ }
390
+ // Submitted, and the marked text is gone: the edit landed between the
391
+ // chars that surrounded it, so highlight that seam instead.
392
+ if (!rects.length && item.status === 'sent') {
393
+ for (const which of order) {
394
+ const candidate = pageOf.get(which);
395
+ if (!candidate) continue;
396
+ const changed = annotationAnchorRects(candidate, item, cache);
397
+ if (changed) { pageEl = candidate; rects = changed.rects; landed = true; break; }
398
+ }
399
+ }
400
+ if (pageEl && rects.length) resolved.push({ item, pageEl, rects, landed });
401
+ }
402
+ for (const pageEl of pages) pageEl.querySelector(`${ANNO_SURFACE} [data-fdc-anno-layer]`)?.replaceChildren();
403
+ for (const { item, pageEl, rects, landed } of resolved) {
404
+ const layer = annotationLayer(pageEl);
405
+ if (!layer) continue;
406
+ const sent = item.status === 'sent';
407
+ const kind = landed ? 'is-done' : (item.type === 'delete' ? 'is-delete' : 'is-comment');
408
+ for (const rect of rects) {
409
+ const mark = document.createElement('div');
410
+ mark.className = `fdc-anno-mark ${kind}${!landed && sent ? ' is-sent' : ''}`;
411
+ mark.dataset.fdcAnnoId = item.id;
412
+ mark.style.left = `${rect.x * 100}%`;
413
+ mark.style.top = `${rect.y * 100}%`;
414
+ mark.style.width = `${rect.w * 100}%`;
415
+ mark.style.height = `${rect.h * 100}%`;
416
+ mark.title = landed
417
+ ? `已改动(原批注:${clipQuote(item.quote, 60)})`
418
+ : `${item.type === 'delete' ? '删除' : '修改'}:${clipQuote(item.quote, 60)}`;
419
+ layer.appendChild(mark);
420
+ }
421
+ const first = rects[0];
422
+ const badge = document.createElement('button');
423
+ badge.type = 'button';
424
+ badge.className = `fdc-anno-badge${landed ? ' is-done' : ''}`;
425
+ badge.dataset.fdcAnnoId = item.id;
426
+ badge.textContent = landed ? '✓' : String(numbers.get(item.id) || '');
427
+ badge.style.left = `${(first.x + first.w) * 100}%`;
428
+ badge.style.top = `${first.y * 100}%`;
429
+ badge.title = landed ? '改动位置(点开批注)' : '打开批注';
430
+ badge.addEventListener('pointerdown', event => {
431
+ event.preventDefault();
432
+ event.stopPropagation();
433
+ openAnnotationPanel(item.id);
434
+ });
435
+ layer.appendChild(badge);
436
+ }
437
+ }
438
+ function schedulePaint() {
439
+ if (disposed || annoTimer) return;
440
+ annoTimer = setTimeout(() => { annoTimer = 0; paintAnnotations(); }, 120);
441
+ }
442
+ function selectionInfo() {
443
+ const selection = window.getSelection();
444
+ if (!selection || selection.rangeCount !== 1 || selection.isCollapsed) return null;
445
+ const range = selection.getRangeAt(0);
446
+ if (!range.toString().trim()) return null;
447
+ const startEl = range.startContainer.nodeType === 1 ? range.startContainer : range.startContainer.parentElement;
448
+ const pageEl = startEl?.closest?.(ANNO_PAGE);
449
+ if (!pageEl || !annotationRoot().contains(pageEl)) return null;
450
+ const endEl = range.endContainer.nodeType === 1 ? range.endContainer : range.endContainer.parentElement;
451
+ if (!pageEl.contains(endEl)) return null;
452
+ const quote = normalizeQuote(range.toString());
453
+ if (!quote) return null;
454
+ return { range: range.cloneRange(), pageEl, page: Number(pageEl.getAttribute('data-pdf-page')) || 1, quote };
455
+ }
456
+ function hideBubble() {
457
+ if (annoBubble) annoBubble.hidden = true;
458
+ }
459
+ function hideEditor() {
460
+ if (annoEditor) annoEditor.hidden = true;
461
+ }
462
+ function hidePanel() {
463
+ if (annoPanel) annoPanel.hidden = true;
464
+ }
465
+ function closeAnnotationUi() {
466
+ annoPending = undefined;
467
+ hideBubble();
468
+ hideEditor();
469
+ hidePanel();
470
+ }
471
+ function toast(message, error) {
472
+ if (disposed) return;
473
+ if (!annoToast) {
474
+ annoToast = document.createElement('div');
475
+ annoToast.className = 'fdc-anno-toast';
476
+ annoToast.setAttribute('role', 'status');
477
+ annoToast.setAttribute('aria-live', 'polite');
478
+ document.body.appendChild(annoToast);
479
+ }
480
+ annoToast.textContent = message;
481
+ annoToast.classList.toggle('is-error', !!error);
482
+ annoToast.hidden = false;
483
+ clearTimeout(annoToastTimer);
484
+ annoToastTimer = setTimeout(() => { if (annoToast) annoToast.hidden = true; }, 2600);
485
+ }
486
+ function placement(panel, rect) {
487
+ panel.hidden = false;
488
+ panel.style.left = '8px';
489
+ panel.style.top = '8px';
490
+ const width = panel.offsetWidth, height = panel.offsetHeight;
491
+ const left = Math.max(8, Math.min(window.innerWidth - width - 8, rect ? rect.left : window.innerWidth - width - 16));
492
+ let top = rect ? rect.bottom + 6 : Math.max(40, (window.innerHeight - height) / 2);
493
+ if (top + height > window.innerHeight - 8) top = Math.max(8, (rect ? rect.top : window.innerHeight) - height - 6);
494
+ panel.style.left = `${left}px`;
495
+ panel.style.top = `${top}px`;
496
+ }
497
+ function annotationContext(id, address) {
498
+ const path = decodeFilePath(address || '');
499
+ if (path === annoPath && id === annoSession) return;
500
+ annoPath = path;
501
+ annoSession = id || '';
502
+ closeAnnotationUi();
503
+ bump();
504
+ schedulePaint();
505
+ }
506
+ function createAnnotation(info, type, note) {
507
+ if (!annoPath) { closeAnnotationUi(); toast('当前文件不支持批注', true); return; }
508
+ if (!info.pageEl.isConnected || !annotationRoot().contains(info.pageEl)) {
509
+ closeAnnotationUi();
510
+ toast('文档已切换,批注未保存', true);
511
+ return;
512
+ }
513
+ const textEl = info.pageEl.querySelector(ANNO_TEXT);
514
+ let prefix = '', suffix = '';
515
+ if (textEl) {
516
+ const index = annotationIndex(textEl);
517
+ const normalized = annotationNormalize(index.text);
518
+ const quote = normalizeQuote(info.quote);
519
+ let at = normalized.text.indexOf(quote);
520
+ // Prefer the occurrence the reader actually selected when the same
521
+ // phrase appears more than once on the page.
522
+ const flat = annotationOffsetOf(textEl, info.range.startContainer, info.range.startOffset);
523
+ if (flat >= 0) {
524
+ const hint = normalized.map.findIndex(raw => raw >= flat);
525
+ if (hint >= 0 && normalized.text.startsWith(quote, hint)) at = hint;
526
+ }
527
+ if (at < 0) {
528
+ // Spacing differences between the selection and the text layer
529
+ // would otherwise leave the mark without anchors, and a mark
530
+ // without anchors cannot be found again after the file is edited.
531
+ const loose = locateQuoteLoose(normalized.text, quote);
532
+ if (loose) {
533
+ prefix = normalized.text.slice(Math.max(0, loose.from - 24), loose.from);
534
+ suffix = normalized.text.slice(loose.to, loose.to + 24);
535
+ }
536
+ } else {
537
+ prefix = normalized.text.slice(Math.max(0, at - 24), at);
538
+ suffix = normalized.text.slice(at + quote.length, at + quote.length + 24);
539
+ }
540
+ }
541
+ book.add(annoPath, {
542
+ page: info.page,
543
+ type,
544
+ quote: info.quote,
545
+ note,
546
+ prefix,
547
+ suffix,
548
+ rects: annotationPct(info.pageEl, info.range),
549
+ });
550
+ closeAnnotationUi();
551
+ bump();
552
+ schedulePaint();
553
+ const saved = !book.saveFailed;
554
+ toast(saved
555
+ ? (type === 'delete' ? '已加删除线' : '已保存批注')
556
+ : '批注只在本页有效(本地存储写入失败)', !saved);
557
+ }
558
+ function openAnnotationEditor(info, rect) {
559
+ annoPending = info;
560
+ if (!annoEditor) {
561
+ annoEditor = document.createElement('div');
562
+ annoEditor.className = 'fdc-anno-editor';
563
+ annoEditor.innerHTML = '<div class="fdc-anno-quote"></div><textarea placeholder="写清要怎么改,例如:把口径改成 2026 年"></textarea>' +
564
+ '<div class="fdc-anno-actions"><button type="button" data-act="cancel">取消</button><button type="button" class="primary" data-act="save">保存批注</button></div>';
565
+ annoEditor.addEventListener('pointerdown', event => event.stopPropagation());
566
+ annoEditor.querySelector('[data-act="cancel"]').addEventListener('click', () => { annoPending = undefined; hideEditor(); });
567
+ annoEditor.querySelector('[data-act="save"]').addEventListener('click', () => {
568
+ const note = annoEditor.querySelector('textarea').value;
569
+ if (!annoPending) return;
570
+ createAnnotation(annoPending, 'comment', note);
571
+ });
572
+ document.body.appendChild(annoEditor);
573
+ }
574
+ annoEditor.querySelector('.fdc-anno-quote').textContent = `「${clipQuote(info.quote, 90)}」`;
575
+ annoEditor.querySelector('textarea').value = '';
576
+ placement(annoEditor, rect);
577
+ annoEditor.querySelector('textarea').focus();
578
+ }
579
+ function renderPanel(focusId) {
580
+ if (!annoPanel) return;
581
+ const items = annotationPage();
582
+ const numbers = new Map(items.map((item, index) => [item.id, index + 1]));
583
+ const pending = items.filter(item => item.status !== 'sent').length;
584
+ annoPanel.querySelector('header b').textContent = String(items.length);
585
+ const list = annoPanel.querySelector('.fdc-anno-list');
586
+ list.replaceChildren();
587
+ if (!items.length) {
588
+ const empty = document.createElement('div');
589
+ empty.className = 'fdc-anno-empty';
590
+ empty.textContent = '还没有批注。在文档里选中文字,点「删除线」或「批注」。';
591
+ list.appendChild(empty);
592
+ }
593
+ for (const item of items) {
594
+ const row = document.createElement('li');
595
+ row.className = `fdc-anno-item${item.id === focusId ? ' on' : ''}${item.status === 'sent' ? ' is-sent' : ''}`;
596
+ row.dataset.id = item.id;
597
+ // Document text is untrusted input: every label goes through
598
+ // textContent, never innerHTML.
599
+ const head = document.createElement('div');
600
+ head.className = 'fdc-anno-head';
601
+ const title = document.createElement('b');
602
+ title.textContent = `#${numbers.get(item.id)} · 第 ${item.page} 页`;
603
+ const kind = document.createElement('em');
604
+ kind.textContent = item.type === 'delete' ? '删除' : '修改';
605
+ const tools = document.createElement('span');
606
+ tools.className = 'fdc-anno-tools';
607
+ for (const [action, label] of [['jump', '定位'], ['edit', '编辑'], ['del', '删除']]) {
608
+ const button = document.createElement('button');
609
+ button.type = 'button';
610
+ button.dataset.act = action;
611
+ button.textContent = label;
612
+ tools.appendChild(button);
613
+ }
614
+ head.append(title, kind, tools);
615
+ const quote = document.createElement('div');
616
+ quote.className = 'fdc-anno-text';
617
+ quote.textContent = `「${clipQuote(item.quote, 70)}」`;
618
+ const note = document.createElement('div');
619
+ note.className = 'fdc-anno-note';
620
+ note.textContent = item.type === 'delete'
621
+ ? (item.note || '删掉这段文字。')
622
+ : (item.note || '按意见修改这段文字。');
623
+ row.append(head, quote, note);
624
+ list.appendChild(row);
625
+ }
626
+ const pendingLabel = annoPanel.querySelector('footer span');
627
+ pendingLabel.textContent = items.length === 0 ? '还没有批注' : (pending ? `${pending} 条待提交` : '已全部提交');
628
+ annoPanel.querySelector('[data-act="submit"]').disabled = pending === 0;
629
+ annoPanel.dataset.focus = focusId || '';
630
+ }
631
+ function openAnnotationPanel(focusId, anchor) {
632
+ if (!annoPanel) {
633
+ annoPanel = document.createElement('div');
634
+ annoPanel.className = 'fdc-anno-panel';
635
+ annoPanel.setAttribute('role', 'dialog');
636
+ annoPanel.setAttribute('aria-label', '文档批注');
637
+ annoPanel.innerHTML = '<header><span>文档批注 · <b>0</b> 条</span><button type="button" data-act="close" aria-label="关闭批注面板">×</button></header><ul class="fdc-anno-list"></ul>' +
638
+ '<footer><span></span><button type="button" data-act="clear">清空</button><button type="button" class="primary" data-act="submit">提交给 AI</button></footer>';
639
+ annoPanel.addEventListener('pointerdown', event => event.stopPropagation());
640
+ annoPanel.querySelector('[data-act="close"]').addEventListener('click', hidePanel);
641
+ annoPanel.querySelector('[data-act="submit"]').addEventListener('click', submitAnnotations);
642
+ annoPanel.querySelector('[data-act="clear"]').addEventListener('click', () => {
643
+ if (!annoPath || !book.count(annoPath)) return;
644
+ if (!window.confirm(`清空「${relativeToWorkspace(annoPath, sessionCwd(annoSession)) || annoPath}」的全部批注?`)) return;
645
+ book.clear(annoPath);
646
+ bump(); renderPanel(); schedulePaint();
647
+ });
648
+ annoPanel.querySelector('.fdc-anno-list').addEventListener('click', event => {
649
+ const button = event.target.closest('button[data-act]');
650
+ const row = event.target.closest('.fdc-anno-item');
651
+ if (!row) return;
652
+ const item = annotationPage().find(entry => entry.id === row.dataset.id);
653
+ if (!item || !button) return;
654
+ event.preventDefault();
655
+ event.stopPropagation();
656
+ const action = button.dataset.act;
657
+ if (action === 'jump') {
658
+ const root = annotationRoot();
659
+ const mark = root.querySelector(`[data-fdc-anno-id="${CSS.escape(item.id)}"]`);
660
+ const pageEl = mark?.closest(ANNO_PAGE) || root.querySelector(`${ANNO_PAGE}[data-pdf-page="${item.page}"]`);
661
+ pageEl?.scrollIntoView({ block: 'center', behavior: 'smooth' });
662
+ row.classList.add('on');
663
+ } else if (action === 'del') {
664
+ book.remove(annoPath, item.id);
665
+ bump(); renderPanel(); schedulePaint();
666
+ } else if (action === 'edit') {
667
+ const note = row.querySelector('.fdc-anno-note');
668
+ if (row.querySelector('textarea')) return;
669
+ const textarea = document.createElement('textarea');
670
+ textarea.value = item.note || '';
671
+ note.replaceChildren(textarea);
672
+ const save = document.createElement('button');
673
+ save.type = 'button';
674
+ save.className = 'primary';
675
+ save.textContent = '保存';
676
+ save.style.marginTop = '4px';
677
+ save.addEventListener('click', event => {
678
+ event.stopPropagation();
679
+ book.update(annoPath, item.id, { note: textarea.value });
680
+ bump(); renderPanel(item.id); schedulePaint();
681
+ });
682
+ note.appendChild(save);
683
+ textarea.focus();
684
+ }
685
+ });
686
+ document.body.appendChild(annoPanel);
687
+ }
688
+ renderPanel(focusId);
689
+ const rect = anchor?.getBoundingClientRect?.();
690
+ placement(annoPanel, rect);
691
+ }
692
+ function sessionsService() {
693
+ for (const candidate of [scoped, ctx]) {
694
+ try {
695
+ const value = candidate?.get?.('sessions') || candidate?.sessions;
696
+ if (value) return value;
697
+ } catch { /* keep looking */ }
698
+ }
699
+ return undefined;
700
+ }
701
+ function sessionCwd(sessionId) {
702
+ try {
703
+ const rows = sessionsService()?.list?.getSnapshot?.()?.byId || {};
704
+ return rows[sessionId]?.cwd || '';
705
+ } catch { return ''; }
706
+ }
707
+ let annoSubmitting = false;
708
+ async function submitAnnotations() {
709
+ if (annoSubmitting) return;
710
+ const path = annoPath, session = annoSession;
711
+ if (!path) { toast('当前文件不支持批注', true); return; }
712
+ if (!session) { toast('会话尚未就绪,稍后再试', true); return; }
713
+ const items = book.items(path).filter(item => item.status !== 'sent')
714
+ .slice().sort((left, right) => left.page - right.page || (left.createdAt || 0) - (right.createdAt || 0));
715
+ if (!items.length) { toast('没有待提交的批注'); return; }
716
+ const file = relativeToWorkspace(path, sessionCwd(session));
717
+ const prompt = formatAnnotationPrompt(file, items);
718
+ annoSubmitting = true;
719
+ if (annoPanel) annoPanel.querySelector('[data-act="submit"]').disabled = true;
720
+ let timer;
721
+ try {
722
+ const scope = sessionsService()?.scope?.(session);
723
+ const conversation = typeof scope?.get === 'function' ? scope.get('conversation') : scope?.conversation;
724
+ if (!conversation || typeof conversation.send !== 'function') throw new Error('会话发送服务不可用');
725
+ // A stuck host channel must not leave the button disabled forever.
726
+ await Promise.race([
727
+ conversation.send(prompt),
728
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('发送超时,可能已排队')), 15000); }),
729
+ ]);
730
+ book.markSent(path, items.map(item => item.id));
731
+ if (path === annoPath) {
732
+ bump();
733
+ renderPanel();
734
+ schedulePaint();
735
+ }
736
+ toast(`已提交 ${items.length} 条批注`);
737
+ } catch (error) {
738
+ toast(`提交失败:${error?.message || error}`, true);
739
+ } finally {
740
+ clearTimeout(timer);
741
+ annoSubmitting = false;
742
+ if (annoPanel && !annoPanel.hidden) renderPanel();
743
+ }
744
+ }
745
+ function installAnnotations() {
746
+ const pointer = event => {
747
+ if (event.target instanceof Element && event.target.closest('.fdc-anno-bubble,.fdc-anno-editor,.fdc-anno-panel,.fdc-anno-toast')) return;
748
+ setTimeout(() => {
749
+ if (disposed) return;
750
+ const info = selectionInfo();
751
+ if (!info) {
752
+ if (!annoEditor || annoEditor.hidden) annoPending = undefined;
753
+ hideBubble();
754
+ return;
755
+ }
756
+ annoPending = info;
757
+ if (!annoBubble) {
758
+ annoBubble = document.createElement('div');
759
+ annoBubble.className = 'fdc-anno-bubble';
760
+ annoBubble.innerHTML = '<button type="button" data-act="delete">删除线</button><button type="button" data-act="comment">批注</button>';
761
+ annoBubble.addEventListener('pointerdown', event => event.preventDefault());
762
+ annoBubble.querySelector('[data-act="delete"]').addEventListener('click', () => {
763
+ if (annoPending) createAnnotation(annoPending, 'delete', '');
764
+ });
765
+ annoBubble.querySelector('[data-act="comment"]').addEventListener('click', () => {
766
+ if (!annoPending) return;
767
+ const rect = annoBubble.getBoundingClientRect();
768
+ openAnnotationEditor(annoPending, rect);
769
+ hideBubble();
770
+ });
771
+ document.body.appendChild(annoBubble);
772
+ }
773
+ annoBubble.hidden = false;
774
+ placement(annoBubble, info.range.getBoundingClientRect());
775
+ }, 0);
776
+ };
777
+ const scroll = () => {
778
+ if (annoEditor && !annoEditor.hidden) return;
779
+ annoPending = undefined;
780
+ hideBubble();
781
+ };
782
+ const escape = event => { if (event.key === 'Escape') closeAnnotationUi(); };
783
+ const outside = event => {
784
+ if (!(event.target instanceof Element)) return;
785
+ if (event.target.closest('.fdc-anno-panel,.fdc-anno-editor,.fdc-anno-bubble,[data-fdc-anno-toggle]')) return;
786
+ hidePanel();
787
+ if (annoEditor && !annoEditor.hidden) { annoPending = undefined; hideEditor(); }
788
+ hideBubble();
789
+ };
790
+ const resize = () => { hidePanel(); hideBubble(); };
791
+ const changes = new MutationObserver(records => {
792
+ for (const record of records) {
793
+ if (record.type === 'attributes') {
794
+ if (record.target.matches?.(ANNO_SURFACE) || record.target.matches?.(ANNO_PAGE)) {
795
+ schedulePaint();
796
+ return;
797
+ }
798
+ continue;
799
+ }
800
+ const nodes = [...record.addedNodes, ...record.removedNodes];
801
+ if (nodes.some(node => node instanceof Element && (node.matches(ANNO_PAGE) || node.matches(ANNO_TEXT) || node.matches(ANNO_SURFACE) || node.matches('[data-fdc-anno-layer]') || !!node.closest(ANNO_TEXT)))) {
802
+ schedulePaint();
803
+ return;
804
+ }
805
+ }
806
+ });
807
+ changes.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['hidden'] });
808
+ // `storage` fires only in other windows/tabs; apply the exact record and
809
+ // repaint so both windows converge without a reload.
810
+ const storage = event => {
811
+ if (event.key === null) {
812
+ book.reload();
813
+ model.reload();
814
+ bump();
815
+ schedulePaint();
816
+ if (annoPanel && !annoPanel.hidden) renderPanel();
817
+ schedule();
818
+ return;
819
+ }
820
+ let changed = false;
821
+ if (event.key === 'dsh.document-view.v1') { model.reload(); changed = true; }
822
+ if (book.applyStorageEvent(event.key, event.newValue)) changed = true;
823
+ if (!changed) return;
824
+ bump();
825
+ schedulePaint();
826
+ if (annoPanel && !annoPanel.hidden) renderPanel();
827
+ if (event.key === 'dsh.document-view.v1') schedule();
828
+ };
829
+ window.addEventListener('storage', storage);
830
+ document.addEventListener('mouseup', pointer, true);
831
+ document.addEventListener('keyup', pointer, true);
832
+ document.addEventListener('scroll', scroll, true);
833
+ document.addEventListener('keydown', escape, true);
834
+ document.addEventListener('pointerdown', outside, true);
835
+ window.addEventListener('resize', resize);
836
+ return () => {
837
+ changes.disconnect();
838
+ document.removeEventListener('mouseup', pointer, true);
839
+ document.removeEventListener('keyup', pointer, true);
840
+ document.removeEventListener('scroll', scroll, true);
841
+ document.removeEventListener('keydown', escape, true);
842
+ document.removeEventListener('pointerdown', outside, true);
843
+ window.removeEventListener('resize', resize);
844
+ window.removeEventListener('storage', storage);
845
+ clearTimeout(annoTimer);
846
+ annoBubble?.remove();
847
+ annoEditor?.remove();
848
+ annoPanel?.remove();
849
+ annoToast?.remove();
850
+ clearTimeout(annoToastTimer);
851
+ };
852
+ }
853
+
104
854
  function clearIntent() {
105
855
  pendingIntent = undefined;
106
856
  clearTimeout(intentTimer);
@@ -109,6 +859,33 @@ export function installDocumentCollaboration(ctx, require) {
109
859
  if (drag?.changed) model.save();
110
860
  drag = undefined;
111
861
  }
862
+ // The host's built-in HTML preview is a DOMPurify-sanitized document with
863
+ // CSP `script-src 'none'` and an empty sandbox, so any single-file page
864
+ // that lays itself out with inline JS (a deck calling fit()) never runs
865
+ // The host renders HTML previews inside an empty sandbox with CSP
866
+ // `script-src 'none'`, so every inline script is dead and a page that sizes
867
+ // itself with JS stays at its intrinsic width and gets clipped. The host
868
+ // ships its own escape hatch — an "临时解锁(不安全)" control that switches the
869
+ // preview to the scripted blob renderer. Drive that instead of re-rendering
870
+ // the sanitized markup ourselves: the page keeps its own paging and fit().
871
+ const unlockTried = new WeakSet();
872
+ function unlockHtmlPreview() {
873
+ const host = document.querySelector('iframe[data-html-preview]:not([data-fdc-html])');
874
+ if (!host || host.getAttribute('sandbox') !== '') return;
875
+ if (unlockTried.has(host)) return;
876
+ const panel = document.querySelector('[data-rightbar-col]') || host.parentElement;
877
+ if (!panel) return;
878
+ const scope = panel || document;
879
+ const clickable = scope.querySelectorAll('button,[role="button"]');
880
+ for (const node of clickable) {
881
+ const label = ((node.textContent || '') + ' ' + (node.getAttribute('aria-label') || '')).trim();
882
+ if (label.includes('临时解锁') || /unlock/i.test(label)) {
883
+ node.click();
884
+ unlockTried.add(host);
885
+ return;
886
+ }
887
+ }
888
+ }
112
889
  function consumeIntent(id, address) {
113
890
  if (!pendingIntent) return;
114
891
  const intent = pendingIntent;
@@ -156,7 +933,7 @@ export function installDocumentCollaboration(ctx, require) {
156
933
  }
157
934
  if (model.session(id).enabled && !sidebar.isExpanded()) {
158
935
  try {
159
- if (isDocument(tab?.contentId) || tab?.kind === 'files') sidebar.toggleExpanded();
936
+ if (isDocument(tab?.contentId) || tab?.kind === 'files' || tab?.kind === 'browser') sidebar.toggleExpanded();
160
937
  else sidebar.openTab('files');
161
938
  } catch { /* The arriving session may not have adopted its sidebar yet. */ }
162
939
  }
@@ -194,9 +971,18 @@ export function installDocumentCollaboration(ctx, require) {
194
971
  if (!id) return null;
195
972
  const state = model.session(id);
196
973
  const h = React.createElement;
197
- if (documentSeat) return state.enabled ? h('div', {className:'fdc-control'}, h('button', {
198
- type:'button', 'aria-label':'退出文档协作', onClick:() => toggle(id)
199
- }, '退出协作')) : null;
974
+ if (documentSeat) {
975
+ const count = annotationCount();
976
+ return h('div', { className:'fdc-control' },
977
+ h('button', { type:'button', title:'在文档里划线批注,汇总后一键交给 AI', 'data-fdc-anno-toggle':'',
978
+ onClick:event => {
979
+ if (annoPanel && !annoPanel.hidden) { hidePanel(); return; }
980
+ openAnnotationPanel(undefined, event.currentTarget);
981
+ } }, count ? `批注 ${count}` : '批注'),
982
+ state.enabled ? h('button', {
983
+ type:'button', 'aria-label':'退出文档协作', onClick:() => toggle(id)
984
+ }, '退出协作') : null);
985
+ }
200
986
  const icon = h('svg', {width:14,height:14,viewBox:'0 0 16 16',fill:'none','aria-hidden':true},
201
987
  h('rect',{x:2,y:2,width:12,height:12,rx:2,stroke:'currentColor'}),h('path',{d:'M9 2v12',stroke:'currentColor'}));
202
988
  return h('div', { className:'fdc-control' },
@@ -382,6 +1168,7 @@ export function installDocumentCollaboration(ctx, require) {
382
1168
  compact.appendChild(button);
383
1169
  }
384
1170
  frame.append(divider, compact);
1171
+ schedulePaint();
385
1172
  }
386
1173
  if (observedFrame !== frame) { resize.disconnect(); resize.observe(frame); observedFrame = frame; observedPanel = undefined; }
387
1174
  markHeader();
@@ -397,13 +1184,16 @@ export function installDocumentCollaboration(ctx, require) {
397
1184
  const address = tab?.contentId || '';
398
1185
  const state = model.session(id);
399
1186
  const inventory = sidebar.openTabs.getSnapshot();
400
- const docs = inventory.filter(entry => entry.sessionId === id && isDocument(entry.contentId)).length;
1187
+ const sessionRoot = document.querySelector(`[data-sidebar-right-session="${CSS.escape(id)}"]`) || right || document;
1188
+ const htmlPreview = !!sessionRoot.querySelector('iframe[data-html-preview]');
1189
+ const docs = inventory.filter(entry => entry.sessionId === id && isDocument(entry.contentId)).length + (htmlPreview ? 1 : 0);
401
1190
  model.observeCount(id, docs);
402
1191
  consumeIntent(id, address);
403
1192
  const expanded = sidebar.isExpanded();
404
1193
  const changed = id !== lastSession || address !== lastAddress;
405
1194
  if (changed) narrowView = 'document';
406
1195
  lastSession = id; lastAddress = address;
1196
+ annotationContext(id, address);
407
1197
  const shellReady = markShell();
408
1198
  const panel = right?.querySelector(`[data-sidebar-right-session="${CSS.escape(id)}"][data-sidebar-right-panel]`);
409
1199
  if (observedPanel !== panel) {
@@ -417,9 +1207,15 @@ export function installDocumentCollaboration(ctx, require) {
417
1207
  // On wide windows, a native fullscreen request is respected. On narrow
418
1208
  // windows, native auto-fullscreen is adapted to the document/chat switch.
419
1209
  const fullscreen = panel?.getAttribute('data-sidebar-right-panel') === 'fullscreen' && !geometry.narrow;
420
- const visible = shellReady && state.enabled && expanded && !fullscreen && (isDocument(address) || tab?.kind === 'files');
1210
+ const visible = shellReady && state.enabled && expanded && !fullscreen && (isDocument(address) || htmlPreview || tab?.kind === 'files' || tab?.kind === 'browser');
1211
+ // The preview panel fills the visible column through CSS (absolute inset
1212
+ // 0), so the iframe's viewport equals what the user sees and a page that
1213
+ // sizes itself from it lands centred instead of clipped.
421
1214
  if (visible) {
422
1215
  frame.setAttribute('data-fdc-active','');
1216
+ // Only drive the host's script-unlock control after the reader
1217
+ // explicitly entered collaboration mode for this HTML preview.
1218
+ if (htmlPreview) unlockHtmlPreview();
423
1219
  const columns = geometry.narrow ? `${left}px minmax(0,1fr) 0px` : `${left}px minmax(0,1fr) ${geometry.chat}px`;
424
1220
  if (frame.style.getPropertyValue('--fdc-columns') !== columns) frame.style.setProperty('--fdc-columns', columns);
425
1221
  if (geometry.narrow) frame.setAttribute('data-fdc-narrow', narrowView);
@@ -450,7 +1246,7 @@ export function installDocumentCollaboration(ctx, require) {
450
1246
  function viewGesture(event) {
451
1247
  if (!event.isTrusted) return;
452
1248
  const target = event.target instanceof Element ? event.target : document.activeElement;
453
- if (!target || target.closest('.fdc-control,[data-fdc-compact],[data-fdc-divider]')) return;
1249
+ if (!target || target.closest('.fdc-control,[data-fdc-compact],[data-fdc-divider],.fdc-anno-badge,[data-fdc-anno-layer]')) return;
454
1250
  if (event.type === 'keydown' && !['Enter',' '].includes(event.key)) return;
455
1251
  if (target.closest('[data-dockkit-tab-close]')) return;
456
1252
  const tabNode = target.closest('[data-dockkit-tab]');
@@ -481,7 +1277,7 @@ export function installDocumentCollaboration(ctx, require) {
481
1277
  if (columns !== nativeColumns) { nativeColumns = columns; schedule(); }
482
1278
  });
483
1279
  let nativeColumns = '';
484
- const structuralSelector = '[data-rightbar-col],[data-sidebar-right-panel],[data-excel-preview],[data-slot="conversation.session.header.actions"],.fortune-zoom-container';
1280
+ const structuralSelector = '[data-rightbar-col],[data-sidebar-right-panel],[data-excel-preview],iframe[data-html-preview],[data-slot="conversation.session.header.actions"],.fortune-zoom-container';
485
1281
  const observer = new MutationObserver(records => {
486
1282
  if (records.some(record => {
487
1283
  if (record.type === 'attributes') {
@@ -500,6 +1296,7 @@ export function installDocumentCollaboration(ctx, require) {
500
1296
  document.addEventListener('keydown', manualZoom, true);
501
1297
  document.addEventListener('click', sheetGesture, true);
502
1298
  document.addEventListener('contextmenu', sheetGesture, true);
1299
+ const annoDispose = installAnnotations();
503
1300
  const unsubMounted = sidebar.mounted.subscribe(schedule);
504
1301
  const unsubTabs = sidebar.openTabs.subscribe(schedule);
505
1302
  const disposers = [];
@@ -518,6 +1315,7 @@ export function installDocumentCollaboration(ctx, require) {
518
1315
  document.removeEventListener('click',sheetGesture,true);
519
1316
  document.removeEventListener('contextmenu',sheetGesture,true);
520
1317
  unsubMounted(); unsubTabs(); disposers.forEach(dispose => dispose());
1318
+ annoDispose();
521
1319
  removeGeometry(); center?.removeAttribute('data-fdc-center'); divider?.remove(); compact?.remove(); style.remove(); listeners.clear();
522
1320
  for (const [node,attribute] of headerMarks) node.removeAttribute(attribute);
523
1321
  headerMarks.clear();