-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathclient.js
More file actions
2206 lines (2118 loc) · 104 KB
/
Copy pathclient.js
File metadata and controls
2206 lines (2118 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// annotation-for-dsh 的浏览器端 half(client bundle)。
//
// 手写 CJS + ModuleLoader 包装(同 omdsh-dev navbar/greeter 模式,零构建
// 步骤):纯 DOM 自渲染,无任何 @deepseek-ai 值导入(bundle purity gate 合规);
// cordis 服务经 exports.inject 的字符串名接入(sessions / conversation / locale)。
//
// v1.4.x · 自包含批注流(取代 v0.9 chip 设计与 v1.0 发送面板):
// 1. 选中助手文字 → 工具条「批注」→ 写批注(可留空 = 仅标记原文)
// 2. 保存后原文亮蓝编号 + 高亮(纯视觉,不弹窗);跨消息/跨回合连续累积
// 3. 输入框旁「批注 ×N」标签:悬浮可见全部内容、可逐条删除
// 4. 回车发送:capture 阶段拦截 Enter(IME 守卫对齐官方 InputBar:isComposing /
// keyCode 229 + compositionend 后短延迟 latch)→ 批注块 prepend 进草稿
// (setDraft,不覆盖用户文字)→ composer 正常提交
// 5. 用户气泡不显示批注块:MutationObserver 微任务阶段(绘制前)按最后一个
// 「提问:」切掉批注块、贴「批注 ×N」标签(hover 可见);1s 轮询兜底 +
// 历史消息自动修复(用户气泡是 MessageText 单文本节点,非 markdown)
// 6. 回复逐条对照:批注块末尾注入格式指令,模型按「Annotation N:…」逐条
// 回应;回复渲染完成(data-streaming 移除)后把「Annotation N:」替换为
// 可悬浮芯片(数据取最近一条带标签用户消息的 tag.__annotationItems,刷新
// 自动重建;改 DOM 前先快照 TreeWalker 收集的文本节点再逐个替换,遍历
// 中途 replaceChild 会让 walker 指针失效)
// 7. 语言跟随 DSH locale 服务(v1.4):UI 文案与协议块 zh/en 双语、实时切换,
// 隐藏手术与反解析同时兼容「提问:」/「Ask:」与「问题:」老格式
//
// 消息格式(zh):我批注了以下 N 处内容…\n\n1. 原文\n 批注:…\n\n
// 请用「Annotation 1:…」…\n\n提问:
// (en 用 I annotated the following N passage(s)… + Note: … + Ask:;
// zh 分隔标记用「提问:」而非「问题:」——标题行「回答我的问题:」里也含
// 它,气泡隐藏手术会误命中)
//
// 发送清空只认 watchInputDraft 的「草稿有→空」迁移(未就绪时订阅重试补齐);
// 气泡装饰走 MutationObserver + 轮询,只负责隐藏/贴标签,绝不清空待发送批注
// (历史消息重装饰与刚发送在 DOM 上不可区分,见 decorateAll)。
//
// 判别式与 omdsh-dev/navbar 一致:助手行 = [data-time-hover-root] 且不含
// user bubble([class*="bubble"])。
// focus-chat(@dingyi222666/dsh-focus-chat)兼容:其会话视图挂载在
// [data-focus-flow] 内,助手行 = class 含 "assistant" 的容器(CSS Modules
// 哈希名形如 `<hash>_assistant`,流式期间行自带 data-streaming),用户行
// 沿用 data-time-hover-root;切换视图 tab 时主视图会卸载,故行判别必须
// 同时覆盖两种视图结构(见 assistantRows / allMessageRows / assistantRowOf)。
window.__ModuleLoader__.load({
// 必须与 package.json "name" 完全一致,否则 client-modules 报:
// bundle loaded without registering "@changfenhuang/dsh-annotation"
id: '@changfenhuang/dsh-annotation',
factory: (require) => {
'use strict'
var module = { exports: {} }
var exports = module.exports
// ============================== 样式 ==============================
var STYLE_ID = 'annotation-for-dsh-style'
if (document.getElementById(STYLE_ID) === null) {
var style = document.createElement('style')
style.id = STYLE_ID
style.textContent = [
'[data-annotation-for-dsh] { all: initial; }',
'[data-annotation-for-dsh] * { box-sizing: border-box; }',
'.dsh-ann-bar { position: fixed; z-index: 1200; display: flex; align-items: center;',
' gap: 2px; padding: 4px; border-radius: 12px;',
' border: 1px solid var(--dsw-alias-border-inverted);',
' background: var(--dsw-specific-menu, #2c2c2e);',
' box-shadow: var(--dsw-shadow-lv3);',
' font-family: var(--dsw-font-family, system-ui);',
' animation: dsh-ann-pop .12s var(--ds-ease-in-out, ease); }',
'@keyframes dsh-ann-pop { from { opacity: 0; transform: translateY(3px); }',
' to { opacity: 1; transform: none; } }',
'.dsh-ann-ghost { display: inline-flex; align-items: center; gap: 5px; height: 28px;',
' padding: 0 10px; border: none; border-radius: 14px; background: transparent;',
' color: var(--dsw-alias-label-primary); font-family: inherit;',
' font-size: 12px; line-height: 18px; cursor: pointer; }',
'.dsh-ann-ghost:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }',
'.dsh-ann-ghost:disabled { opacity: .45; cursor: default; }',
'.dsh-ann-ghost svg { width: 14px; height: 14px; }',
'.dsh-ann-action { display: inline-flex; align-items: center; gap: 5px; height: 28px;',
' padding: 0 12px; border: none; border-radius: 14px;',
' background: var(--dsw-alias-button-primary-fill);',
' color: var(--dsw-alias-label-primary-foreground);',
' font-family: inherit; font-size: 12px; line-height: 18px; cursor: pointer; }',
'.dsh-ann-action:hover:not(:disabled) { background: var(--dsw-alias-button-primary-hover); }',
'.dsh-ann-action:disabled { opacity: .4; cursor: default; }',
'.dsh-ann-action svg { width: 14px; height: 14px; }',
'.dsh-ann-icon { display: inline-flex; align-items: center; justify-content: center;',
' width: 28px; height: 28px; padding: 0; border: none; border-radius: 28px;',
' background: transparent; color: var(--dsw-alias-label-tertiary); cursor: pointer; }',
'.dsh-ann-icon:hover { background: var(--dsw-alias-interactive-bg-hover);',
' color: var(--dsw-alias-label-secondary); }',
'.dsh-ann-icon svg { width: 14px; height: 14px; }',
'.dsh-ann-card { position: fixed; z-index: 1201; width: 400px;',
' max-width: calc(100vw - 16px); padding: 12px; border-radius: 12px;',
' border: 1px solid var(--dsw-alias-border-inverted);',
' background: var(--dsw-specific-menu, #2c2c2e);',
' box-shadow: var(--dsw-shadow-lv3);',
' font-family: var(--dsw-font-family, system-ui);',
' animation: dsh-ann-pop .12s var(--ds-ease-in-out, ease); }',
'.dsh-ann-card-head { display: flex; align-items: center; justify-content: space-between;',
' margin-bottom: 8px; }',
'.dsh-ann-card-title { font-size: 13px; font-weight: 600;',
' color: var(--dsw-alias-label-primary); }',
'.dsh-ann-quote { font-size: 12px; line-height: 1.55;',
' color: var(--dsw-alias-label-tertiary);',
' border-left: 2px solid var(--dsw-alias-border-inverted);',
' background: var(--dsw-alias-bg-layer-1);',
' border-radius: 0 8px 8px 0; padding: 6px 10px; margin-bottom: 8px;',
' max-height: 72px; overflow: hidden; word-break: break-word;',
' display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; }',
'.dsh-ann-quotes { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px;',
' max-height: 150px; overflow-y: auto; }',
'.dsh-ann-qitem { display: flex; align-items: flex-start; gap: 8px; padding: 6px 8px;',
' border-radius: 8px; background: var(--dsw-alias-bg-layer-1); }',
'.dsh-ann-qnum { flex: none; display: inline-flex; align-items: center; justify-content: center;',
' width: 16px; height: 16px; margin-top: 1px; border-radius: 8px;',
' background: var(--dsw-alias-text-accent, #4c9aff); color: #fff;',
' font-size: 10px; font-weight: 700; }',
'.dsh-ann-qbody { flex: 1; min-width: 0; }',
'.dsh-ann-qtext { font-size: 12px; line-height: 1.5;',
' color: var(--dsw-alias-label-tertiary); max-height: 36px; overflow: hidden;',
' word-break: break-word; display: -webkit-box; -webkit-line-clamp: 2;',
' -webkit-box-orient: vertical; }',
'.dsh-ann-qnote { font-size: 11px; line-height: 1.5; margin-top: 2px;',
' color: var(--dsw-alias-label-secondary); max-height: 34px; overflow: hidden;',
' word-break: break-word; white-space: pre-wrap; display: -webkit-box;',
' -webkit-line-clamp: 2; -webkit-box-orient: vertical; }',
'.dsh-ann-qdel { flex: none; display: inline-flex; align-items: center; justify-content: center;',
' width: 18px; height: 18px; padding: 0; border: none; border-radius: 9px;',
' background: transparent; color: var(--dsw-alias-label-tertiary); cursor: pointer; }',
'.dsh-ann-qdel:hover { background: var(--dsw-alias-interactive-bg-hover);',
' color: var(--dsw-alias-label-secondary); }',
'.dsh-ann-qdel svg { width: 10px; height: 10px; }',
'.dsh-ann-input { width: 100%; min-height: 64px; padding: 8px 10px;',
' border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px;',
' background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary);',
' font-family: inherit; font-size: 13px; line-height: 20px;',
' outline: none; resize: vertical; transition: border-color .15s ease; }',
'.dsh-ann-input:focus { border-color: var(--dsw-alias-text-accent, #4c9aff); }',
'.dsh-ann-input::placeholder { color: var(--dsw-alias-label-dimmed); }',
'.dsh-ann-row { display: flex; gap: 8px; margin-top: 10px; justify-content: flex-end; }',
'.dsh-ann-cancel { display: inline-flex; align-items: center; height: 28px; padding: 0 12px;',
' border: 1px solid var(--dsw-alias-border-l2); border-radius: 14px;',
' background: transparent; color: var(--dsw-alias-label-primary);',
' font-family: inherit; font-size: 12px; cursor: pointer; }',
'.dsh-ann-cancel:hover { background: var(--dsw-alias-interactive-bg-hover); }',
'.dsh-ann-error { color: var(--dsw-alias-state-error-primary, #ff7a7a);',
' font-size: 12px; margin-top: 8px; word-break: break-word; }',
'.dsh-ann-hl { position: fixed; z-index: 900; background: rgba(255, 195, 0, .15);',
' border-radius: 2px; pointer-events: none; animation: dsh-ann-fadein .15s ease; }',
'.dsh-ann-num { position: fixed; z-index: 940; display: inline-flex; align-items: center;',
' justify-content: center; min-width: 16px; height: 16px; padding: 0 4px;',
' border-radius: 8px; border: 1px solid rgba(255, 255, 255, .3);',
' background: var(--dsw-alias-text-accent, #4c9aff); color: #fff;',
' font-family: var(--dsw-font-family, system-ui); font-size: 10px; font-weight: 700;',
' box-shadow: 0 1px 4px rgba(0,0,0,.35); pointer-events: auto; cursor: pointer;',
' transition: filter .12s ease; }',
'.dsh-ann-num:hover { filter: brightness(1.15); }',
'body:has([role="dialog"][aria-modal="true"]) [data-annotation-overlay] { display: none; }',
'.dsh-ann-tip { animation: dsh-ann-pop .12s var(--ds-ease-in-out, ease); }',
'@keyframes dsh-ann-fadein { from { opacity: 0; } to { opacity: 1; } }',
].join('\n')
document.head.appendChild(style)
}
// ============================== i18n(zh / en) ==============================
// UI 文案与批注协议块双语化:当前语言由 DSH 的 locale 服务驱动
// (ctx.locale.getSnapshot().active + subscribe()),服务缺失时回退 zh。
// 历史消息的隐藏手术与反解析同时兼容 zh/en 标记,跨语言切换不丢批注。
var STR = {
zh: {
actions: {
annotate: '批注',
already: '已批注',
annotateTitle: '为选中的内容写一条批注',
alreadyTitle: '这段内容已在批注清单中',
},
edit: {
addTitle: '添加批注',
editTitle: '编辑批注',
placeholder: '写下批注…(可留空,保存后仅标记原文)',
save: '保存批注',
},
common: { cancel: '取消' },
error: { noSelection: '没有选中的内容' },
chip: { count: '条批注' },
tip: { title: '批注({n} 条)', notePrefix: '批注:', del: '删' },
bubble: { tag: '批注 ×{n}', title: '本消息携带批注({n} 条)' },
reply: {
headWithQuote: '批注 {n} 的原文',
headNoQuote: '批注 {n}',
notePrefix: '你的批注:',
missing: '(未找到对应批注条目)',
},
toast: {
attachFail: '批注拼稿失败,消息将不带批注发送:',
skipCommand: '本条是斜杠命令,未拼入批注;批注已保留,将随下一条消息发送',
},
block: {
head: '我批注了以下 {n} 处内容(编号与原文对应),请针对它们回答我的问题:',
notePrefix: '批注:',
format: '请用「Annotation 1:…」到「Annotation {n}:…」的格式,逐条回应上面每一条批注,最后再回答我的问题。',
marker: '提问:',
},
},
en: {
actions: {
annotate: 'Annotate',
already: 'Annotated',
annotateTitle: 'Write a note about the selected text',
alreadyTitle: 'This passage is already in your annotation list',
},
edit: {
addTitle: 'Add annotation',
editTitle: 'Edit annotation',
placeholder: 'Write a note… (optional; saving only marks the passage)',
save: 'Save annotation',
},
common: { cancel: 'Cancel' },
error: { noSelection: 'No text selected' },
chip: { count: ' annotation(s)' },
tip: { title: 'Annotations ({n})', notePrefix: 'Note: ', del: 'Del' },
bubble: { tag: 'Annotations ×{n}', title: 'This message carries {n} annotation(s)' },
reply: {
headWithQuote: 'Source of annotation {n}',
headNoQuote: 'Annotation {n}',
notePrefix: 'Your note: ',
missing: '(no matching annotation found)',
},
toast: {
attachFail: 'Failed to attach annotations; the message will be sent without them: ',
skipCommand: 'Slash command detected — annotations stay pending and will attach to your next message',
},
block: {
head: 'I annotated the following {n} passage(s) (the numbers match the quotes below); please respond to them when answering my question:',
notePrefix: 'Note: ',
format: 'Please respond to each annotation in the format "Annotation 1: …" through "Annotation {n}: …", then answer my question.',
marker: 'Ask:',
},
},
}
var currentLang = 'zh'
function setLang(id) {
currentLang = (id === 'en' || id === 'zh') ? id : 'zh'
}
function dictVal(lang, key) {
var cur = STR[lang]
var parts = key.split('.')
for (var i = 0; i < parts.length; i++) {
if (cur === undefined || cur === null) return undefined
cur = cur[parts[i]]
}
return cur
}
/** @param {string} key @param {Object<string, string|number>} [params] */
function t(key, params) {
var s = dictVal(currentLang, key)
if (s === undefined) s = dictVal('zh', key)
if (s === undefined) s = key
if (params !== undefined && params !== null) {
for (var k in params) {
if (Object.prototype.hasOwnProperty.call(params, k)) {
s = s.split('{' + k + '}').join(String(params[k]))
}
}
}
return s
}
// 批注块头部哨兵(zh/en 都识别;兼容历史消息与跨语言切换)。
var BLOCK_HEADS = { zh: '我批注了以下', en: 'I annotated the following' }
function hasAnnotationBlock(text) {
return text.indexOf(BLOCK_HEADS.zh) !== -1 || text.indexOf(BLOCK_HEADS.en) !== -1
}
// 气泡隐藏手术的分隔标记:当前语言优先,另保留另一语言与「问题:」老格式。
var BLOCK_MARKERS = {
zh: ['\n提问:', '提问:', '\n问题:', '问题:'],
en: ['\nAsk:', 'Ask:'],
}
function blockMarkers() {
return currentLang === 'en'
? BLOCK_MARKERS.en.concat(BLOCK_MARKERS.zh)
: BLOCK_MARKERS.zh.concat(BLOCK_MARKERS.en)
}
// 反解析用的段落级分隔标记(批注块按协议生成,均以 \n\n 开头)。
var PARSE_MARKERS = ['\n\n提问:', '\n\n问题:', '\n\nAsk:']
// ============================== 工具 ==============================
// 助手行判别:0810 snapshot 起助手消息行 = ChatNodeSeat 上的
// data-chat-flow-kind="assistant-step"(旧版 data-time-hover-root 已不再
// 出现在助手消息主体上,只留在用户行与 turn 尾节点);保留旧判别式兜底
// 兼容回滚旧 snapshot,并排除新版 data-turn-tail 误判。
function isAssistantRow(el) {
if (el.matches('[data-chat-flow-kind="assistant-step"]')) return true
return el.hasAttribute('data-time-hover-root')
&& el.querySelector('[class*="bubble"]') === null
&& !el.hasAttribute('data-turn-tail')
}
// ---------- focus-chat(@dingyi222666/dsh-focus-chat)视图兼容 ----------
// 该插件在 conversation.view 槽注册「聚焦会话」视图:挂载于
// [data-focus-flow](列容器)→ [data-focus-anchor-key](行包装)→ 行。
// 助手行 = class 含 "assistant" 的容器(CSS Modules 哈希名保留 local 名,
// 形如 `<hash>_assistant`;流式期间行自带 data-streaming,停流后移除)。
// 用户行保留 data-time-hover-root + [class*="bubble"],与旧判别式一致。
function isFocusFlow(el) {
return el !== null && typeof el.closest === 'function'
&& el.closest('[data-focus-flow]') !== null
}
function isFocusAssistantRow(el) {
if (el === null || !el.classList || !isFocusFlow(el)) return false
for (var i = 0; i < el.classList.length; i++) {
if (el.classList[i].indexOf('assistant') !== -1) return true
}
return false
}
/** focus 视图的全部消息行(用户 + 助手,DOM 顺序)。只保留最外层助手
* 容器(markdown 内部子元素也可能带含 assistant 的类名)。 */
function focusMessageRows() {
var flow = document.querySelector('[data-focus-flow]')
if (flow === null) return []
var out = []
var all = flow.querySelectorAll('[data-time-hover-root], [class*="assistant"]')
for (var i = 0; i < all.length; i++) {
var el = all[i]
if (el.hasAttribute('data-time-hover-root')) {
if (!isAssistantRow(el)) out.push(el)
continue
}
if (!isFocusAssistantRow(el)) continue
var p = el.parentElement
if (p !== null && p !== flow && isFocusAssistantRow(p)) continue
out.push(el)
}
return out
}
function assistantRowOf(node) {
var el = (node instanceof Element) ? node : (node !== null ? node.parentElement : null)
while (el !== null && el !== document.body) {
if (el.hasAttribute('data-chat-flow-kind')) {
return el.getAttribute('data-chat-flow-kind') === 'assistant-step' ? el : null
}
if (el.hasAttribute('data-time-hover-root')) {
return isAssistantRow(el) ? el : null
}
if (isFocusAssistantRow(el)) {
// 冒到最外层 focus 助手容器(内部子元素可能也含 assistant 类名)。
while (el.parentElement !== null && el.parentElement !== document.body
&& isFocusAssistantRow(el.parentElement)) {
el = el.parentElement
}
return el
}
el = el.parentElement
}
return null
}
function assistantRows() {
var modern = document.querySelectorAll('[data-chat-flow-kind="assistant-step"]')
if (modern.length > 0) return Array.prototype.slice.call(modern)
var focus = focusMessageRows().filter(isFocusAssistantRow)
if (focus.length > 0) return focus
return Array.prototype.slice.call(document.querySelectorAll('[data-time-hover-root]'))
.filter(isAssistantRow)
}
/** 全部消息行(用户 + 助手 + 其它节点):新版走 data-chat-flow-kind,
* 旧版回退 data-time-hover-root;focus-chat 视图单独按 DOM 顺序收集
* (会话视图 tab 切换时主视图会卸载,两种结构不同时存在)。
* 用于气泡装饰、批注条目回溯。 */
function allMessageRows() {
var modern = document.querySelectorAll('[data-chat-flow-kind]')
if (modern.length > 0) return Array.prototype.slice.call(modern)
var focus = focusMessageRows()
if (focus.length > 0) return focus
return Array.prototype.slice.call(document.querySelectorAll('[data-time-hover-root]'))
}
/** 由字符偏移在元素内构造 Range(跨文本节点)。 */
function rangeFromOffset(el, offset, length) {
var nodes = []
var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
var n
while ((n = walker.nextNode()) !== null) nodes.push(n)
var pos = 0
for (var i = 0; i < nodes.length; i++) {
var len = (nodes[i].nodeValue || '').length
if (offset < pos + len) {
var range = document.createRange()
range.setStart(nodes[i], offset - pos)
var remain = length
var j = i
var inner = offset - pos
while (remain > 0) {
var l = (nodes[j].nodeValue || '').length
var take = Math.min(remain, l - inner)
remain -= take
if (remain === 0) { range.setEnd(nodes[j], inner + take); break }
j++
inner = 0
}
return range
}
pos += len
}
return null
}
function findRangeIn(el, quote) {
var full = ''
var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
var n
while ((n = walker.nextNode()) !== null) full += n.nodeValue || ''
var start = full.indexOf(quote)
if (start === -1) return null
return rangeFromOffset(el, start, quote.length)
}
/** 空白完全剥离匹配:返回 quote 在 full 中的所有原始偏移区间 [{start,end}]。
* 解决选区文本跨块级元素(GenUI 表格单元格等)带出 \n、而 DOM textContent
* 无此空白导致的匹配失败(此前会掉进宽松匹配命中旧轮次)。 */
function allNormSpans(full, quote) {
var nq = quote.replace(/\s+/g, '')
if (nq === '') return []
var nf = ''
var map = []
for (var i = 0; i < full.length; i++) {
if (!/\s/.test(full[i])) { nf += full[i]; map.push(i) }
}
var out = []
var idx = nf.indexOf(nq)
while (idx !== -1) {
out.push({ start: map[idx], end: map[idx + nq.length - 1] + 1 })
idx = nf.indexOf(nq, idx + 1)
}
return out
}
function findNormSpan(full, quote) {
var spans = allNormSpans(full, quote)
return spans.length > 0 ? spans[0] : null
}
/** 批注芯片差异变体:选区文本里芯片是「Annotation N」(无冒号),而消息行
* 渲染文本可能是「Annotation N:」(React 重渲染后冒号恢复)——匹配失败时
* 用变体重试,抹平该差异。 */
function quoteVariants(quote) {
var out = [quote]
var re = /Annotation[\s\u200b\u200c\u200d\u00ad]*(\d+)/gi
var m
while ((m = re.exec(quote)) !== null) {
out.push(quote.slice(0, m.index) + 'Annotation ' + m[1] + ':' + quote.slice(m.index + m[0].length))
}
return out
}
function allPositionsOf(el, quote) {
var full = el.textContent || ''
var out = []
var idx = full.indexOf(quote)
while (idx !== -1) {
out.push(idx)
idx = full.indexOf(quote, idx + 1)
}
return out
}
function ctxScore(full, pos, len, ctx) {
if (ctx === null) return 0
var before = full.slice(Math.max(0, pos - 24), pos)
var after = full.slice(pos + len, pos + len + 24)
var s = 0
for (var i = 0; i < Math.min(before.length, ctx.before.length); i++) {
if (before[i] === ctx.before[i]) s++
}
for (var j = 0; j < Math.min(after.length, ctx.after.length); j++) {
if (after[j] === ctx.after[j]) s++
}
return s
}
/** 由 Range 起点算出它在元素文本内的绝对字符偏移(真实位置)。 */
function offsetOfRangeInRow(row, range) {
try {
var walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT)
var n
var pos = 0
while ((n = walker.nextNode()) !== null) {
var len = (n.nodeValue || '').length
if (n === range.startContainer) return pos + range.startOffset
pos += len
}
} catch (_) { /* fallthrough */ }
return -1
}
/** 宽松定位:token 式匹配,双向容忍空白差异。 */
function findRangeFlexible(el, quote) {
var qNorm = quote.replace(/\s+/g, ' ').trim()
if (qNorm === '') return null
var tokens = qNorm.split(' ').filter(function (t) { return t !== '' })
if (tokens.length === 0) return null
var nodes = []
var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
var n
while ((n = walker.nextNode()) !== null) nodes.push(n)
var stream = []
for (var i = 0; i < nodes.length; i++) {
var text = nodes[i].nodeValue || ''
for (var k = 0; k < text.length; k++) stream.push({ node: nodes[i], offset: k, ch: text[k] })
}
var t = 0
var ti = 0
var startNode = null
var startOff = 0
var endNode = null
var endOff = -1
var seenGap = false
for (var s = 0; s < stream.length && t < tokens.length; s++) {
var ch = stream[s].ch
var isWs = /\s/.test(ch)
if (isWs) {
if (ti === 0) seenGap = true
continue
}
if (ti === 0) {
if (t > 0 && !seenGap) seenGap = true
if (ch === tokens[t][0]) {
if (t === 0) { startNode = stream[s].node; startOff = stream[s].offset }
ti = 1
} else {
seenGap = true
continue
}
if (tokens[t].length === 1) {
endNode = stream[s].node
endOff = stream[s].offset
t++
ti = 0
seenGap = false
}
continue
}
if (ch === tokens[t][ti]) {
ti++
if (ti === tokens[t].length) {
endNode = stream[s].node
endOff = stream[s].offset
t++
ti = 0
seenGap = false
}
} else {
ti = 0
if (ch === tokens[t][0]) {
if (t === 0) { startNode = stream[s].node; startOff = stream[s].offset }
ti = 1
if (tokens[t].length === 1) {
endNode = stream[s].node
endOff = stream[s].offset
t++
ti = 0
seenGap = false
}
}
}
}
if (t === tokens.length && startNode !== null) {
var range = document.createRange()
range.setStart(startNode, startOff)
range.setEnd(endNode, endOff + 1)
return range
}
return null
}
/** 定位批注的 Range:消息 seq 锚定优先,空白不敏感重搜兜底。 */
function locateQuote(quote, saved) {
if (saved !== undefined && saved !== null && saved.range && saved.range.startContainer) {
try {
if (saved.range.startContainer.isConnected && saved.range.endContainer.isConnected) {
var t = saved.range.toString()
if (t.replace(/\s+/g, '') === quote.replace(/\s+/g, '')) {
return saved.range
}
}
} catch (_) { /* range 已失效 */ }
}
var rows = assistantRows()
if (saved !== undefined && saved !== null && saved.seqKey !== '') {
try {
var item = document.querySelector('[data-chat-anchor-key="' + saved.seqKey + '"]')
// focus-chat 视图的锚 key 属性名不同,值语义一致。
if (item === null) {
item = document.querySelector('[data-focus-anchor-key="' + saved.seqKey + '"]')
}
if (item !== null) {
var itText = item.textContent || ''
if (saved.textOffset >= 0) {
var sp0 = findNormSpan(itText, quote)
if (sp0 !== null && Math.abs(sp0.start - saved.textOffset) <= 2) {
var itRange = rangeFromOffset(item, sp0.start, sp0.end - sp0.start)
if (itRange !== null) return itRange
}
}
if (saved.ctxBefore !== '') {
var itIdx = itText.indexOf(saved.ctxBefore)
if (itIdx !== -1) {
var itNear = itIdx + saved.ctxBefore.length
var sp1 = findNormSpan(itText.slice(itNear), quote)
if (sp1 !== null) {
var itRange2 = rangeFromOffset(item, itNear + sp1.start, sp1.end - sp1.start)
if (itRange2 !== null) return itRange2
}
}
}
// 锚点消息内的全量扫描(空白不敏感 + 上下文评分)。
var spansIt = allNormSpans(itText, quote)
var bestIt = null
var bestItScore = -1
for (var pp2 = 0; pp2 < spansIt.length; pp2++) {
var rngIt = rangeFromOffset(item, spansIt[pp2].start, spansIt[pp2].end - spansIt[pp2].start)
if (rngIt === null) continue
var scIt = ctxScore(itText, spansIt[pp2].start, spansIt[pp2].end - spansIt[pp2].start,
{ before: saved.ctxBefore || '', after: saved.ctxAfter || '' })
if (scIt > bestItScore) { bestItScore = scIt; bestIt = rngIt }
}
if (bestIt !== null && (saved.ctxBefore === '' || bestItScore > 0)) return bestIt
// 锚点消息还在但原文匹配不上:先试批注芯片差异变体(「Annotation N」
// vs「Annotation N:」)在**同一条消息内**宽松重定位——绝不跨消息
// 模糊搜索(那是「跳到旧轮次」的根源,v1.3.6 纪律)。
var variants = quoteVariants(quote)
for (var vi = 0; vi < variants.length; vi++) {
var vsp = allNormSpans(itText, variants[vi])
for (var vj = 0; vj < vsp.length; vj++) {
var vrng = rangeFromOffset(item, vsp[vj].start, vsp[vj].end - vsp[vj].start)
if (vrng !== null) return vrng
}
var vflex = findRangeFlexible(item, variants[vi])
if (vflex !== null) return vflex
}
// 同消息内确实定位不到 → 放弃(脚标隐藏)。
return null
}
} catch (_) { return null }
}
if (saved !== undefined && saved !== null && saved.rowHead !== '') {
for (var r = 0; r < rows.length; r++) {
var rowText = rows[r].textContent || ''
if (rowText.slice(0, 24) !== saved.rowHead) continue
if (saved.textOffset >= 0) {
var spR = findNormSpan(rowText, quote)
if (spR !== null && Math.abs(spR.start - saved.textOffset) <= 2) {
var range = rangeFromOffset(rows[r], spR.start, spR.end - spR.start)
if (range !== null) return range
}
}
if (saved.ctxBefore !== '') {
var bIdx = rowText.indexOf(saved.ctxBefore)
if (bIdx !== -1) {
var near = bIdx + saved.ctxBefore.length
var spR2 = findNormSpan(rowText.slice(near), quote)
if (spR2 !== null) {
var range2 = rangeFromOffset(rows[r], near + spR2.start, spR2.end - spR2.start)
if (range2 !== null) return range2
}
}
}
var spans = allNormSpans(rowText, quote)
var bestRow = null
var bestRowScore = -1
for (var pp = 0; pp < spans.length; pp++) {
var rng = rangeFromOffset(rows[r], spans[pp].start, spans[pp].end - spans[pp].start)
if (rng === null) continue
var sc = ctxScore(rowText, spans[pp].start, spans[pp].end - spans[pp].start,
saved !== undefined && saved !== null
? { before: saved.ctxBefore || '', after: saved.ctxAfter || '' }
: null)
if (sc > bestRowScore) { bestRowScore = sc; bestRow = rng }
}
if (bestRow !== null) return bestRow
}
}
var ctx = saved !== undefined && saved !== null
? { before: saved.ctxBefore || '', after: saved.ctxAfter || '' }
: null
var best = null
var bestScore = -1
for (var i = 0; i < rows.length; i++) {
var full = rows[i].textContent || ''
var spans = allNormSpans(full, quote)
for (var p = 0; p < spans.length; p++) {
var range = rangeFromOffset(rows[i], spans[p].start, spans[p].end - spans[p].start)
if (range === null) continue
var score = ctxScore(full, spans[p].start, spans[p].end - spans[p].start, ctx)
if (score > bestScore) { bestScore = score; best = range }
}
}
if (best !== null && (ctx === null || bestScore > 0)) return best
var flow = document.querySelector('[data-chat-flow]')
if (flow === null) flow = document.querySelector('[data-focus-flow]')
if (flow !== null) {
var full2 = flow.textContent || ''
var positions2 = allPositionsOf(flow, quote)
var best2 = null
var bestScore2 = -1
for (var q2 = 0; q2 < positions2.length; q2++) {
var range2 = rangeFromOffset(flow, positions2[q2], quote.length)
if (range2 === null) continue
var score2 = ctxScore(full2, positions2[q2], quote.length, ctx)
if (score2 > bestScore2) { bestScore2 = score2; best2 = range2 }
}
if (best2 !== null && (ctx === null || bestScore2 > 0)) return best2
}
return null
}
function truncate(s, n) {
return s.length > n ? s.slice(0, n) + '…' : s
}
function placeAbove(rect, height) {
var w = 400
var left = rect.left + rect.width / 2 - w / 2
left = Math.max(8, Math.min(left, window.innerWidth - w - 8))
var top = rect.top - height - 8
if (top < 8) top = Math.min(rect.bottom + 8, window.innerHeight - height - 8)
return { left: Math.round(left), top: Math.round(Math.max(8, top)) }
}
function svg(paths, viewBox) {
var s = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
s.setAttribute('viewBox', viewBox)
s.setAttribute('fill', 'none')
s.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
for (var i = 0; i < paths.length; i++) {
var p = document.createElementNS('http://www.w3.org/2000/svg', 'path')
p.setAttribute('d', paths[i])
p.setAttribute('fill', 'currentColor')
s.appendChild(p)
}
return s
}
var ICONS = {
plus: function () {
return svg(['M8.64453 1.5V7.34961H14.5V8.65039H8.64453V14.5H7.34473V8.65039H1.5V7.34961H7.34473V1.5H8.64453Z'], '0 0 16 16')
},
check: function () {
return svg([
'M15.0498 3.92579L8.49512 12.3818C8.25774 12.6881 8.04517 12.9645 7.84668 13.1689C7.63957 13.3823 7.38732 13.5841 7.04492 13.6719C6.86373 13.7183 6.6757 13.7346 6.48926 13.7197C6.13666 13.6915 5.8528 13.5355 5.6123 13.3604C5.38201 13.1926 5.12573 12.9567 4.83984 12.6953L1.03125 9.21289L1.96875 8.1875L5.77734 11.6699C6.08684 11.9529 6.27773 12.1249 6.43066 12.2363C6.50183 12.2882 6.54699 12.3135 6.57324 12.3252C6.58525 12.3305 6.59269 12.3322 6.5957 12.333C6.59802 12.3336 6.59961 12.334 6.59961 12.334C6.63317 12.3367 6.66758 12.3335 6.7002 12.3252C6.7002 12.3252 6.70211 12.3251 6.7041 12.3242C6.70698 12.3229 6.71348 12.319 6.72461 12.3115C6.74849 12.2956 6.78843 12.2642 6.84961 12.2012C6.98138 12.0654 7.13957 11.8628 7.39648 11.5313L13.9502 3.07422L15.0498 3.92579Z',
], '0 0 16 16')
},
close: function () {
return svg([
'M14.1168 13.197L13.197 14.1167L1.8833 2.80303L2.80309 1.88324L14.1168 13.197Z',
'M13.197 1.88326L14.1168 2.80305L2.80309 14.1168L1.8833 13.197L13.197 1.88326Z',
], '0 0 16 16')
},
send: function () {
return svg([
'M8.3125 0.981587C8.66767 1.0545 8.97902 1.20558 9.2627 1.43374C9.48724 1.61438 9.73029 1.85933 9.97949 2.10854L14.707 6.83608L13.293 8.25014L9 3.95717V15.0431H7V3.95717L2.70703 8.25014L1.29297 6.83608L6.02051 2.10854C6.26971 1.85933 6.51277 1.61438 6.7373 1.43374C6.97662 1.24126 7.28445 1.04542 7.6875 0.981587C7.8973 0.94841 8.1031 0.956564 8.3125 0.981587Z',
], '0 0 16 16')
},
trash: function () {
return svg([
'M14.4782 4.84067L14.2138 10.1152C14.1102 12.1872 14.067 13.0115 13.3866 13.9607C13.1044 14.3546 12.7498 14.6912 12.3424 14.9535C11.8239 15.2872 11.2415 15.4316 10.5585 15.4998C9.88727 15.5668 9.04946 15.5656 7.99998 15.5656C6.95051 15.5656 6.1127 15.5668 5.44142 15.4998C4.75851 15.4316 4.17602 15.2872 3.65753 14.9535C3.25012 14.6912 2.89559 14.3546 2.61332 13.9607C1.93296 13.0115 1.88979 12.1872 1.78619 10.1152L1.52179 4.84067L2.89006 4.77277L3.15343 10.0463C3.26221 12.2218 3.32452 12.6015 3.72646 13.1624C3.90825 13.4161 4.13686 13.6334 4.39927 13.8023C4.66204 13.9714 5.00263 14.0792 5.57825 14.1367C6.16562 14.1953 6.92298 14.1963 7.99998 14.1963C9.07699 14.1963 9.83434 14.1953 10.4217 14.1367C10.9973 14.0792 11.3379 13.9714 11.6007 13.8023C11.8631 13.6334 12.0917 13.4161 12.2735 13.1624C12.6755 12.6015 12.7378 12.2218 12.8465 10.0463L13.1099 4.77277L14.4782 4.84067ZM5.43011 6.22849H6.7994V11.3909H5.43011V6.22849ZM9.20056 6.22849H10.5699V11.3909H9.20056V6.22849ZM8.53597 0.434431C9.17976 0.434431 9.6522 0.426926 10.0966 0.571258C10.2357 0.616451 10.3717 0.672554 10.502 0.738948C10.9182 0.951107 11.2464 1.29099 11.7015 1.74612L12.4978 2.54136H15.3742V3.91169H0.625732V2.54136H3.50218L4.29845 1.74612C4.75358 1.29099 5.08174 0.951107 5.49801 0.738948C5.62831 0.672554 5.76425 0.616451 5.90334 0.571258C6.34776 0.426926 6.82021 0.434431 7.46399 0.434431H8.53597ZM7.46399 1.80476C6.73208 1.80476 6.51641 1.81187 6.32617 1.87369C6.25545 1.89667 6.18668 1.92533 6.12041 1.95907C5.96398 2.03878 5.82348 2.16253 5.44142 2.54136H10.5585C10.1765 2.16253 10.036 2.03878 9.87955 1.95907C9.81329 1.92533 9.74452 1.89667 9.6738 1.87369C9.48356 1.81187 9.26789 1.80476 8.53597 1.80476H7.46399Z',
], '0 0 16 16')
},
}
var PENDING_STORAGE_PREFIX = 'dsh.annotation.pending.v1.'
function pendingStorageKey(sessionId) {
return PENDING_STORAGE_PREFIX + encodeURIComponent(String(sessionId))
}
function parsePendingQuotes(raw) {
if (typeof raw !== 'string' || raw === '') return []
try {
var value = JSON.parse(raw)
if (!Array.isArray(value)) return []
return value.filter(function (q) {
return q !== null && typeof q === 'object'
&& typeof q.id === 'string' && typeof q.text === 'string' && q.text !== ''
}).map(function (q) {
return {
id: q.id,
text: q.text,
note: typeof q.note === 'string' ? q.note : '',
range: null,
seqKey: typeof q.seqKey === 'string' ? q.seqKey : '',
rowHead: typeof q.rowHead === 'string' ? q.rowHead : '',
textOffset: Number.isFinite(q.textOffset) ? q.textOffset : -1,
ctxBefore: typeof q.ctxBefore === 'string' ? q.ctxBefore : '',
ctxAfter: typeof q.ctxAfter === 'string' ? q.ctxAfter : '',
}
})
} catch (_) {
return []
}
}
function stringifyPendingQuotes(quotes) {
return JSON.stringify(quotes.map(function (q) {
return {
id: q.id,
text: q.text,
note: q.note || '',
seqKey: q.seqKey || '',
rowHead: q.rowHead || '',
textOffset: Number.isFinite(q.textOffset) ? q.textOffset : -1,
ctxBefore: q.ctxBefore || '',
ctxAfter: q.ctxAfter || '',
}
}))
}
// ============================== 插件主体 ==============================
function apply(ctx) {
var sessions = ctx.sessions
var host = document.createElement('div')
host.setAttribute('data-annotation-for-dsh', '')
document.body.appendChild(host)
var overlay = document.createElement('div')
overlay.setAttribute('data-annotation-overlay', '')
document.body.appendChild(overlay)
var ui = {
mode: 'closed', // closed | actions | editing | composing
editingId: null, // 非空 = 正在编辑该 id 的已有批注(点角标进入)
quote: '',
quotes: [], // [{ id, text, note, range, seqKey, rowHead, textOffset, ctxBefore, ctxAfter }]
noteDraft: '',
pos: { left: 0, top: 0 },
error: null,
busy: false,
lastKey: '',
pendingAnchor: null,
el: null,
}
function readPendingQuotes(sessionId) {
if (sessionId === undefined) return []
try {
return parsePendingQuotes(localStorage.getItem(pendingStorageKey(sessionId)))
} catch (err) {
console.warn('[annotation] 读取待发送批注失败:', err)
return []
}
}
function writePendingQuotes(sessionId) {
if (sessionId === undefined) return
try {
var key = pendingStorageKey(sessionId)
if (ui.quotes.length === 0) localStorage.removeItem(key)
else localStorage.setItem(key, stringifyPendingQuotes(ui.quotes))
} catch (err) {
console.warn('[annotation] 保存待发送批注失败:', err)
}
}
function writeCurrentPendingQuotes() {
writePendingQuotes(sessions.list.getSnapshot().current)
}
var ignoreUntil = 0
var settleTimer = null
// ---------- IME 合成 latch(对齐官方 InputBar composingRef)----------
// macOS / 豆包等:compositionend 之后才会到 keydown(Enter, isComposing=false,
// keyCode=13),仅查 isComposing / 229 挡不住「上屏确认 Enter」。若此时
// attachAndSend → setDraft,会打断合成,表现为只能打出拼音字母。
// 延迟清 latch 与 InputBar 一致(略放宽到 50ms,兼容第三方输入法时序)。
var imeComposing = false
var imeClearTimer = null
var imeTouchedAt = 0
function markImeComposing() {
imeComposing = true
imeTouchedAt = Date.now()
if (imeClearTimer !== null) {
clearTimeout(imeClearTimer)
imeClearTimer = null
}
}
function markImeEnded() {
if (imeClearTimer !== null) clearTimeout(imeClearTimer)
imeClearTimer = setTimeout(function () {
imeComposing = false
imeClearTimer = null
}, 50)
}
/** @param {KeyboardEvent} e */
function isImeKeyBlocked(e) {
if (e.isComposing === true || e.keyCode === 229) {
imeTouchedAt = Date.now()
return true
}
// compositionend 偶尔会丢失。只在浏览器已明确报告「非合成」且 latch
// 1.2 秒没有活动时复位,避免一次异常把之后所有 Enter 永久锁死。
if (imeComposing && imeClearTimer === null && Date.now() - imeTouchedAt >= 1200) {
imeComposing = false
}
return imeComposing
}
document.addEventListener('compositionstart', markImeComposing, true)
document.addEventListener('compositionend', markImeEnded, true)
// ---------- 轻提示 ----------
var toastTimer = null
function showToast(msg) {
try {
var old = document.querySelector('[data-annotation-toast]')
if (old !== null) old.remove()
var el = document.createElement('div')
el.setAttribute('data-annotation-toast', '')
el.textContent = msg
el.style.cssText = 'position:fixed;z-index:1300;left:50%;bottom:88px;transform:translateX(-50%);max-width:min(420px,calc(100vw - 24px));padding:8px 14px;border-radius:10px;background:var(--dsw-specific-menu,#2c2c2e);border:1px solid var(--dsw-alias-border-inverted);box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-primary);font-family:var(--dsw-font-family,system-ui);font-size:12px;pointer-events:none;'
document.body.appendChild(el)
if (toastTimer !== null) clearTimeout(toastTimer)
toastTimer = setTimeout(function () {
toastTimer = null
if (el.parentNode) el.parentNode.removeChild(el)
}, 3000)
} catch (_) { /* toast 失败忽略 */ }
}
// ---------- 选区监听 ----------
function selectionKey(sel) {
if (sel === null || sel.rangeCount === 0) return ''
var r = sel.getRangeAt(0)
return String(r.startContainer === r.endContainer ? 1 : 0)
+ ':' + r.startOffset + ':' + r.endOffset + ':' + sel.toString().length
}
function onSelection() {
if (ui.mode !== 'closed' && host.childNodes.length === 0) {
ui.mode = 'closed'
ui.lastKey = ''
}
if (ui.mode === 'editing' || ui.mode === 'composing' || ignoreUntil > Date.now()) return
var sel = window.getSelection()
if (sel === null || sel.isCollapsed || sel.rangeCount === 0) {
clearSettle()
return
}
var range = sel.getRangeAt(0)
var anc = range.commonAncestorContainer
var ancEl = anc instanceof Element ? anc : (anc && anc.parentElement)
if (ancEl !== null && ancEl.closest) {
if (ancEl.closest('[data-annotation-for-dsh]') || ancEl.closest('[data-annotation-overlay]')
|| ancEl.closest('[data-composer-card]') || ancEl.closest('[data-input-scroll]')) {
clearSettle()
return
}
}
if (host.contains(anc) || overlay.contains(anc)) {
clearSettle()
return
}
var text = sel.toString().trim()
if (text.length === 0) { clearSettle(); return }
var key = selectionKey(sel)
if (ui.mode === 'actions' && key === ui.lastKey) { clearSettle(); return }
var rootEl = assistantRowOf(range.commonAncestorContainer)
if (rootEl === null) { clearSettle(); closeToolbar(); return }
clearSettle()
settleTimer = setTimeout(function () {
settleTimer = null
if (ui.mode === 'editing' || ui.mode === 'composing') return
var s = window.getSelection()
if (s === null || s.isCollapsed || selectionKey(s) !== key) return
var r = s.getRangeAt(0)
if (assistantRowOf(r.commonAncestorContainer) === null) return
var rect = r.getBoundingClientRect()
if (rect.width === 0 || rect.height === 0) return
var p = placeAbove(rect, 40)
if (ui.mode === 'actions' && ui.quote === text) {
ui.lastKey = key
ui.pos = p
if (ui.el !== null && ui.el.style) {
ui.el.style.left = p.left + 'px'
ui.el.style.top = p.top + 'px'
}
return
}
ui.lastKey = key
ui.mode = 'actions'
ui.quote = text
ui.error = null
ui.pos = p
render()
}, 250)
}
document.addEventListener('selectionchange', onSelection)
function clearSettle() {
if (settleTimer !== null) { clearTimeout(settleTimer); settleTimer = null }
}