dsh-mindmark 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,3239 @@
1
+ // dsh-mindmark — Web client half.
2
+ //
3
+ // Contributions:
4
+ // • `conversation.chat.text-interaction` (keyed, session-scoped): the Word-like
5
+ // action bar that the Chat view places next to a text selection. We register
6
+ // under the built-in `quote` key with a lower priority (so the bar replaces
7
+ // the plain Quote button and keeps Quote as its first action), plus our own
8
+ // `dsh-mindmark` interaction for hosts where the Quote plugin is absent.
9
+ // • `conversation.input.left` (session list): the brief/full injection-mode
10
+ // switch beside the composer controls, with a pending-count badge.
11
+ // • `conversation.session.header.utilities` (session list): marker icon +
12
+ // count; toggles the annotation panel.
13
+ // • `shell.overlay` (root list): the annotation panel, the move banner and
14
+ // the reference form. The reference form lives here rather than in the
15
+ // selection bar because the Chat view dismisses its bar whenever the window
16
+ // loses focus, and a native file dialog takes the focus away.
17
+ //
18
+ // Moving a passage works like cut and paste: Alt+C (or the toolbar's Move)
19
+ // picks up the selection, a click inside the same answer puts a blinking caret
20
+ // where it goes (the passage is inserted right after the caret; dragging over
21
+ // some text instead makes the passage replace that text), Alt+V (or the
22
+ // banner's button) drops it there, Esc cancels. Alt is the only
23
+ // modifier that neither clashes with typing (Shift) nor stays invisible to the
24
+ // page (Fn); Harness itself binds no Alt+C / Alt+V.
25
+ //
26
+ // Annotations are text anchors, never host-DOM references: the selection is
27
+ // converted into character offsets over the nearest scroll container, stored as
28
+ // a quote + prefix/suffix + CSS path record on the Host, and re-anchored by
29
+ // scoring every `indexOf(quote)` candidate against the saved context. The same
30
+ // selection is also located inside its message body so the Host can render a
31
+ // full revision view. Painting uses the CSS Custom Highlight API, so no DOM
32
+ // inside messages is ever mutated.
33
+ //
34
+ // Everything is plain ES5-flavoured JavaScript with `React.createElement`; no
35
+ // Harness Client packages are imported, all chrome follows the `--dsw-alias-*`
36
+ // theme tokens and everything is namespaced under the `dsa-` class prefix.
37
+
38
+ window.__ModuleLoader__.load({
39
+ id: 'dsh-mindmark',
40
+ factory: (require) => {
41
+ var module = { exports: {} }
42
+ var exports = module.exports
43
+
44
+ var React = require('react')
45
+ var h = React.createElement
46
+ var useEffect = React.useEffect
47
+ var useState = React.useState
48
+ var useRef = React.useRef
49
+ var useSyncExternalStore = React.useSyncExternalStore
50
+
51
+ var ROUTE = '/plugins/dsh-mindmark/annotations'
52
+ var UI_ATTR = 'data-dsh-mindmark-ui'
53
+ var UI_SELECTOR = '[' + UI_ATTR + ']'
54
+ var CSS_ID = 'dsh-mindmark'
55
+ var STYLES = ['highlight', 'underline', 'strike', 'comment', 'rewrite', 'move', 'reference']
56
+ // First toolbar row: one click and done. Second row: needs your input.
57
+ var QUICK_STYLES = ['highlight', 'underline', 'strike']
58
+ var INPUT_STYLES = ['comment', 'rewrite', 'reference', 'move']
59
+ var NOTE_STYLES = { comment: true, rewrite: true }
60
+ var MATERIAL_KINDS = ['text', 'url', 'file']
61
+ var MAX_MATERIAL = 200000
62
+ var MAX_MATERIAL_FILE_BYTES = 4 * 1024 * 1024
63
+ var MATERIAL_FILE_ACCEPT = '.txt,.md,.markdown,.csv,.tsv,.json,.html,.htm,.xml,.yaml,.yml,.log,.tex,.rst,.srt,text/*'
64
+ var MOVE_EXTRA_HIGHLIGHTS = ['dsa-move-pending', 'dsa-move-replace', 'dsa-ref-pending']
65
+ var CARET_LAYER_ID = 'dsa-caret-layer'
66
+ var MODES = ['brief', 'full']
67
+ var MAX_QUOTE = 2000
68
+ var MAX_NOTE = 2000
69
+ var MAX_MESSAGE_TEXT = 20000
70
+ var CONTEXT_MAX = 80
71
+ var SELECTOR_MAX = 300
72
+ var ID_MAX = 120
73
+ var MUTATION_DEBOUNCE = 150
74
+ var STATE_REPAINT_DELAY = 60
75
+ var PANEL_TITLE_ID = 'dsa-annotate-panel-title'
76
+ var SURFACE_KEY = 'dsh-mindmark'
77
+
78
+ // ------------------------------------------------------------- dictionaries
79
+
80
+ var DICT = {
81
+ zh: {
82
+ headerLabel: '标注',
83
+ headerTitle: '标注 · {count} 条待处理',
84
+ panelTitle: '我的标注',
85
+ toolbarLabel: '标注操作',
86
+ count: '{count} 条',
87
+ pendingCount: '{count} 条待处理',
88
+ quote: '引用',
89
+ highlight: '高亮',
90
+ underline: '下划线',
91
+ strike: '删除',
92
+ comment: '批注',
93
+ rewrite: '改写',
94
+ 'hint.highlight': '这是我要的:保留并强化',
95
+ 'hint.underline': '这里不够:展开或给依据',
96
+ 'hint.strike': '去掉:下一版不要出现',
97
+ 'hint.comment': '写一条意见,让助手按它处理',
98
+ 'hint.rewrite': '把这段改成你要的样子',
99
+ 'hint.quote': '把选中的文字引用到输入框',
100
+ move: '移动',
101
+ reference: '依据',
102
+ 'hint.move': '把这段挪到别处:Alt+C 拿起,在同一条回答里点一下目标位置,Alt+V 放下',
103
+ 'hint.reference': '给这段挂参考材料,让助手只按材料改这一段',
104
+ moveBanner: '移动「{quote}」',
105
+ moveHowTo: '在同一条回答里点一下要放的位置(拖选一段则替换那段),再按 Alt+V 或点「放到这里」;Esc 取消',
106
+ moveReady: '放在闪烁竖线之后:…{before}▮{after}…',
107
+ moveReplaceReady: '替换选中的「{quote}」',
108
+ moveOverlap: '被替换的文字不能和被移动的文字重叠',
109
+ movePlaceReplace: '移到这里替换',
110
+ moveReplaceLabel: '替换',
111
+ moveNoTarget: '还没选位置:先在同一条回答里点一下要放的地方',
112
+ moveOtherMessage: '只能移到同一条回答里',
113
+ moveSamePlace: '目标位置在被移动的文字里面或就在原处,换一个地方',
114
+ moveUnanchored: '这段文字不在某一条回答里,没法移动',
115
+ movePlace: '放到这里',
116
+ moveReasonPlaceholder: '理由(可选)',
117
+ moveTargetLabel: '移到',
118
+ reasonLabel: '理由',
119
+ requirementLabel: '要求',
120
+ materialLabel: '材料',
121
+ refTabText: '粘贴文本',
122
+ refTabUrl: '链接',
123
+ refTabFile: '文件',
124
+ refTitlePlaceholder: '材料名称(可选),如:教材第 3 章',
125
+ refTextPlaceholder: '把参考材料粘贴在这里…',
126
+ refUrlPlaceholder: 'https://…',
127
+ refFileChoose: '选择文件',
128
+ refFileNone: '还没选文件',
129
+ refFileHint: '支持 txt、md、csv、json、html 等纯文本;PDF、Word 请先复制文字再粘贴',
130
+ refNotePlaceholder: '要求(可选),如:按材料的口径改写这一段,其余不动',
131
+ refTooLong: '材料太长(最多 {max} 字),只保留和这一段相关的部分',
132
+ refFileError: '读不了这个文件,请改为粘贴文本',
133
+ refBadUrl: '链接要以 http:// 或 https:// 开头',
134
+ chars: '{count} 字',
135
+ unmark: '清除标记',
136
+ close: '关闭',
137
+ delete: '删除',
138
+ clearAll: '清空全部',
139
+ resolve: '标为已处理',
140
+ reopen: '重新提交',
141
+ resolveAll: '全部标为已处理',
142
+ confirm: '确定',
143
+ cancel: '取消',
144
+ commentPlaceholder: '写下你的意见…',
145
+ rewritePlaceholder: '改成…',
146
+ statusPending: '待处理',
147
+ statusResolved: '已处理',
148
+ byModel: '助手已处理',
149
+ byUser: '你已处理',
150
+ byCap: '多轮未处理,已自动收起',
151
+ noteLabel: '批注',
152
+ rewriteLabel: '改为',
153
+ modeLabel: '标注注入',
154
+ modeBrief: '精简',
155
+ modeFull: '完整',
156
+ modeBriefHint: '精简:下一轮只发送被标注的段落和少量上下文',
157
+ modeFullHint: '完整:下一轮发送整条回答的修订视图',
158
+ modeTitle: '标注如何送给助手',
159
+ loading: '加载中…',
160
+ empty: '还没有标注。在回答里选中文字,工具条会浮出来。',
161
+ footerHint: '待处理的标注会在下一轮自动送给助手;助手处理后会标为已处理。',
162
+ distill: '沉淀为习惯',
163
+ distillHint: '让助手把这些标注归纳成长期偏好,写进你的全局 AGENTS.md,新对话自动遵守',
164
+ distillPrompt: '请回顾我在这个对话里做过的全部标注(用 annotations 工具 action=list 查看),归纳出我反复表现出的偏好,每条一句、可直接执行、不要带具体内容,然后用 annotations 工具 action=distill 把它们写入 lessons。写完后把沉淀的偏好列给我看。',
165
+ lessonsTitle: '已沉淀的偏好',
166
+ lessonsEmpty: '还没有沉淀过偏好。标注积累几条后,点「沉淀为习惯」让助手归纳。',
167
+ forget: '移除',
168
+ warning: '当前浏览器不支持 CSS Custom Highlight API:标注仍会保存,但不会显示在页面上。',
169
+ 'err.generic': '操作失败,请稍后重试。',
170
+ 'err.network': '无法连接到 Harness,标注没有保存。',
171
+ 'err.http': '标注服务返回了错误。',
172
+ 'err.load': '加载标注失败。',
173
+ 'err.add': '保存标注失败。',
174
+ 'err.remove': '删除标注失败。',
175
+ 'err.clear': '清空标注失败。',
176
+ 'err.resolve': '更新标注状态失败。',
177
+ 'err.mode': '切换模式失败。',
178
+ 'err.invalid': '标注数据不完整,没有保存。',
179
+ },
180
+ en: {
181
+ headerLabel: 'Annotations',
182
+ headerTitle: 'Annotations · {count} pending',
183
+ panelTitle: 'My annotations',
184
+ toolbarLabel: 'Annotate selection',
185
+ count: '{count}',
186
+ pendingCount: '{count} pending',
187
+ quote: 'Quote',
188
+ highlight: 'Highlight',
189
+ underline: 'Underline',
190
+ strike: 'Strike',
191
+ comment: 'Comment',
192
+ rewrite: 'Rewrite',
193
+ 'hint.highlight': 'This is what I want: keep and strengthen it',
194
+ 'hint.underline': 'Not enough here: expand or justify',
195
+ 'hint.strike': 'Drop this next time',
196
+ 'hint.comment': 'Leave a note the assistant must act on',
197
+ 'hint.rewrite': 'Replace this passage with your own words',
198
+ 'hint.quote': 'Quote the selection into the composer',
199
+ move: 'Move',
200
+ reference: 'Source',
201
+ 'hint.move': 'Move this passage: Alt+C picks it up, click the target spot in the same answer, Alt+V drops it',
202
+ 'hint.reference': 'Attach reference material; the assistant revises only this passage to match it',
203
+ moveBanner: 'Move "{quote}"',
204
+ moveHowTo: 'Click where it should go in the same answer (drag over text to replace it), then press Alt+V or "Drop here"; Esc cancels',
205
+ moveReady: 'Goes right after the blinking caret: …{before}▮{after}…',
206
+ moveReplaceReady: 'Replaces the selected "{quote}"',
207
+ moveOverlap: 'The replaced text cannot overlap the passage being moved',
208
+ movePlaceReplace: 'Replace with it',
209
+ moveReplaceLabel: 'Replaces',
210
+ moveNoTarget: 'No target yet: click the spot in the same answer first',
211
+ moveOtherMessage: 'A passage can only move within the same answer',
212
+ moveSamePlace: 'The target is inside the passage or where it already is; pick another spot',
213
+ moveUnanchored: 'This text is not part of an answer and cannot be moved',
214
+ movePlace: 'Drop here',
215
+ moveReasonPlaceholder: 'Why (optional)',
216
+ moveTargetLabel: 'Move to',
217
+ reasonLabel: 'Why',
218
+ requirementLabel: 'Ask',
219
+ materialLabel: 'Material',
220
+ refTabText: 'Paste text',
221
+ refTabUrl: 'Link',
222
+ refTabFile: 'File',
223
+ refTitlePlaceholder: 'Material name (optional), e.g. Textbook ch. 3',
224
+ refTextPlaceholder: 'Paste the reference material here…',
225
+ refUrlPlaceholder: 'https://…',
226
+ refFileChoose: 'Choose file',
227
+ refFileNone: 'No file chosen',
228
+ refFileHint: 'Plain-text files (txt, md, csv, json, html…); for PDF or Word, copy the text and paste it',
229
+ refNotePlaceholder: 'Instruction (optional), e.g. rewrite this passage to match the material',
230
+ refTooLong: 'Material too long (max {max} characters); keep only the relevant part',
231
+ refFileError: 'Could not read this file; paste the text instead',
232
+ refBadUrl: 'The link must start with http:// or https://',
233
+ chars: '{count} chars',
234
+ unmark: 'Remove marks',
235
+ close: 'Close',
236
+ delete: 'Delete',
237
+ clearAll: 'Clear all',
238
+ resolve: 'Mark handled',
239
+ reopen: 'Send again',
240
+ resolveAll: 'Mark all handled',
241
+ confirm: 'OK',
242
+ cancel: 'Cancel',
243
+ commentPlaceholder: 'Your note…',
244
+ rewritePlaceholder: 'Replace with…',
245
+ statusPending: 'Pending',
246
+ statusResolved: 'Handled',
247
+ byModel: 'Handled by the assistant',
248
+ byUser: 'Handled by you',
249
+ byCap: 'Auto-settled after several turns',
250
+ noteLabel: 'Note',
251
+ rewriteLabel: 'Replace with',
252
+ modeLabel: 'Annotation feed',
253
+ modeBrief: 'Brief',
254
+ modeFull: 'Full',
255
+ modeBriefHint: 'Brief: next turn sends only the annotated passages with a little context',
256
+ modeFullHint: 'Full: next turn sends the whole answer as a revision view',
257
+ modeTitle: 'How annotations reach the assistant',
258
+ loading: 'Loading…',
259
+ empty: 'No annotations yet. Select text in an answer and the toolbar appears.',
260
+ footerHint: 'Pending annotations are sent to the assistant on the next turn; it marks them handled afterwards.',
261
+ distill: 'Keep as habit',
262
+ distillHint: 'Ask the assistant to distill these annotations into long-term preferences in your global AGENTS.md',
263
+ distillPrompt: 'Review every annotation I made in this conversation (use the annotations tool with action=list), distill the preferences I keep showing into one actionable sentence each without specific content, then write them with the annotations tool action=distill in lessons. Show me the distilled list afterwards.',
264
+ lessonsTitle: 'Distilled preferences',
265
+ lessonsEmpty: 'Nothing distilled yet. After a few annotations, click "Keep as habit" to let the assistant summarize them.',
266
+ forget: 'Remove',
267
+ warning: 'This browser does not support the CSS Custom Highlight API: annotations are still saved but will not be painted.',
268
+ 'err.generic': 'Something went wrong. Try again.',
269
+ 'err.network': 'Could not reach the Harness; the annotation was not saved.',
270
+ 'err.http': 'The annotation service returned an error.',
271
+ 'err.load': 'Could not load annotations.',
272
+ 'err.add': 'Could not save the annotation.',
273
+ 'err.remove': 'Could not delete the annotation.',
274
+ 'err.clear': 'Could not clear annotations.',
275
+ 'err.resolve': 'Could not update the annotation.',
276
+ 'err.mode': 'Could not switch the mode.',
277
+ 'err.invalid': 'The annotation data was incomplete and was not saved.',
278
+ },
279
+ }
280
+
281
+ // ---------------------------------------------------------------- locale
282
+
283
+ var fallbackLocale = {
284
+ subscribe: function () {
285
+ return function () {}
286
+ },
287
+ getSnapshot: function () {
288
+ return { active: 'zh', revision: 0 }
289
+ },
290
+ }
291
+ var localeService = fallbackLocale
292
+
293
+ function subscribeLocale(listener) {
294
+ try {
295
+ if (localeService && typeof localeService.subscribe === 'function') return localeService.subscribe(listener)
296
+ } catch (error) {
297
+ console.error('dsh-mindmark: locale subscribe failed', error)
298
+ }
299
+ return function () {}
300
+ }
301
+
302
+ function localeRevision() {
303
+ try {
304
+ var snapshot = localeService.getSnapshot()
305
+ if (snapshot && typeof snapshot.revision === 'number') return snapshot.revision
306
+ if (snapshot && typeof snapshot.active === 'string') return snapshot.active
307
+ } catch (error) {
308
+ /* fall through */
309
+ }
310
+ return 'default'
311
+ }
312
+
313
+ function useLocaleRevision() {
314
+ return useSyncExternalStore(subscribeLocale, localeRevision, localeRevision)
315
+ }
316
+
317
+ function translate(key, vars) {
318
+ var active = 'zh'
319
+ try {
320
+ var snapshot = localeService.getSnapshot()
321
+ if (snapshot && typeof snapshot.active === 'string') active = snapshot.active
322
+ } catch (error) {
323
+ active = 'zh'
324
+ }
325
+ var dict = String(active).toLowerCase().indexOf('zh') === 0 ? DICT.zh : DICT.en
326
+ var value = dict[key]
327
+ if (value === undefined) value = DICT.en[key]
328
+ if (value === undefined) value = key
329
+ if (vars && typeof value === 'string') {
330
+ return value.replace(/\{(\w+)\}/g, function (match, name) {
331
+ return vars[name] !== undefined ? String(vars[name]) : match
332
+ })
333
+ }
334
+ return value
335
+ }
336
+
337
+ function WithTranslate(component) {
338
+ return function Translated(props) {
339
+ useLocaleRevision()
340
+ var next = {}
341
+ for (var key in props) next[key] = props[key]
342
+ next.t = translate
343
+ return h(component, next)
344
+ }
345
+ }
346
+
347
+ // ------------------------------------------------------------------ styles
348
+
349
+ var MARK_COLORS = {
350
+ highlight: { pending: 'background-color:#f5c542;color:#1b1b1f', resolved: 'background-color:color-mix(in srgb,#f5c542 45%,transparent)' },
351
+ underline: {
352
+ pending: 'text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:2px;text-decoration-color:#4d7cfe',
353
+ resolved: 'text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:2px;text-decoration-color:color-mix(in srgb,#4d7cfe 45%,transparent)',
354
+ },
355
+ strike: {
356
+ pending: 'text-decoration:line-through;text-decoration-thickness:2px;text-decoration-color:#e5484d;background-color:color-mix(in srgb,#e5484d 14%,transparent)',
357
+ resolved: 'text-decoration:line-through;text-decoration-thickness:2px;text-decoration-color:color-mix(in srgb,#e5484d 50%,transparent)',
358
+ },
359
+ comment: {
360
+ pending: 'background-color:color-mix(in srgb,#2fb36f 24%,transparent);text-decoration:underline dotted;text-decoration-color:#2fb36f;text-underline-offset:2px',
361
+ resolved: 'text-decoration:underline dotted;text-decoration-color:color-mix(in srgb,#2fb36f 55%,transparent);text-underline-offset:2px',
362
+ },
363
+ rewrite: {
364
+ pending: 'background-color:color-mix(in srgb,#a06bff 22%,transparent);text-decoration:line-through;text-decoration-color:#a06bff',
365
+ resolved: 'text-decoration:line-through;text-decoration-color:color-mix(in srgb,#a06bff 50%,transparent)',
366
+ },
367
+ move: {
368
+ pending: 'background-color:color-mix(in srgb,#ff8a3d 20%,transparent);text-decoration:underline dashed;text-decoration-thickness:2px;text-underline-offset:3px;text-decoration-color:#ff8a3d',
369
+ resolved: 'text-decoration:underline dashed;text-underline-offset:3px;text-decoration-color:color-mix(in srgb,#ff8a3d 50%,transparent)',
370
+ },
371
+ reference: {
372
+ pending: 'background-color:color-mix(in srgb,#19b5c9 20%,transparent);text-decoration:underline double;text-underline-offset:3px;text-decoration-color:#19b5c9',
373
+ resolved: 'text-decoration:underline double;text-underline-offset:3px;text-decoration-color:color-mix(in srgb,#19b5c9 50%,transparent)',
374
+ },
375
+ }
376
+
377
+ function highlightName(style, status) {
378
+ return 'dsa-' + style + (status === 'resolved' ? '-resolved' : '')
379
+ }
380
+
381
+ var CSS_LINES = [
382
+ '[data-dsh-mindmark-ui]{box-sizing:border-box}',
383
+ '[data-dsh-mindmark-ui] *{box-sizing:border-box}',
384
+ '.dsa-header-btn{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:4px;',
385
+ 'height:26px;min-width:26px;padding:0 6px;border:1px solid transparent;border-radius:7px;background:transparent;',
386
+ 'color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:12px;line-height:1;cursor:pointer}',
387
+ '.dsa-header-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#343844);color:var(--dsw-alias-label-primary,#f2f4f7)}',
388
+ '.dsa-header-btn.is-active{color:var(--dsw-alias-brand-primary,#4d7cfe);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
389
+ '.dsa-header-btn:focus-visible,.dsa-tool-btn:focus-visible,.dsa-tool-close:focus-visible,.dsa-panel-close:focus-visible,',
390
+ '.dsa-item-btn:focus-visible,.dsa-btn:focus-visible,.dsa-mode-btn:focus-visible,.dsa-note-input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d7cfe);outline-offset:1px}',
391
+ '.dsa-header-btn svg{display:block;flex:none}',
392
+ '.dsa-header-badge{min-width:15px;height:15px;padding:0 4px;border-radius:999px;',
393
+ 'background:var(--dsw-alias-brand-primary,#4d7cfe);color:var(--dsw-alias-label-primary-foreground,#10131a);',
394
+ 'font-size:10px;line-height:15px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums}',
395
+ // selection action bar (rendered inside the Chat view's own surface)
396
+ '.dsa-toolbar{display:flex;align-items:center;gap:2px;padding:4px;',
397
+ 'border-radius:10px;background:var(--dsw-alias-button-floating-fill,var(--dsw-alias-bg-overlay,#2a2d36));',
398
+ 'border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l1,#3b3f4a));',
399
+ 'box-shadow:var(--dsw-elevation-panel,0 10px 28px rgba(0,0,0,.32));color:var(--dsw-alias-label-primary,#f2f4f7);',
400
+ 'font-family:inherit;font-size:13px;line-height:1;white-space:nowrap;pointer-events:auto}',
401
+ '.dsa-toolbar.is-note{flex-direction:column;align-items:stretch;gap:6px;padding:8px;white-space:normal;min-width:260px;max-width:min(420px,80vw)}',
402
+ '.dsa-tool-btn{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 8px;border:0;border-radius:7px;',
403
+ 'background:transparent;color:inherit;font:inherit;font-size:12.5px;line-height:1;cursor:pointer;white-space:nowrap}',
404
+ '.dsa-tool-btn:hover{background:var(--dsw-alias-button-floating-hover,var(--dsw-alias-interactive-bg-hover,#343844))}',
405
+ '.dsa-tool-glyph{width:10px;height:10px;flex:none;border-radius:2px}',
406
+ '.dsa-tool-glyph-highlight{background:#f5c542}',
407
+ '.dsa-tool-glyph-underline{height:9px;border-radius:0;border-bottom:2px solid #4d7cfe}',
408
+ '.dsa-tool-glyph-strike{height:9px;border-radius:0;background:linear-gradient(transparent 40%,#e5484d 40%,#e5484d 60%,transparent 60%)}',
409
+ '.dsa-tool-glyph-comment{border-radius:50%;background:#2fb36f}',
410
+ '.dsa-tool-glyph-rewrite{background:#a06bff}',
411
+ '.dsa-tool-glyph-quote{width:9px;height:9px;border-left:3px solid var(--dsw-alias-label-secondary,#a3a8b4);border-radius:0}',
412
+ '.dsa-tool-glyph-move{width:12px;height:9px;border-radius:0;border-bottom:2px dashed #ff8a3d}',
413
+ '.dsa-tool-glyph-reference{border:2px solid #19b5c9;background:transparent}',
414
+ '.dsa-toolbar.is-rows{flex-direction:column;align-items:stretch;gap:2px}',
415
+ '.dsa-tool-row{display:flex;align-items:center;gap:2px}',
416
+ '.dsa-kbd{margin-left:1px;padding:0 3px;border-radius:3px;border:1px solid var(--dsw-alias-border-l1,#3b3f4a);',
417
+ 'font-size:10px;line-height:14px;color:var(--dsw-alias-label-tertiary,#8a8f9c)}',
418
+ '.dsa-toolbar.is-ref{min-width:320px;max-width:min(460px,86vw)}',
419
+ '.dsa-ref-dialog{position:fixed;left:50%;bottom:132px;transform:translateX(-50%);z-index:71;width:min(460px,calc(100vw - 32px));',
420
+ 'max-height:calc(100vh - 180px);overflow-y:auto;animation:dsa-panel-in 140ms ease-out}',
421
+ '.dsa-ref-file input[type=file]{display:none}',
422
+ '.dsa-ref-tabs{display:inline-flex;gap:2px;padding:2px;border-radius:7px;background:var(--dsw-alias-bg-layer-2,#343844);align-self:flex-start}',
423
+ '.dsa-ref-tab{height:22px;padding:0 9px;border:0;border-radius:5px;background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);',
424
+ 'font:inherit;font-size:12px;line-height:1;cursor:pointer}',
425
+ '.dsa-ref-tab.is-on{background:var(--dsw-alias-bg-overlay,#2a2d36);color:var(--dsw-alias-label-primary,#f2f4f7);box-shadow:0 1px 2px rgba(0,0,0,.25)}',
426
+ '.dsa-ref-line,.dsa-move-reason{height:30px;padding:0 9px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1,#3b3f4a);',
427
+ 'background:var(--dsw-alias-bg-layer-1,#20232b);color:var(--dsw-alias-label-primary,#f2f4f7);font:inherit;font-size:13px}',
428
+ '.dsa-ref-line{width:100%}',
429
+ '.dsa-ref-meta{display:flex;justify-content:space-between;gap:8px;font-size:11px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f9c)}',
430
+ '.dsa-ref-file{display:flex;align-items:center;gap:8px;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
431
+ '.dsa-ref-file span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
432
+ '.dsa-ref-file input{display:none}',
433
+ '.dsa-ref-error{margin:0;font-size:11.5px;line-height:16px;color:var(--dsw-alias-state-error-primary,#ff6b6b)}',
434
+ '.dsa-note-input.is-small{min-height:40px}',
435
+ '.dsa-ref-tab:focus-visible,.dsa-ref-line:focus-visible,.dsa-move-reason:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d7cfe);outline-offset:1px}',
436
+ '.dsa-tool-divider{width:1px;height:16px;margin:0 2px;flex:none;background:var(--dsw-alias-border-l1,#3b3f4a)}',
437
+ '.dsa-tool-close{width:26px;height:26px;padding:0;display:inline-grid;place-items:center;border:0;border-radius:7px;',
438
+ 'background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:15px;line-height:1;cursor:pointer}',
439
+ '.dsa-tool-close:hover{color:var(--dsw-alias-label-primary,#f2f4f7);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
440
+ '.dsa-note-head{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
441
+ '.dsa-note-quote{margin:0;max-height:56px;overflow:hidden;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary,#a3a8b4);',
442
+ 'border-left:2px solid var(--dsw-alias-border-l1,#3b3f4a);padding-left:8px;white-space:normal;word-break:break-word}',
443
+ '.dsa-note-input{width:100%;min-height:58px;max-height:160px;resize:vertical;padding:7px 9px;border-radius:8px;',
444
+ 'border:1px solid var(--dsw-alias-border-l1,#3b3f4a);background:var(--dsw-alias-bg-layer-1,#20232b);color:var(--dsw-alias-label-primary,#f2f4f7);',
445
+ 'font:inherit;font-size:13px;line-height:1.5;white-space:pre-wrap}',
446
+ '.dsa-note-actions{display:flex;justify-content:flex-end;gap:6px}',
447
+ // composer mode switch
448
+ '.dsa-mode{display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 4px 0 8px;border-radius:8px;',
449
+ 'border:1px solid var(--dsw-alias-border-l1,#3b3f4a);color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:12px;line-height:1;white-space:nowrap}',
450
+ '.dsa-mode-label{display:inline-flex;align-items:center;gap:4px}',
451
+ '.dsa-mode-label svg{display:block}',
452
+ '.dsa-mode-seg{display:inline-flex;padding:2px;border-radius:6px;background:var(--dsw-alias-bg-layer-2,#343844);gap:2px}',
453
+ '.dsa-mode-btn{height:20px;padding:0 7px;border:0;border-radius:5px;background:transparent;color:inherit;font:inherit;font-size:11.5px;line-height:1;cursor:pointer}',
454
+ '.dsa-mode-btn.is-on{background:var(--dsw-alias-bg-overlay,#2a2d36);color:var(--dsw-alias-label-primary,#f2f4f7);box-shadow:0 1px 2px rgba(0,0,0,.25)}',
455
+ '.dsa-mode-btn:disabled{cursor:default;opacity:.6}',
456
+ '.dsa-mode-badge{min-width:15px;height:15px;padding:0 4px;border-radius:999px;background:var(--dsw-alias-brand-primary,#4d7cfe);',
457
+ 'color:var(--dsw-alias-label-primary-foreground,#10131a);font-size:10px;line-height:15px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums}',
458
+ '@container (max-width: 520px){.dsa-mode-label span{display:none}}',
459
+ // panel
460
+ '[data-dsh-mindmark-ui].dsa-layer{position:fixed;inset:0;z-index:70;pointer-events:none}',
461
+ '.dsa-panel{position:fixed;z-index:70;pointer-events:auto;top:64px;right:16px;width:360px;',
462
+ 'max-width:calc(100vw - 24px);max-height:min(600px,calc(100vh - 96px));display:flex;flex-direction:column;',
463
+ 'border-radius:12px;border:1px solid var(--dsw-alias-border-l1,#3b3f4a);background:var(--dsw-alias-bg-overlay,#2a2d36);',
464
+ 'color:var(--dsw-alias-label-primary,#f2f4f7);box-shadow:0 18px 48px rgba(0,0,0,.36);font-family:inherit;',
465
+ 'font-size:13px;overflow:hidden;animation:dsa-panel-in 140ms ease-out}',
466
+ '@keyframes dsa-panel-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}',
467
+ '.dsa-panel-head{flex:none;display:flex;align-items:center;gap:8px;padding:10px 12px;',
468
+ 'border-bottom:1px solid var(--dsw-alias-border-l1,#3b3f4a)}',
469
+ '.dsa-panel-title{font-size:13.5px;font-weight:600;line-height:20px}',
470
+ '.dsa-panel-count{flex:none;padding:0 6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2,#343844);',
471
+ 'color:var(--dsw-alias-label-secondary,#a3a8b4);font-size:11px;line-height:16px;font-variant-numeric:tabular-nums}',
472
+ '.dsa-spacer{flex:1}',
473
+ '.dsa-panel-close{width:24px;height:24px;padding:0;display:inline-grid;place-items:center;border:0;border-radius:6px;',
474
+ 'background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:15px;line-height:1;cursor:pointer}',
475
+ '.dsa-panel-close:hover{color:var(--dsw-alias-label-primary,#f2f4f7);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
476
+ '.dsa-panel-body{flex:1;min-height:40px;overflow-y:auto;overscroll-behavior:contain;padding:6px 8px;',
477
+ 'display:flex;flex-direction:column;gap:2px}',
478
+ '.dsa-empty,.dsa-loading{margin:0;padding:18px 10px;color:var(--dsw-alias-label-secondary,#a3a8b4);',
479
+ 'font-size:12.5px;line-height:1.7;text-align:center}',
480
+ '.dsa-item{display:flex;align-items:flex-start;gap:8px;padding:8px;border-radius:8px}',
481
+ '.dsa-item:hover{background:var(--dsw-alias-interactive-bg-hover,#343844)}',
482
+ '.dsa-item.is-resolved{opacity:.72}',
483
+ '.dsa-chip{flex:none;margin-top:1px;padding:1px 6px;border-radius:5px;font-size:11px;line-height:16px;white-space:nowrap;color:var(--dsw-alias-label-primary,#f2f4f7)}',
484
+ '.dsa-chip-highlight{background:color-mix(in srgb,#f5c542 32%,transparent)}',
485
+ '.dsa-chip-underline{border:1px solid color-mix(in srgb,#4d7cfe 55%,transparent);color:#7ea0ff}',
486
+ '.dsa-chip-strike{background:color-mix(in srgb,#e5484d 22%,transparent)}',
487
+ '.dsa-chip-comment{background:color-mix(in srgb,#2fb36f 24%,transparent)}',
488
+ '.dsa-chip-rewrite{background:color-mix(in srgb,#a06bff 24%,transparent)}',
489
+ '.dsa-chip-move{background:color-mix(in srgb,#ff8a3d 24%,transparent)}',
490
+ '.dsa-chip-reference{background:color-mix(in srgb,#19b5c9 24%,transparent)}',
491
+ '.dsa-move-banner{position:fixed;left:50%;bottom:132px;transform:translateX(-50%);z-index:71;pointer-events:auto;',
492
+ 'display:flex;align-items:center;gap:8px;flex-wrap:wrap;width:max-content;max-width:min(760px,calc(100vw - 32px));padding:8px 10px;',
493
+ 'border-radius:10px;border:1px solid #ff8a3d;background:var(--dsw-alias-bg-overlay,#2a2d36);color:var(--dsw-alias-label-primary,#f2f4f7);',
494
+ 'box-shadow:0 12px 32px rgba(0,0,0,.32);font-family:inherit;font-size:12.5px;line-height:1.5}',
495
+ '.dsa-move-text{flex:1 1 280px;min-width:0}',
496
+ '.dsa-move-title{font-weight:600}',
497
+ '.dsa-move-state{display:block;font-size:11.5px;color:var(--dsw-alias-label-secondary,#a3a8b4);word-break:break-all}',
498
+ '.dsa-move-state.is-ready{color:#ff8a3d}',
499
+ '.dsa-move-state.is-error{color:var(--dsw-alias-state-error-primary,#ff6b6b)}',
500
+ '.dsa-move-reason{width:170px;height:26px;font-size:12px}',
501
+ '.dsa-item-main{flex:1;min-width:0}',
502
+ '.dsa-quote{margin:0;font-size:12.5px;line-height:1.55;color:var(--dsw-alias-label-primary,#f2f4f7);',
503
+ 'overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;word-break:break-word}',
504
+ '.dsa-note{margin:3px 0 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-primary,#f2f4f7);word-break:break-word;',
505
+ 'border-left:2px solid var(--dsw-alias-border-l1,#3b3f4a);padding-left:7px;white-space:pre-wrap}',
506
+ '.dsa-note b{font-weight:600;color:var(--dsw-alias-label-secondary,#a3a8b4);margin-right:4px}',
507
+ '.dsa-meta{margin:3px 0 0;font-size:11px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f9c);',
508
+ 'font-variant-numeric:tabular-nums;display:flex;gap:6px;flex-wrap:wrap;align-items:center}',
509
+ '.dsa-status{padding:0 5px;border-radius:4px;background:var(--dsw-alias-bg-layer-2,#343844)}',
510
+ '.dsa-status.is-pending{color:var(--dsw-alias-brand-primary,#4d7cfe)}',
511
+ '.dsa-item-actions{flex:none;display:flex;gap:2px}',
512
+ '.dsa-item-btn{width:22px;height:22px;padding:0;display:inline-grid;place-items:center;border:0;',
513
+ 'border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;',
514
+ 'font-size:13px;line-height:1;cursor:pointer;opacity:.7}',
515
+ '.dsa-item-btn:hover{opacity:1;background:var(--dsw-alias-interactive-bg-hover,#343844);color:var(--dsw-alias-label-primary,#f2f4f7)}',
516
+ '.dsa-item-btn.is-del:hover{color:var(--dsw-alias-state-error-primary,#e5484d);',
517
+ 'background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#e5484d) 12%,transparent)}',
518
+ '.dsa-lessons{flex:none;max-height:170px;overflow-y:auto;border-top:1px solid var(--dsw-alias-border-l1,#3b3f4a);padding:6px 10px 4px}',
519
+ '.dsa-lessons-title{margin:0 0 4px;font-size:11.5px;font-weight:600;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
520
+ '.dsa-lesson{display:flex;align-items:flex-start;gap:6px;padding:3px 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-primary,#f2f4f7)}',
521
+ '.dsa-lesson span{flex:1;min-width:0;word-break:break-word}',
522
+ '.dsa-lesson small{flex:none;color:var(--dsw-alias-label-tertiary,#8a8f9c);font-variant-numeric:tabular-nums}',
523
+ '.dsa-lessons-empty{margin:0 0 4px;font-size:11.5px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a8f9c)}',
524
+ '.dsa-panel-foot{flex:none;display:flex;align-items:center;gap:8px;padding:8px 12px 10px;flex-wrap:wrap;',
525
+ 'border-top:1px solid var(--dsw-alias-border-l1,#3b3f4a)}',
526
+ '.dsa-hint{flex:1 1 100%;min-width:0;margin:0;font-size:11px;line-height:15px;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
527
+ '.dsa-btn{flex:none;height:26px;padding:0 10px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1,#3b3f4a);',
528
+ 'background:transparent;color:var(--dsw-alias-label-primary,#f2f4f7);font:inherit;font-size:12px;cursor:pointer}',
529
+ '.dsa-btn.is-primary{background:var(--dsw-alias-brand-primary,#4d7cfe);border-color:transparent;color:var(--dsw-alias-label-primary-foreground,#10131a)}',
530
+ '.dsa-btn:hover:not(:disabled){filter:brightness(1.1);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
531
+ '.dsa-btn.is-primary:hover:not(:disabled){background:var(--dsw-alias-brand-primary,#4d7cfe)}',
532
+ '.dsa-btn:disabled{opacity:.5;cursor:default}',
533
+ '.dsa-warning,.dsa-error{flex:none;margin:8px 10px 0;padding:7px 9px;border-radius:8px;font-size:11.5px;line-height:16px}',
534
+ '.dsa-warning{color:var(--dsw-alias-state-warn-primary,#f0b35b);',
535
+ 'background:color-mix(in srgb,var(--dsw-alias-state-warn-primary,#f0b35b) 12%,transparent)}',
536
+ '.dsa-error{color:var(--dsw-alias-state-error-primary,#ff6b6b);',
537
+ 'background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#e5484d) 12%,transparent)}',
538
+ '@media (max-width:560px){.dsa-panel{top:56px;right:8px;left:8px;width:auto;max-width:none}}',
539
+ '@media (prefers-reduced-motion:reduce){.dsa-panel{animation:none}}',
540
+ ]
541
+ STYLES.forEach(function (style) {
542
+ CSS_LINES.push('::highlight(' + highlightName(style, 'pending') + '){' + MARK_COLORS[style].pending + '}')
543
+ CSS_LINES.push('::highlight(' + highlightName(style, 'resolved') + '){' + MARK_COLORS[style].resolved + '}')
544
+ })
545
+ CSS_LINES.push('::highlight(dsa-move-pending){background-color:color-mix(in srgb,#ff8a3d 34%,transparent);text-decoration:underline dashed;text-decoration-thickness:2px;text-decoration-color:#ff8a3d}')
546
+ CSS_LINES.push('::highlight(dsa-move-replace){background-color:color-mix(in srgb,#ff8a3d 26%,transparent);text-decoration:line-through;text-decoration-thickness:2px;text-decoration-color:#ff8a3d}')
547
+ CSS_LINES.push('.dsa-caret{position:fixed;z-index:69;width:2px;margin-left:-1px;border-radius:1px;background:#ff8a3d;pointer-events:none;' +
548
+ 'box-shadow:0 0 0 1px color-mix(in srgb,#ff8a3d 35%,transparent);animation:dsa-blink 1.06s steps(1,end) infinite}')
549
+ CSS_LINES.push('.dsa-caret.is-saved{opacity:.85}')
550
+ CSS_LINES.push('@keyframes dsa-blink{0%{opacity:1}50%{opacity:0}}')
551
+ CSS_LINES.push('#' + CARET_LAYER_ID + '.is-scrolling .dsa-caret{visibility:hidden}')
552
+ CSS_LINES.push('@media (prefers-reduced-motion:reduce){.dsa-caret{animation:none}}')
553
+ CSS_LINES.push('::highlight(dsa-ref-pending){background-color:color-mix(in srgb,#19b5c9 34%,transparent);text-decoration:underline double;text-decoration-color:#19b5c9}')
554
+ var CSS_TEXT = CSS_LINES.join('\n')
555
+
556
+ // ------------------------------------------------------------------- icons
557
+
558
+ function MarkerIcon(props) {
559
+ var size = props && typeof props.size === 'number' ? props.size : 16
560
+ return h(
561
+ 'svg',
562
+ { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
563
+ h('path', { d: 'M9.8 2.4l3.8 3.8-6.6 6.6H3.1v-3.9l6.7-6.5z', stroke: 'currentColor', strokeWidth: 1.2, strokeLinejoin: 'round' }),
564
+ h('path', { d: 'M8.5 3.7l3.8 3.8', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }),
565
+ h('path', { d: 'M3.3 14.2h9.4', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }),
566
+ )
567
+ }
568
+
569
+ // ------------------------------------------------------------------- utils
570
+
571
+ function hasOwn(object, key) {
572
+ return Object.prototype.hasOwnProperty.call(object, key)
573
+ }
574
+
575
+ function clipString(value, max) {
576
+ if (typeof value !== 'string') return ''
577
+ return value.length > max ? value.slice(0, max) : value
578
+ }
579
+
580
+ function pad2(value) {
581
+ return String(value).padStart(2, '0')
582
+ }
583
+
584
+ function formatTimestamp(value) {
585
+ try {
586
+ var date = new Date(value)
587
+ if (Number.isNaN(date.getTime())) return ''
588
+ return (
589
+ date.getFullYear() + '-' + pad2(date.getMonth() + 1) + '-' + pad2(date.getDate()) +
590
+ ' ' + pad2(date.getHours()) + ':' + pad2(date.getMinutes())
591
+ )
592
+ } catch (error) {
593
+ return ''
594
+ }
595
+ }
596
+
597
+ function previewQuote(quote, max) {
598
+ var limit = typeof max === 'number' ? max : 140
599
+ var text = String(quote || '').replace(/\s+/g, ' ').trim()
600
+ if (text.length > limit) return text.slice(0, limit) + '…'
601
+ return text
602
+ }
603
+
604
+ function compareCreatedAt(left, right) {
605
+ var leftTime = Date.parse(left && left.createdAt) || 0
606
+ var rightTime = Date.parse(right && right.createdAt) || 0
607
+ if (leftTime === rightTime) return 0
608
+ return leftTime < rightTime ? -1 : 1
609
+ }
610
+
611
+ function createClientId() {
612
+ return 'ann_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8)
613
+ }
614
+
615
+ function errorText(t, error) {
616
+ if (!error || typeof error !== 'object') return ''
617
+ if (error.code === 'http' && typeof error.message === 'string' && error.message.length > 0) return error.message
618
+ var key = 'err.' + (typeof error.code === 'string' ? error.code : 'generic')
619
+ var localized = t(key)
620
+ if (localized !== key) return localized
621
+ if (typeof error.message === 'string' && error.message.length > 0) return error.message
622
+ return t('err.generic')
623
+ }
624
+
625
+ function failureToError(failure, operation) {
626
+ var code = failure && typeof failure.code === 'string' ? failure.code : 'http'
627
+ var message = failure && typeof failure.message === 'string' ? failure.message : ''
628
+ if (code === 'network') return { code: 'network', operation: operation, message: message }
629
+ if (code === 'http') return { code: 'http', operation: operation, message: message }
630
+ return { code: operation || 'generic', message: message }
631
+ }
632
+
633
+ function isStyle(value) {
634
+ return STYLES.indexOf(value) >= 0
635
+ }
636
+
637
+ function normalizeMode(value) {
638
+ return MODES.indexOf(value) >= 0 ? value : 'brief'
639
+ }
640
+
641
+ // ------------------------------------------------------------ DOM helpers
642
+
643
+ function elementOfNode(node) {
644
+ if (!node) return null
645
+ if (node.nodeType === 1) return node
646
+ if (node.parentElement) return node.parentElement
647
+ return null
648
+ }
649
+
650
+ function isOurUiNode(node) {
651
+ try {
652
+ var element = elementOfNode(node)
653
+ if (!element || typeof element.closest !== 'function') return false
654
+ return element.closest(UI_SELECTOR) !== null
655
+ } catch (error) {
656
+ return false
657
+ }
658
+ }
659
+
660
+ function isOurUiElement(element) {
661
+ if (!element || element.nodeType !== 1 || typeof element.closest !== 'function') return false
662
+ try {
663
+ return element.closest(UI_SELECTOR) !== null
664
+ } catch (error) {
665
+ return false
666
+ }
667
+ }
668
+
669
+ function isSkippedElement(element, checkOwnUi) {
670
+ if (!element || element.nodeType !== 1) return false
671
+ var tag = typeof element.tagName === 'string' ? element.tagName.toLowerCase() : ''
672
+ if (tag === 'script' || tag === 'style' || tag === 'noscript') return true
673
+ if (checkOwnUi === false) return false
674
+ return isOurUiElement(element)
675
+ }
676
+
677
+ function isScrollContainer(element) {
678
+ try {
679
+ if (!element || element.nodeType !== 1) return false
680
+ if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return false
681
+ var style = window.getComputedStyle(element)
682
+ if (!style) return false
683
+ var overflowY = style.overflowY
684
+ if (overflowY !== 'auto' && overflowY !== 'scroll') return false
685
+ return element.scrollHeight > element.clientHeight + 20
686
+ } catch (error) {
687
+ return false
688
+ }
689
+ }
690
+
691
+ // The nearest scrollable ancestor of the selection is the indexing root; when
692
+ // there is none the whole body is. Host class names are never consulted.
693
+ function findRoot(range) {
694
+ try {
695
+ var current = elementOfNode(range && range.commonAncestorContainer)
696
+ while (current && current !== document.documentElement) {
697
+ if (!isOurUiElement(current) && isScrollContainer(current)) return current
698
+ current = current.parentElement
699
+ }
700
+ } catch (error) {
701
+ console.error('dsh-mindmark: cannot find the selection root', error)
702
+ }
703
+ return document.body
704
+ }
705
+
706
+ // Raw text-node values in document order (never whitespace-normalized), with
707
+ // cumulative offsets, skipping our own UI and script/style subtrees.
708
+ function buildIndex(root) {
709
+ var nodes = []
710
+ var starts = new Map()
711
+ var text = ''
712
+ try {
713
+ if (!root) return { nodes: nodes, text: text, starts: starts }
714
+ var checkOwnUi = root === document.body
715
+ var walker = document.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */, null)
716
+ var node = walker.nextNode()
717
+ while (node !== null) {
718
+ if (!isSkippedElement(node.parentElement, checkOwnUi)) {
719
+ var value = node.nodeValue
720
+ if (typeof value === 'string' && value.length > 0) {
721
+ nodes.push({ node: node, start: text.length, length: value.length })
722
+ starts.set(node, text.length)
723
+ text += value
724
+ }
725
+ }
726
+ node = walker.nextNode()
727
+ }
728
+ } catch (error) {
729
+ console.error('dsh-mindmark: text indexing failed', error)
730
+ }
731
+ return { nodes: nodes, text: text, starts: starts }
732
+ }
733
+
734
+ function firstIndexedTextNodeIn(subtree, index) {
735
+ if (!subtree) return null
736
+ if (subtree.nodeType === 3) return index.starts.has(subtree) ? subtree : null
737
+ if (subtree.nodeType !== 1) return null
738
+ try {
739
+ var walker = document.createTreeWalker(subtree, 4, null)
740
+ var node = walker.nextNode()
741
+ while (node !== null) {
742
+ if (index.starts.has(node)) return node
743
+ node = walker.nextNode()
744
+ }
745
+ } catch (error) {
746
+ /* the subtree is unreadable: treat it as containing no text */
747
+ }
748
+ return null
749
+ }
750
+
751
+ function lastIndexedTextNodeIn(container, index) {
752
+ try {
753
+ if (!container || typeof document.createTreeWalker !== 'function') return null
754
+ var walker = document.createTreeWalker(container, 4, null)
755
+ var node = walker.nextNode()
756
+ var last = null
757
+ while (node !== null) {
758
+ if (index.starts.has(node)) last = node
759
+ node = walker.nextNode()
760
+ }
761
+ return last
762
+ } catch (error) {
763
+ return null
764
+ }
765
+ }
766
+
767
+ function offsetOf(index, container, offset) {
768
+ try {
769
+ if (!index || !container) return 0
770
+ if (container.nodeType === 3) {
771
+ var known = index.starts.get(container)
772
+ if (typeof known === 'number') {
773
+ var length = typeof container.nodeValue === 'string' ? container.nodeValue.length : 0
774
+ var local = typeof offset === 'number' ? offset : 0
775
+ return known + Math.max(0, Math.min(local, length))
776
+ }
777
+ return index.text.length
778
+ }
779
+ var children = container.childNodes
780
+ if (!children) return index.text.length
781
+ var position = typeof offset === 'number' ? Math.max(0, Math.min(offset, children.length)) : 0
782
+ for (var childIndexValue = position; childIndexValue < children.length; childIndexValue += 1) {
783
+ var staged = firstIndexedTextNodeIn(children[childIndexValue], index)
784
+ if (staged !== null) {
785
+ var stagedStart = index.starts.get(staged)
786
+ if (typeof stagedStart === 'number') return stagedStart
787
+ }
788
+ }
789
+ var lastText = lastIndexedTextNodeIn(container, index)
790
+ if (lastText !== null) {
791
+ var lastStart = index.starts.get(lastText)
792
+ if (typeof lastStart === 'number') {
793
+ return lastStart + (typeof lastText.nodeValue === 'string' ? lastText.nodeValue.length : 0)
794
+ }
795
+ }
796
+ return index.text.length
797
+ } catch (error) {
798
+ console.error('dsh-mindmark: offset lookup failed', error)
799
+ return 0
800
+ }
801
+ }
802
+
803
+ function escapeIdent(value) {
804
+ var text = String(value)
805
+ try {
806
+ if (typeof CSS !== 'undefined' && CSS && typeof CSS.escape === 'function') return CSS.escape(text)
807
+ } catch (error) {
808
+ /* fall through to the hand-rolled escape */
809
+ }
810
+ return text.replace(/([^a-zA-Z0-9_-])/g, '\\$1')
811
+ }
812
+
813
+ function elementSiblingIndex(element) {
814
+ var index = 1
815
+ var sibling = element
816
+ while (sibling && sibling.previousElementSibling) {
817
+ sibling = sibling.previousElementSibling
818
+ index += 1
819
+ }
820
+ return index
821
+ }
822
+
823
+ function cssPath(element) {
824
+ try {
825
+ if (!element || element.nodeType !== 1) return ''
826
+ var segments = []
827
+ var current = element
828
+ var depth = 0
829
+ while (current && current.nodeType === 1 && depth < 6) {
830
+ if (current === document.documentElement) {
831
+ segments.unshift('html')
832
+ break
833
+ }
834
+ if (current === document.body) {
835
+ segments.unshift('body')
836
+ break
837
+ }
838
+ var tag = typeof current.tagName === 'string' ? current.tagName.toLowerCase() : ''
839
+ if (tag.length === 0) break
840
+ var segment = tag
841
+ if (current.id) {
842
+ segment += '#' + escapeIdent(current.id)
843
+ segments.unshift(segment)
844
+ break
845
+ }
846
+ var classList = current.classList
847
+ var classCount = 0
848
+ if (classList && classList.length > 0) {
849
+ for (var index = 0; index < classList.length && classCount < 3; index += 1) {
850
+ var className = classList[index]
851
+ if (typeof className !== 'string' || className.length === 0 || className.length > 40) continue
852
+ segment += '.' + escapeIdent(className)
853
+ classCount += 1
854
+ }
855
+ }
856
+ var parent = current.parentElement
857
+ if (parent) segment += ':nth-child(' + elementSiblingIndex(current) + ')'
858
+ segments.unshift(segment)
859
+ current = parent
860
+ depth += 1
861
+ }
862
+ var path = segments.join(' > ')
863
+ while (segments.length > 1 && path.length > SELECTOR_MAX) {
864
+ segments.shift()
865
+ path = segments.join(' > ')
866
+ }
867
+ return path.length > SELECTOR_MAX ? '' : path
868
+ } catch (error) {
869
+ console.error('dsh-mindmark: cannot build a CSS path', error)
870
+ return ''
871
+ }
872
+ }
873
+
874
+ function resolveRoot(selector) {
875
+ try {
876
+ if (typeof selector === 'string' && selector.length > 0 && selector.length <= SELECTOR_MAX) {
877
+ var element = document.querySelector(selector)
878
+ if (element && element.nodeType === 1 && !isOurUiElement(element)) return element
879
+ }
880
+ } catch (error) {
881
+ /* a stale or malformed selector falls back to body */
882
+ }
883
+ return document.body
884
+ }
885
+
886
+ // --------------------------------------------------------- anchoring
887
+
888
+ function commonPrefixLen(left, right) {
889
+ if (typeof left !== 'string' || typeof right !== 'string') return 0
890
+ var max = Math.min(left.length, right.length)
891
+ var index = 0
892
+ while (index < max && left.charCodeAt(index) === right.charCodeAt(index)) index += 1
893
+ return index
894
+ }
895
+
896
+ function commonSuffixLen(left, right) {
897
+ if (typeof left !== 'string' || typeof right !== 'string') return 0
898
+ var max = Math.min(left.length, right.length)
899
+ var index = 0
900
+ while (index < max && left.charCodeAt(left.length - 1 - index) === right.charCodeAt(right.length - 1 - index)) {
901
+ index += 1
902
+ }
903
+ return index
904
+ }
905
+
906
+ function positionAtOffset(index, offset) {
907
+ var nodes = index.nodes
908
+ if (!nodes || nodes.length === 0) return null
909
+ if (offset <= 0) return { node: nodes[0].node, offset: 0 }
910
+ if (offset >= index.text.length) {
911
+ var last = nodes[nodes.length - 1]
912
+ var lastLength = typeof last.node.nodeValue === 'string' ? last.node.nodeValue.length : 0
913
+ return { node: last.node, offset: lastLength }
914
+ }
915
+ var low = 0
916
+ var high = nodes.length - 1
917
+ var found = 0
918
+ while (low <= high) {
919
+ var mid = (low + high) >> 1
920
+ if (nodes[mid].start <= offset) {
921
+ found = mid
922
+ low = mid + 1
923
+ } else {
924
+ high = mid - 1
925
+ }
926
+ }
927
+ var entry = nodes[found]
928
+ var local = offset - entry.start
929
+ var maxLocal = typeof entry.node.nodeValue === 'string' ? entry.node.nodeValue.length : 0
930
+ return { node: entry.node, offset: Math.max(0, Math.min(local, maxLocal)) }
931
+ }
932
+
933
+ function rangeFromOffsets(index, start, end) {
934
+ var maxOffset = index.text.length
935
+ var safeStart = Math.max(0, Math.min(start, maxOffset))
936
+ var safeEnd = Math.max(0, Math.min(end, maxOffset))
937
+ if (safeEnd <= safeStart) return null
938
+ var startPosition = positionAtOffset(index, safeStart)
939
+ var endPosition = positionAtOffset(index, safeEnd)
940
+ if (startPosition === null || endPosition === null) return null
941
+ try {
942
+ var range = document.createRange()
943
+ range.setStart(startPosition.node, startPosition.offset)
944
+ range.setEnd(endPosition.node, endPosition.offset)
945
+ return range
946
+ } catch (error) {
947
+ return null
948
+ }
949
+ }
950
+
951
+ function locateAnnotationRange(annotation, index) {
952
+ try {
953
+ if (!annotation || typeof annotation.quote !== 'string' || annotation.quote.length === 0) return null
954
+ var text = index.text
955
+ if (!text || text.length === 0) return null
956
+ var quote = annotation.quote
957
+ var prefix = typeof annotation.prefix === 'string' ? annotation.prefix : ''
958
+ var suffix = typeof annotation.suffix === 'string' ? annotation.suffix : ''
959
+ var bestStart = -1
960
+ var bestScore = -1
961
+ var bestPossible = prefix.length + suffix.length
962
+ var searchFrom = 0
963
+ var guard = 0
964
+ while (guard < 500) {
965
+ var found = text.indexOf(quote, searchFrom)
966
+ if (found === -1) break
967
+ var score = 0
968
+ var beforeContext = text.slice(Math.max(0, found - prefix.length), found)
969
+ score += commonSuffixLen(prefix, beforeContext)
970
+ var afterContext = text.slice(found + quote.length, found + quote.length + suffix.length)
971
+ score += commonPrefixLen(suffix, afterContext)
972
+ if (score > bestScore) {
973
+ bestScore = score
974
+ bestStart = found
975
+ }
976
+ if (bestScore >= bestPossible) break
977
+ searchFrom = found + 1
978
+ guard += 1
979
+ }
980
+ if (bestStart < 0) return null
981
+ return rangeFromOffsets(index, bestStart, bestStart + quote.length)
982
+ } catch (error) {
983
+ return null
984
+ }
985
+ }
986
+
987
+ function ensureIndexEntry(cache, selector) {
988
+ var key = typeof selector === 'string' ? selector : ''
989
+ if (hasOwn(cache, key)) return cache[key]
990
+ var entry = null
991
+ try {
992
+ var root = resolveRoot(key)
993
+ entry = { root: root, index: buildIndex(root) }
994
+ } catch (error) {
995
+ entry = null
996
+ }
997
+ cache[key] = entry
998
+ return entry
999
+ }
1000
+
1001
+ function collectRanges(annotations) {
1002
+ var resolved = []
1003
+ var cache = {}
1004
+ for (var index = 0; index < annotations.length; index += 1) {
1005
+ var annotation = annotations[index]
1006
+ try {
1007
+ var entry = ensureIndexEntry(cache, annotation.rootSelector)
1008
+ if (entry === null) continue
1009
+ var range = locateAnnotationRange(annotation, entry.index)
1010
+ if (range !== null) resolved.push({ annotation: annotation, range: range })
1011
+ } catch (error) {
1012
+ /* one bad record must not stop the others */
1013
+ }
1014
+ }
1015
+ return resolved
1016
+ }
1017
+
1018
+ // ------------------------------------------------------------- painting
1019
+
1020
+ function supportsHighlights() {
1021
+ try {
1022
+ if (typeof Highlight !== 'function') return false
1023
+ if (typeof CSS === 'undefined' || CSS === null) return false
1024
+ return CSS.highlights !== undefined && CSS.highlights !== null
1025
+ } catch (error) {
1026
+ return false
1027
+ }
1028
+ }
1029
+
1030
+ function setHighlightGroup(name, ranges) {
1031
+ try {
1032
+ if (!supportsHighlights()) return
1033
+ var registry = CSS.highlights
1034
+ if (ranges.length === 0) {
1035
+ registry.delete(name)
1036
+ return
1037
+ }
1038
+ var group = null
1039
+ try {
1040
+ group = new Highlight(...ranges)
1041
+ } catch (error) {
1042
+ group = null
1043
+ }
1044
+ if (group === null) {
1045
+ group = new Highlight()
1046
+ for (var index = 0; index < ranges.length; index += 1) group.add(ranges[index])
1047
+ }
1048
+ registry.set(name, group)
1049
+ } catch (error) {
1050
+ console.error('dsh-mindmark: cannot paint highlights', error)
1051
+ }
1052
+ }
1053
+
1054
+ function clearHighlights() {
1055
+ try {
1056
+ if (!supportsHighlights()) return
1057
+ STYLES.forEach(function (style) {
1058
+ CSS.highlights.delete(highlightName(style, 'pending'))
1059
+ CSS.highlights.delete(highlightName(style, 'resolved'))
1060
+ })
1061
+ MOVE_EXTRA_HIGHLIGHTS.forEach(function (name) {
1062
+ CSS.highlights.delete(name)
1063
+ })
1064
+ removeCarets()
1065
+ } catch (error) {
1066
+ console.error('dsh-mindmark: cannot clear highlights', error)
1067
+ }
1068
+ }
1069
+
1070
+ var applyTimer = null
1071
+
1072
+ function paintHighlightsNow() {
1073
+ try {
1074
+ if (!supportsHighlights()) return
1075
+ var current = getState()
1076
+ var annotations = current.sessionId !== null && Array.isArray(current.annotations) ? current.annotations : []
1077
+ var resolved = annotations.length === 0 ? [] : collectRanges(annotations)
1078
+ var groups = {}
1079
+ STYLES.forEach(function (style) {
1080
+ groups[highlightName(style, 'pending')] = []
1081
+ groups[highlightName(style, 'resolved')] = []
1082
+ })
1083
+ for (var index = 0; index < resolved.length; index += 1) {
1084
+ var item = resolved[index]
1085
+ var name = highlightName(item.annotation.style, item.annotation.status)
1086
+ if (groups[name]) groups[name].push(item.range)
1087
+ }
1088
+ MOVE_EXTRA_HIGHLIGHTS.forEach(function (extra) {
1089
+ groups[extra] = []
1090
+ })
1091
+ var cache = {}
1092
+ var carets = []
1093
+ function markTarget(entry, prefix, quote, suffix, saved) {
1094
+ if (entry === null) return
1095
+ var spot = locateTargetIn(entry.index, prefix, quote, suffix)
1096
+ if (spot === null) return
1097
+ if (spot.end > spot.start) {
1098
+ var replaced = rangeFromOffsets(entry.index, spot.start, spot.end)
1099
+ if (replaced !== null) groups['dsa-move-replace'].push(replaced)
1100
+ } else {
1101
+ var box = visibleCaret(entry, spot.start, saved)
1102
+ if (box !== null) carets.push(box)
1103
+ }
1104
+ }
1105
+ for (var moveIndex = 0; moveIndex < annotations.length; moveIndex += 1) {
1106
+ var move = annotations[moveIndex]
1107
+ if (move.style !== 'move' || move.status === 'resolved') continue
1108
+ markTarget(ensureIndexEntry(cache, move.rootSelector), move.targetPrefix, move.targetQuote, move.targetSuffix, true)
1109
+ }
1110
+ var pendingRef = current.referenceDraft
1111
+ if (pendingRef && pendingRef.built && current.sessionId !== null) {
1112
+ var refEntry = ensureIndexEntry(cache, pendingRef.built.record.rootSelector)
1113
+ var refRange = refEntry === null ? null : locateAnnotationRange(pendingRef.built.record, refEntry.index)
1114
+ if (refRange !== null) groups['dsa-ref-pending'].push(refRange)
1115
+ }
1116
+ var pendingMove = current.pendingMove
1117
+ if (pendingMove && pendingMove.built && current.sessionId !== null) {
1118
+ var pendingEntry = ensureIndexEntry(cache, pendingMove.built.record.rootSelector)
1119
+ if (pendingEntry !== null) {
1120
+ var sourceRange = locateAnnotationRange(pendingMove.built.record, pendingEntry.index)
1121
+ if (sourceRange !== null) groups['dsa-move-pending'].push(sourceRange)
1122
+ if (pendingMove.target) {
1123
+ markTarget(pendingEntry, pendingMove.target.prefix, pendingMove.target.quote, pendingMove.target.suffix, false)
1124
+ }
1125
+ }
1126
+ }
1127
+ drawCarets(carets)
1128
+ Object.keys(groups).forEach(function (name) {
1129
+ setHighlightGroup(name, groups[name])
1130
+ })
1131
+ } catch (error) {
1132
+ console.error('dsh-mindmark: repaint failed', error)
1133
+ }
1134
+ }
1135
+
1136
+ function cancelPaintTimer() {
1137
+ if (applyTimer !== null) {
1138
+ clearTimeout(applyTimer)
1139
+ applyTimer = null
1140
+ }
1141
+ }
1142
+
1143
+ function schedulePaint(delay) {
1144
+ try {
1145
+ if (applyTimer !== null) return
1146
+ var wait = typeof delay === 'number' && delay >= 0 ? delay : MUTATION_DEBOUNCE
1147
+ applyTimer = setTimeout(function () {
1148
+ applyTimer = null
1149
+ paintHighlightsNow()
1150
+ }, wait)
1151
+ } catch (error) {
1152
+ console.error('dsh-mindmark: cannot schedule a repaint', error)
1153
+ }
1154
+ }
1155
+
1156
+ function paintNow() {
1157
+ cancelPaintTimer()
1158
+ paintHighlightsNow()
1159
+ }
1160
+
1161
+ // ----------------------------------------------- selection → record
1162
+
1163
+ function readLiveRange() {
1164
+ var nativeSelection = null
1165
+ try {
1166
+ nativeSelection = typeof window.getSelection === 'function' ? window.getSelection() : null
1167
+ } catch (error) {
1168
+ return null
1169
+ }
1170
+ if (!nativeSelection || nativeSelection.rangeCount === 0 || nativeSelection.isCollapsed) return null
1171
+ var text = ''
1172
+ try {
1173
+ text = nativeSelection.toString()
1174
+ } catch (error) {
1175
+ return null
1176
+ }
1177
+ if (typeof text !== 'string' || text.trim().length === 0 || text.length > MAX_QUOTE) return null
1178
+ try {
1179
+ var range = nativeSelection.getRangeAt(0)
1180
+ if (!range || !range.startContainer || !range.endContainer) return null
1181
+ if (isOurUiNode(range.startContainer) || isOurUiNode(range.endContainer)) return null
1182
+ return range
1183
+ } catch (error) {
1184
+ return null
1185
+ }
1186
+ }
1187
+
1188
+ // The message body is the Chat view's own interaction source element (the
1189
+ // rendered Markdown of one assistant answer); the flow item above it carries
1190
+ // the node key and the turn. Only attribute names the Chat view documents
1191
+ // for plugins are consulted, and a miss simply yields an unanchored record.
1192
+ function locateMessage(range) {
1193
+ try {
1194
+ var element = elementOfNode(range.commonAncestorContainer)
1195
+ if (!element || typeof element.closest !== 'function') return null
1196
+ var body = element.closest('[data-text-interaction-source]')
1197
+ if (!body) return null
1198
+ var item = body.closest('[data-chat-node-key]')
1199
+ var key = item && typeof item.getAttribute === 'function' ? item.getAttribute('data-chat-node-key') : null
1200
+ var turnRaw = item && typeof item.getAttribute === 'function' ? item.getAttribute('data-chat-turn') : null
1201
+ var turn = turnRaw !== null && /^\d+$/.test(turnRaw) ? Number(turnRaw) : undefined
1202
+ var index = buildIndex(body)
1203
+ if (!index.text || index.text.length === 0 || index.text.length > MAX_MESSAGE_TEXT) return null
1204
+ var start = offsetOf(index, range.startContainer, range.startOffset)
1205
+ var end = offsetOf(index, range.endContainer, range.endOffset)
1206
+ if (!(end > start)) return null
1207
+ if (!key) key = 'text:' + hashText(index.text)
1208
+ return { key: clipString(key, 200), text: index.text, turn: turn, start: start, end: end }
1209
+ } catch (error) {
1210
+ return null
1211
+ }
1212
+ }
1213
+
1214
+ // The rendered body of one answer that contains `node`, or null.
1215
+ function messageBodyOf(node) {
1216
+ var element = elementOfNode(node)
1217
+ if (!element || typeof element.closest !== 'function' || isOurUiElement(element)) return null
1218
+ try {
1219
+ return element.closest('[data-text-interaction-source]')
1220
+ } catch (error) {
1221
+ return null
1222
+ }
1223
+ }
1224
+
1225
+ function messageKeyOf(body, index) {
1226
+ var item = body.closest('[data-chat-node-key]')
1227
+ var key = item && typeof item.getAttribute === 'function' ? item.getAttribute('data-chat-node-key') : null
1228
+ if (!key) key = 'text:' + hashText(index.text)
1229
+ return clipString(key, 200)
1230
+ }
1231
+
1232
+ // Where a move would land, read from the selection inside an answer: a
1233
+ // collapsed selection (a click) is an insertion point; a selection over
1234
+ // some text means that text is replaced. Returns the message key, the
1235
+ // offsets, the replaced text (`quote`, '' for an insertion) and the text
1236
+ // right before and after.
1237
+ function caretTarget() {
1238
+ try {
1239
+ var nativeSelection = typeof window.getSelection === 'function' ? window.getSelection() : null
1240
+ if (!nativeSelection || nativeSelection.rangeCount === 0) return null
1241
+ var range = nativeSelection.getRangeAt(0)
1242
+ var body = messageBodyOf(range.startContainer)
1243
+ if (!body) return null
1244
+ var index = buildIndex(body)
1245
+ if (!index.text || index.text.length > MAX_MESSAGE_TEXT) return null
1246
+ var offset = offsetOf(index, range.startContainer, range.startOffset)
1247
+ var end = offset
1248
+ if (!range.collapsed && messageBodyOf(range.endContainer) === body) {
1249
+ end = offsetOf(index, range.endContainer, range.endOffset)
1250
+ if (end - offset > MAX_QUOTE || index.text.slice(offset, end).trim().length === 0) end = offset
1251
+ }
1252
+ if (end < offset) end = offset
1253
+ return {
1254
+ key: messageKeyOf(body, index),
1255
+ offset: offset,
1256
+ end: end,
1257
+ quote: index.text.slice(offset, end),
1258
+ prefix: index.text.slice(Math.max(0, offset - CONTEXT_MAX), offset),
1259
+ suffix: index.text.slice(end, Math.min(index.text.length, end + CONTEXT_MAX)),
1260
+ }
1261
+ } catch (error) {
1262
+ return null
1263
+ }
1264
+ }
1265
+
1266
+ // Offsets of a move target inside an indexed root, found by its context.
1267
+ function locateTargetIn(index, prefix, quote, suffix) {
1268
+ var before = typeof prefix === 'string' ? prefix : ''
1269
+ var middle = typeof quote === 'string' ? quote : ''
1270
+ var after = typeof suffix === 'string' ? suffix : ''
1271
+ if (!index || !index.text || before.length + middle.length + after.length === 0) return null
1272
+ var found = index.text.indexOf(before + middle + after)
1273
+ if (found < 0) return null
1274
+ var start = found + before.length
1275
+ return { start: start, end: start + middle.length }
1276
+ }
1277
+
1278
+ // The on-screen box of the caret at an insertion point: the left edge of
1279
+ // the next character, or the right edge of the previous one at a line end.
1280
+ function caretBox(index, at) {
1281
+ var text = index.text
1282
+ function rectOf(start, end, side) {
1283
+ var range = rangeFromOffsets(index, start, end)
1284
+ if (range === null) return null
1285
+ var rects = range.getClientRects()
1286
+ var rect = rects.length > 0 ? (side === 'left' ? rects[0] : rects[rects.length - 1]) : null
1287
+ if (!rect || (rect.width === 0 && rect.height === 0)) return null
1288
+ return { x: side === 'left' ? rect.left : rect.right, top: rect.top, height: rect.height }
1289
+ }
1290
+ var next = at < text.length && !/\s/.test(text.charAt(at)) ? rectOf(at, at + 1, 'left') : null
1291
+ if (next !== null) return next
1292
+ var previous = at > 0 && text.charAt(at - 1) !== '\n' ? rectOf(at - 1, at, 'right') : null
1293
+ if (previous !== null) return previous
1294
+ return at < text.length ? rectOf(at, at + 1, 'left') : null
1295
+ }
1296
+
1297
+ // Blinking carets live in one fixed layer outside the chat DOM.
1298
+ var caretScrollTimer = null
1299
+
1300
+ function caretLayer() {
1301
+ var layer = document.getElementById(CARET_LAYER_ID)
1302
+ if (layer === null && document.body) {
1303
+ layer = document.createElement('div')
1304
+ layer.id = CARET_LAYER_ID
1305
+ layer.setAttribute(UI_ATTR, '1')
1306
+ layer.setAttribute('aria-hidden', 'true')
1307
+ document.body.appendChild(layer)
1308
+ }
1309
+ return layer
1310
+ }
1311
+
1312
+ function hideCaretsWhileScrolling() {
1313
+ var layer = document.getElementById(CARET_LAYER_ID)
1314
+ if (layer === null) return
1315
+ layer.classList.add('is-scrolling')
1316
+ if (caretScrollTimer !== null) clearTimeout(caretScrollTimer)
1317
+ caretScrollTimer = setTimeout(function () {
1318
+ caretScrollTimer = null
1319
+ layer.classList.remove('is-scrolling')
1320
+ }, MUTATION_DEBOUNCE + 60)
1321
+ }
1322
+
1323
+ function drawCarets(boxes) {
1324
+ var layer = caretLayer()
1325
+ if (layer === null) return
1326
+ while (layer.childNodes.length > boxes.length) layer.removeChild(layer.lastChild)
1327
+ for (var index = 0; index < boxes.length; index += 1) {
1328
+ var box = boxes[index]
1329
+ var caret = layer.childNodes[index]
1330
+ if (!caret) {
1331
+ caret = document.createElement('div')
1332
+ layer.appendChild(caret)
1333
+ }
1334
+ caret.className = 'dsa-caret' + (box.saved ? ' is-saved' : '')
1335
+ caret.style.left = box.x + 'px'
1336
+ caret.style.top = box.top + 'px'
1337
+ caret.style.height = box.height + 'px'
1338
+ }
1339
+ }
1340
+
1341
+ function removeCarets() {
1342
+ var layer = document.getElementById(CARET_LAYER_ID)
1343
+ if (layer !== null && layer.parentNode !== null) layer.parentNode.removeChild(layer)
1344
+ }
1345
+
1346
+ // A caret box clipped to its scroll container, or null when scrolled out.
1347
+ function visibleCaret(entry, at, saved) {
1348
+ var box = caretBox(entry.index, at)
1349
+ if (box === null) return null
1350
+ var bounds = entry.root && entry.root !== document.body ? entry.root.getBoundingClientRect() : null
1351
+ if (bounds && (box.top + box.height < bounds.top || box.top > bounds.bottom)) return null
1352
+ box.saved = saved === true
1353
+ return box
1354
+ }
1355
+
1356
+ function hashText(text) {
1357
+ var hash = 5381
1358
+ for (var index = 0; index < text.length; index += 1) hash = ((hash << 5) + hash + text.charCodeAt(index)) | 0
1359
+ return (hash >>> 0).toString(36)
1360
+ }
1361
+
1362
+ function buildRecord(range, style) {
1363
+ try {
1364
+ var root = findRoot(range)
1365
+ var index = buildIndex(root)
1366
+ if (!index.text || index.nodes.length === 0) return null
1367
+ var start = offsetOf(index, range.startContainer, range.startOffset)
1368
+ var end = offsetOf(index, range.endContainer, range.endOffset)
1369
+ if (!(end > start)) return null
1370
+ var quote = index.text.slice(start, end)
1371
+ if (!quote || quote.trim().length === 0 || quote.length > MAX_QUOTE) return null
1372
+ var message = locateMessage(range)
1373
+ var record = {
1374
+ id: createClientId(),
1375
+ style: isStyle(style) ? style : 'highlight',
1376
+ quote: quote,
1377
+ note: '',
1378
+ prefix: index.text.slice(Math.max(0, start - CONTEXT_MAX), start),
1379
+ suffix: index.text.slice(end, Math.min(index.text.length, end + CONTEXT_MAX)),
1380
+ rootSelector: cssPath(root),
1381
+ createdAt: new Date().toISOString(),
1382
+ status: 'pending',
1383
+ }
1384
+ if (message !== null) {
1385
+ record.messageKey = message.key
1386
+ record.messageStart = message.start
1387
+ record.messageEnd = message.end
1388
+ if (typeof message.turn === 'number') record.turn = message.turn
1389
+ }
1390
+ return { record: record, message: message === null ? null : { key: message.key, text: message.text, turn: message.turn } }
1391
+ } catch (error) {
1392
+ console.error('dsh-mindmark: cannot build the annotation record', error)
1393
+ return null
1394
+ }
1395
+ }
1396
+
1397
+ function rangesIntersect(left, right) {
1398
+ try {
1399
+ if (left.compareBoundaryPoints(1, right) >= 0) return false
1400
+ if (right.compareBoundaryPoints(1, left) >= 0) return false
1401
+ return true
1402
+ } catch (error) {
1403
+ return false
1404
+ }
1405
+ }
1406
+
1407
+ function annotationsIntersecting(range) {
1408
+ var current = getState()
1409
+ var hits = []
1410
+ if (current.sessionId === null || current.annotations.length === 0) return hits
1411
+ var cache = {}
1412
+ for (var index = 0; index < current.annotations.length; index += 1) {
1413
+ var annotation = current.annotations[index]
1414
+ var entry = ensureIndexEntry(cache, annotation.rootSelector)
1415
+ if (entry === null) continue
1416
+ var annotationRange = locateAnnotationRange(annotation, entry.index)
1417
+ if (annotationRange !== null && rangesIntersect(annotationRange, range)) hits.push(annotation.id)
1418
+ }
1419
+ return hits
1420
+ }
1421
+
1422
+ // -------------------------------------------------------------- controller
1423
+
1424
+ var state = {
1425
+ sessionId: null,
1426
+ annotations: [],
1427
+ mode: 'brief',
1428
+ lessons: [],
1429
+ loading: false,
1430
+ error: null,
1431
+ panelOpen: false,
1432
+ // { built, target, reason, error } while a passage waits for Alt+V.
1433
+ pendingMove: null,
1434
+ // The open reference form: { built, kind, title, content, url, fileName, text, error }.
1435
+ referenceDraft: null,
1436
+ }
1437
+ var stateListeners = new Set()
1438
+ var loadToken = 0
1439
+ var mutationQueue = Promise.resolve()
1440
+
1441
+ function getState() {
1442
+ return state
1443
+ }
1444
+
1445
+ function subscribeState(listener) {
1446
+ stateListeners.add(listener)
1447
+ return function () {
1448
+ stateListeners.delete(listener)
1449
+ }
1450
+ }
1451
+
1452
+ function publishState(patch) {
1453
+ var next = {}
1454
+ for (var key in state) next[key] = state[key]
1455
+ for (var patchKey in patch) next[patchKey] = patch[patchKey]
1456
+ state = next
1457
+ stateListeners.forEach(function (listener) {
1458
+ try {
1459
+ listener()
1460
+ } catch (error) {
1461
+ console.error('dsh-mindmark: state listener failed', error)
1462
+ }
1463
+ })
1464
+ }
1465
+
1466
+ function enqueueMutation(run) {
1467
+ mutationQueue = mutationQueue.then(run, run).catch(function (error) {
1468
+ console.error('dsh-mindmark: mutation failed', error)
1469
+ })
1470
+ return mutationQueue
1471
+ }
1472
+
1473
+ function normalizeAnnotation(raw) {
1474
+ if (!raw || typeof raw !== 'object') return null
1475
+ var id = typeof raw.id === 'string' ? raw.id : ''
1476
+ if (id.length === 0 || id.length > ID_MAX) return null
1477
+ if (!isStyle(raw.style)) return null
1478
+ var quote = typeof raw.quote === 'string' ? raw.quote : ''
1479
+ if (quote.length === 0 || quote.trim().length === 0 || quote.length > MAX_QUOTE) return null
1480
+ var record = {
1481
+ id: id,
1482
+ style: raw.style,
1483
+ quote: quote,
1484
+ note: clipString(raw.note, MAX_NOTE),
1485
+ prefix: clipString(raw.prefix, CONTEXT_MAX),
1486
+ suffix: clipString(raw.suffix, CONTEXT_MAX),
1487
+ rootSelector: clipString(raw.rootSelector, SELECTOR_MAX),
1488
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : '',
1489
+ status: raw.status === 'resolved' ? 'resolved' : 'pending',
1490
+ resolvedBy: typeof raw.resolvedBy === 'string' ? raw.resolvedBy : '',
1491
+ injections: typeof raw.injections === 'number' ? raw.injections : 0,
1492
+ }
1493
+ if (typeof raw.messageKey === 'string' && raw.messageKey.length > 0) {
1494
+ record.messageKey = raw.messageKey
1495
+ record.messageStart = raw.messageStart
1496
+ record.messageEnd = raw.messageEnd
1497
+ }
1498
+ if (typeof raw.turn === 'number') record.turn = raw.turn
1499
+ if (raw.style === 'move') {
1500
+ record.targetPrefix = clipString(raw.targetPrefix, CONTEXT_MAX)
1501
+ record.targetSuffix = clipString(raw.targetSuffix, CONTEXT_MAX)
1502
+ if (record.targetPrefix.length === 0 && record.targetSuffix.length === 0) return null
1503
+ if (typeof raw.targetOffset === 'number') record.targetOffset = raw.targetOffset
1504
+ if (typeof raw.targetQuote === 'string' && raw.targetQuote.trim().length > 0) {
1505
+ record.targetQuote = clipString(raw.targetQuote, MAX_QUOTE)
1506
+ if (typeof raw.targetEnd === 'number') record.targetEnd = raw.targetEnd
1507
+ }
1508
+ }
1509
+ if (raw.style === 'reference') {
1510
+ var material = normalizeMaterial(raw.material)
1511
+ if (material === null) return null
1512
+ record.material = material
1513
+ }
1514
+ return record
1515
+ }
1516
+
1517
+ // Display-side material metadata; the content itself stays on the Host.
1518
+ function normalizeMaterial(raw) {
1519
+ if (!raw || typeof raw !== 'object' || MATERIAL_KINDS.indexOf(raw.kind) < 0) return null
1520
+ var title = clipString(typeof raw.title === 'string' ? raw.title : '', 120)
1521
+ if (raw.kind === 'url') {
1522
+ var url = typeof raw.url === 'string' ? raw.url : typeof raw.content === 'string' ? raw.content.trim() : ''
1523
+ if (!/^https?:\/\//i.test(url)) return null
1524
+ return { kind: 'url', title: title, url: url, length: 0, excerpt: '' }
1525
+ }
1526
+ var content = typeof raw.content === 'string' ? raw.content.trim() : ''
1527
+ return {
1528
+ kind: raw.kind,
1529
+ title: title,
1530
+ length: typeof raw.length === 'number' ? raw.length : content.length,
1531
+ excerpt: clipString(typeof raw.excerpt === 'string' ? raw.excerpt : content, 600),
1532
+ }
1533
+ }
1534
+
1535
+ function normalizeAnnotationList(raw) {
1536
+ var list = []
1537
+ if (!Array.isArray(raw)) return list
1538
+ for (var index = 0; index < raw.length; index += 1) {
1539
+ var item = normalizeAnnotation(raw[index])
1540
+ if (item !== null) list.push(item)
1541
+ }
1542
+ list.sort(compareCreatedAt)
1543
+ return list
1544
+ }
1545
+
1546
+ function wireRecord(record) {
1547
+ var wire = {
1548
+ id: record.id,
1549
+ style: record.style,
1550
+ quote: record.quote,
1551
+ note: record.note,
1552
+ prefix: record.prefix,
1553
+ suffix: record.suffix,
1554
+ rootSelector: record.rootSelector,
1555
+ createdAt: record.createdAt,
1556
+ }
1557
+ if (typeof record.messageKey === 'string') {
1558
+ wire.messageKey = record.messageKey
1559
+ wire.messageStart = record.messageStart
1560
+ wire.messageEnd = record.messageEnd
1561
+ }
1562
+ if (typeof record.turn === 'number') wire.turn = record.turn
1563
+ if (record.style === 'move') {
1564
+ wire.targetPrefix = record.targetPrefix
1565
+ wire.targetSuffix = record.targetSuffix
1566
+ if (typeof record.targetOffset === 'number') wire.targetOffset = record.targetOffset
1567
+ if (typeof record.targetQuote === 'string' && record.targetQuote.length > 0) {
1568
+ wire.targetQuote = record.targetQuote
1569
+ if (typeof record.targetEnd === 'number') wire.targetEnd = record.targetEnd
1570
+ }
1571
+ }
1572
+ if (record.style === 'reference' && record.material) {
1573
+ wire.material = { kind: record.material.kind, title: record.material.title, content: record.material.content }
1574
+ }
1575
+ return wire
1576
+ }
1577
+
1578
+ function networkFailure(cause) {
1579
+ var failure = new Error(cause && cause.message ? cause.message : 'network error')
1580
+ failure.code = 'network'
1581
+ return failure
1582
+ }
1583
+
1584
+ function requestJson(url, options) {
1585
+ var pending = null
1586
+ try {
1587
+ if (typeof fetch !== 'function') return Promise.reject(networkFailure(new Error('fetch is unavailable')))
1588
+ pending = fetch(url, options)
1589
+ } catch (failure) {
1590
+ return Promise.reject(networkFailure(failure))
1591
+ }
1592
+ if (!pending || typeof pending.then !== 'function') {
1593
+ return Promise.reject(networkFailure(new Error('fetch returned no promise')))
1594
+ }
1595
+ return pending.then(
1596
+ function (response) {
1597
+ if (!response || typeof response.text !== 'function') throw networkFailure(new Error('empty response'))
1598
+ return response.text().then(
1599
+ function (text) {
1600
+ var data = null
1601
+ if (typeof text === 'string' && text.length > 0) {
1602
+ try {
1603
+ data = JSON.parse(text)
1604
+ } catch (error) {
1605
+ data = null
1606
+ }
1607
+ }
1608
+ if (response.ok === true && data && data.ok === true) return data
1609
+ var failure = new Error('HTTP ' + String(response.status))
1610
+ failure.code = 'http'
1611
+ if (data && data.error && typeof data.error.message === 'string') failure.message = data.error.message
1612
+ throw failure
1613
+ },
1614
+ function (failure) {
1615
+ throw networkFailure(failure)
1616
+ },
1617
+ )
1618
+ },
1619
+ function (failure) {
1620
+ throw networkFailure(failure)
1621
+ },
1622
+ )
1623
+ }
1624
+
1625
+ function normalizeLessons(raw) {
1626
+ var list = []
1627
+ if (!Array.isArray(raw)) return list
1628
+ for (var index = 0; index < raw.length; index += 1) {
1629
+ var item = raw[index]
1630
+ if (item && typeof item.text === 'string' && item.text.length > 0) {
1631
+ list.push({ text: clipString(item.text, 300), date: typeof item.date === 'string' ? item.date : '' })
1632
+ }
1633
+ }
1634
+ return list
1635
+ }
1636
+
1637
+ // The composer-side slot hands us its draft setter so the panel (root
1638
+ // scope, no composer access) can prefill the distill request.
1639
+ var draftSetter = null
1640
+
1641
+ function requestDistill(prompt) {
1642
+ if (typeof draftSetter !== 'function') return false
1643
+ try {
1644
+ draftSetter(prompt)
1645
+ return true
1646
+ } catch (error) {
1647
+ console.error('dsh-mindmark: cannot prefill the composer', error)
1648
+ return false
1649
+ }
1650
+ }
1651
+
1652
+ function forgetLesson(text) {
1653
+ var sessionId = state.sessionId
1654
+ if (sessionId === null || typeof text !== 'string') return
1655
+ var previous = state.lessons
1656
+ publishState({
1657
+ lessons: previous.filter(function (item) {
1658
+ return item.text !== text
1659
+ }),
1660
+ error: null,
1661
+ })
1662
+ enqueueMutation(function () {
1663
+ return postAction({ action: 'forget-lesson', sessionId: sessionId, lessons: [text] }).then(
1664
+ function (data) {
1665
+ if (state.sessionId !== sessionId) return
1666
+ applyServerPayload(data)
1667
+ },
1668
+ function (failure) {
1669
+ if (state.sessionId !== sessionId) return
1670
+ publishState({ lessons: previous, error: failureToError(failure, 'resolve') })
1671
+ },
1672
+ )
1673
+ })
1674
+ }
1675
+
1676
+ function applyServerPayload(data, extra) {
1677
+ var patch = extra || {}
1678
+ if (Array.isArray(data.annotations)) patch.annotations = normalizeAnnotationList(data.annotations)
1679
+ if (typeof data.mode === 'string') patch.mode = normalizeMode(data.mode)
1680
+ if (Array.isArray(data.lessons)) patch.lessons = normalizeLessons(data.lessons)
1681
+ if (patch.error === undefined) patch.error = null
1682
+ publishState(patch)
1683
+ }
1684
+
1685
+ function loadSession(sessionId) {
1686
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return
1687
+ loadToken += 1
1688
+ var token = loadToken
1689
+ publishState({ loading: true, error: null })
1690
+ requestJson(ROUTE + '?sessionId=' + encodeURIComponent(sessionId), {
1691
+ method: 'GET',
1692
+ headers: { accept: 'application/json' },
1693
+ }).then(
1694
+ function (data) {
1695
+ if (token !== loadToken || state.sessionId !== sessionId) return
1696
+ applyServerPayload(data, { loading: false })
1697
+ },
1698
+ function (failure) {
1699
+ if (token !== loadToken || state.sessionId !== sessionId) return
1700
+ publishState({ loading: false, error: failureToError(failure, 'load') })
1701
+ },
1702
+ )
1703
+ }
1704
+
1705
+ function setCurrentSession(rawSessionId) {
1706
+ var sessionId = typeof rawSessionId === 'string' && rawSessionId.length > 0 ? rawSessionId : null
1707
+ if (sessionId === state.sessionId) return
1708
+ loadToken += 1
1709
+ publishState({
1710
+ sessionId: sessionId,
1711
+ annotations: [],
1712
+ mode: 'brief',
1713
+ loading: sessionId !== null,
1714
+ error: null,
1715
+ panelOpen: sessionId === null ? false : state.panelOpen,
1716
+ pendingMove: null,
1717
+ referenceDraft: null,
1718
+ })
1719
+ if (sessionId !== null) loadSession(sessionId)
1720
+ }
1721
+
1722
+ function reload() {
1723
+ var sessionId = state.sessionId
1724
+ if (sessionId === null) return
1725
+ loadSession(sessionId)
1726
+ }
1727
+
1728
+ function postAction(body) {
1729
+ return requestJson(ROUTE, {
1730
+ method: 'POST',
1731
+ headers: { 'content-type': 'application/json' },
1732
+ body: JSON.stringify(body),
1733
+ })
1734
+ }
1735
+
1736
+ function addAnnotation(annotation, message) {
1737
+ var sessionId = state.sessionId
1738
+ if (sessionId === null) return
1739
+ var record = normalizeAnnotation(annotation)
1740
+ if (record === null) {
1741
+ publishState({ error: { code: 'invalid', message: '' } })
1742
+ return
1743
+ }
1744
+ loadToken += 1
1745
+ publishState({ annotations: state.annotations.concat([record]), loading: false, error: null })
1746
+ // The wire copy comes from the raw record: it still carries the material text.
1747
+ var body = { action: 'add', sessionId: sessionId, annotation: wireRecord(annotation) }
1748
+ if (message && typeof message.text === 'string') body.message = message
1749
+ enqueueMutation(function () {
1750
+ return postAction(body).then(
1751
+ function (data) {
1752
+ if (state.sessionId !== sessionId) return
1753
+ applyServerPayload(data)
1754
+ },
1755
+ function (failure) {
1756
+ if (state.sessionId !== sessionId) return
1757
+ publishState({
1758
+ annotations: state.annotations.filter(function (item) {
1759
+ return item.id !== record.id
1760
+ }),
1761
+ error: failureToError(failure, 'add'),
1762
+ })
1763
+ },
1764
+ )
1765
+ })
1766
+ }
1767
+
1768
+ function uniqueIds(ids) {
1769
+ var seen = {}
1770
+ var unique = []
1771
+ if (!Array.isArray(ids)) return unique
1772
+ for (var index = 0; index < ids.length; index += 1) {
1773
+ var id = ids[index]
1774
+ if (typeof id === 'string' && id.length > 0 && seen[id] !== true) {
1775
+ seen[id] = true
1776
+ unique.push(id)
1777
+ }
1778
+ }
1779
+ return unique
1780
+ }
1781
+
1782
+ function removeAnnotations(ids) {
1783
+ var sessionId = state.sessionId
1784
+ if (sessionId === null) return
1785
+ var unique = uniqueIds(ids)
1786
+ if (unique.length === 0) return
1787
+ var seen = {}
1788
+ unique.forEach(function (id) {
1789
+ seen[id] = true
1790
+ })
1791
+ var removed = state.annotations.filter(function (item) {
1792
+ return seen[item.id] === true
1793
+ })
1794
+ if (removed.length === 0) return
1795
+ loadToken += 1
1796
+ publishState({
1797
+ annotations: state.annotations.filter(function (item) {
1798
+ return seen[item.id] !== true
1799
+ }),
1800
+ loading: false,
1801
+ error: null,
1802
+ })
1803
+ enqueueMutation(function () {
1804
+ return postAction({ action: 'remove', sessionId: sessionId, ids: unique }).then(
1805
+ function (data) {
1806
+ if (state.sessionId !== sessionId) return
1807
+ applyServerPayload(data)
1808
+ },
1809
+ function (failure) {
1810
+ if (state.sessionId !== sessionId) return
1811
+ var present = {}
1812
+ state.annotations.forEach(function (item) {
1813
+ present[item.id] = true
1814
+ })
1815
+ var restored = state.annotations.concat(
1816
+ removed.filter(function (item) {
1817
+ return present[item.id] !== true
1818
+ }),
1819
+ )
1820
+ restored.sort(compareCreatedAt)
1821
+ publishState({ annotations: restored, error: failureToError(failure, 'remove') })
1822
+ },
1823
+ )
1824
+ })
1825
+ }
1826
+
1827
+ function clearAll() {
1828
+ var sessionId = state.sessionId
1829
+ if (sessionId === null) return
1830
+ var previous = state.annotations
1831
+ if (previous.length === 0) {
1832
+ publishState({ error: null })
1833
+ return
1834
+ }
1835
+ loadToken += 1
1836
+ publishState({ annotations: [], loading: false, error: null })
1837
+ enqueueMutation(function () {
1838
+ return postAction({ action: 'clear', sessionId: sessionId }).then(
1839
+ function (data) {
1840
+ if (state.sessionId !== sessionId) return
1841
+ applyServerPayload(data)
1842
+ },
1843
+ function (failure) {
1844
+ if (state.sessionId !== sessionId) return
1845
+ publishState({ annotations: previous, error: failureToError(failure, 'clear') })
1846
+ },
1847
+ )
1848
+ })
1849
+ }
1850
+
1851
+ function setStatus(ids, status) {
1852
+ var sessionId = state.sessionId
1853
+ if (sessionId === null) return
1854
+ var unique = uniqueIds(ids)
1855
+ var all = unique.length === 0
1856
+ var previous = state.annotations
1857
+ var changed = false
1858
+ var next = previous.map(function (item) {
1859
+ if (!all && unique.indexOf(item.id) < 0) return item
1860
+ if (item.status === status && status === 'resolved') return item
1861
+ if (item.status === status && status === 'pending' && item.injections === 0) return item
1862
+ changed = true
1863
+ var copy = {}
1864
+ for (var key in item) copy[key] = item[key]
1865
+ copy.status = status
1866
+ copy.resolvedBy = status === 'resolved' ? 'user' : ''
1867
+ if (status === 'pending') copy.injections = 0
1868
+ return copy
1869
+ })
1870
+ if (!changed) return
1871
+ loadToken += 1
1872
+ publishState({ annotations: next, loading: false, error: null })
1873
+ enqueueMutation(function () {
1874
+ return postAction({ action: status === 'resolved' ? 'resolve' : 'reopen', sessionId: sessionId, ids: unique }).then(
1875
+ function (data) {
1876
+ if (state.sessionId !== sessionId) return
1877
+ applyServerPayload(data)
1878
+ },
1879
+ function (failure) {
1880
+ if (state.sessionId !== sessionId) return
1881
+ publishState({ annotations: previous, error: failureToError(failure, 'resolve') })
1882
+ },
1883
+ )
1884
+ })
1885
+ }
1886
+
1887
+ function setMode(mode) {
1888
+ var sessionId = state.sessionId
1889
+ var next = normalizeMode(mode)
1890
+ if (sessionId === null || next === state.mode) return
1891
+ var previous = state.mode
1892
+ publishState({ mode: next, error: null })
1893
+ enqueueMutation(function () {
1894
+ return postAction({ action: 'set-mode', sessionId: sessionId, mode: next }).then(
1895
+ function (data) {
1896
+ if (state.sessionId !== sessionId) return
1897
+ applyServerPayload(data)
1898
+ },
1899
+ function (failure) {
1900
+ if (state.sessionId !== sessionId) return
1901
+ publishState({ mode: previous, error: failureToError(failure, 'mode') })
1902
+ },
1903
+ )
1904
+ })
1905
+ }
1906
+
1907
+ function copyOf(object, patch) {
1908
+ var next = {}
1909
+ for (var key in object) next[key] = object[key]
1910
+ for (var patchKey in patch) next[patchKey] = patch[patchKey]
1911
+ return next
1912
+ }
1913
+
1914
+ function startMove(built) {
1915
+ if (state.sessionId === null || !built || !built.record) return
1916
+ publishState({
1917
+ pendingMove: { built: built, target: null, reason: '', error: built.message === null ? 'moveUnanchored' : '' },
1918
+ })
1919
+ }
1920
+
1921
+ function setMoveTarget(target) {
1922
+ var pending = state.pendingMove
1923
+ if (!pending || !target || pending.error === 'moveUnanchored') return
1924
+ var record = pending.built.record
1925
+ var error = ''
1926
+ var replaces = typeof target.end === 'number' && target.end > target.offset
1927
+ if (pending.built.message && target.key !== pending.built.message.key) error = 'moveOtherMessage'
1928
+ else if (typeof record.messageStart === 'number') {
1929
+ if (replaces && target.offset < record.messageEnd && target.end > record.messageStart) error = 'moveOverlap'
1930
+ else if (!replaces && target.offset >= record.messageStart && target.offset <= record.messageEnd) error = 'moveSamePlace'
1931
+ }
1932
+ publishState({ pendingMove: copyOf(pending, { target: error === '' ? target : null, error: error }) })
1933
+ }
1934
+
1935
+ function setMoveReason(text) {
1936
+ var pending = state.pendingMove
1937
+ if (!pending) return
1938
+ publishState({ pendingMove: copyOf(pending, { reason: clipString(String(text || ''), MAX_NOTE) }) })
1939
+ }
1940
+
1941
+ function cancelMove() {
1942
+ if (state.pendingMove) publishState({ pendingMove: null })
1943
+ }
1944
+
1945
+ function placeMove() {
1946
+ var pending = state.pendingMove
1947
+ if (!pending) return false
1948
+ if (pending.error === 'moveUnanchored') return false
1949
+ if (!pending.target) {
1950
+ publishState({ pendingMove: copyOf(pending, { error: pending.error || 'moveNoTarget' }) })
1951
+ return false
1952
+ }
1953
+ var record = copyOf(pending.built.record, {
1954
+ id: createClientId(),
1955
+ style: 'move',
1956
+ note: String(pending.reason || '').trim(),
1957
+ targetPrefix: pending.target.prefix,
1958
+ targetSuffix: pending.target.suffix,
1959
+ targetOffset: pending.target.offset,
1960
+ createdAt: new Date().toISOString(),
1961
+ })
1962
+ if (pending.target.quote) {
1963
+ record.targetQuote = pending.target.quote
1964
+ record.targetEnd = pending.target.end
1965
+ }
1966
+ publishState({ pendingMove: null })
1967
+ addAnnotation(record, pending.built.message)
1968
+ return true
1969
+ }
1970
+
1971
+ function startReference(built) {
1972
+ if (state.sessionId === null || !built || !built.record) return
1973
+ publishState({
1974
+ referenceDraft: { built: built, kind: 'text', title: '', content: '', url: '', fileName: '', text: '', error: '' },
1975
+ })
1976
+ }
1977
+
1978
+ function patchReference(patch) {
1979
+ if (!state.referenceDraft) return
1980
+ publishState({ referenceDraft: copyOf(state.referenceDraft, patch) })
1981
+ }
1982
+
1983
+ function cancelReference() {
1984
+ if (state.referenceDraft) publishState({ referenceDraft: null })
1985
+ }
1986
+
1987
+ // Returns an error dictionary key, or '' once the reference is saved.
1988
+ function submitReference() {
1989
+ var draft = state.referenceDraft
1990
+ if (!draft) return ''
1991
+ if (!referenceReady(draft)) return draft.kind === 'url' ? 'refBadUrl' : ''
1992
+ var record = copyOf(draft.built.record, {
1993
+ style: 'reference',
1994
+ note: String(draft.text || '').trim().slice(0, MAX_NOTE),
1995
+ material: {
1996
+ kind: draft.kind,
1997
+ title: String(draft.title || '').trim(),
1998
+ content: draft.kind === 'url' ? String(draft.url || '').trim() : String(draft.content || ''),
1999
+ },
2000
+ })
2001
+ publishState({ referenceDraft: null })
2002
+ addAnnotation(record, draft.built.message)
2003
+ return ''
2004
+ }
2005
+
2006
+ function setPanelOpen(open) {
2007
+ var next = open === true
2008
+ if (state.panelOpen === next) return
2009
+ publishState({ panelOpen: next })
2010
+ if (next && state.sessionId !== null) reload()
2011
+ }
2012
+
2013
+ function togglePanel() {
2014
+ if (state.sessionId === null && state.panelOpen !== true) return
2015
+ setPanelOpen(state.panelOpen !== true)
2016
+ }
2017
+
2018
+ var controller = {
2019
+ getState: getState,
2020
+ subscribe: subscribeState,
2021
+ setCurrentSession: setCurrentSession,
2022
+ reload: reload,
2023
+ addAnnotation: addAnnotation,
2024
+ removeAnnotations: removeAnnotations,
2025
+ clearAll: clearAll,
2026
+ resolve: function (ids) {
2027
+ setStatus(ids, 'resolved')
2028
+ },
2029
+ reopen: function (ids) {
2030
+ setStatus(ids, 'pending')
2031
+ },
2032
+ setMode: setMode,
2033
+ startMove: startMove,
2034
+ startReference: startReference,
2035
+ patchReference: patchReference,
2036
+ cancelReference: cancelReference,
2037
+ submitReference: submitReference,
2038
+ setMoveTarget: setMoveTarget,
2039
+ setMoveReason: setMoveReason,
2040
+ cancelMove: cancelMove,
2041
+ placeMove: placeMove,
2042
+ forgetLesson: forgetLesson,
2043
+ requestDistill: requestDistill,
2044
+ togglePanel: togglePanel,
2045
+ setPanelOpen: setPanelOpen,
2046
+ }
2047
+
2048
+ function useControllerState() {
2049
+ return useSyncExternalStore(subscribeState, getState, getState)
2050
+ }
2051
+
2052
+ function pendingCount(current) {
2053
+ var count = 0
2054
+ for (var index = 0; index < current.annotations.length; index += 1) {
2055
+ if (current.annotations[index].status !== 'resolved') count += 1
2056
+ }
2057
+ return count
2058
+ }
2059
+
2060
+ // ------------------------------------------------------------- components
2061
+
2062
+ function keepSelection(event) {
2063
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
2064
+ }
2065
+
2066
+ function ToolButton(props) {
2067
+ return h(
2068
+ 'button',
2069
+ {
2070
+ type: 'button',
2071
+ className: 'dsa-tool-btn',
2072
+ title: props.title,
2073
+ 'aria-label': props.label,
2074
+ onPointerDown: keepSelection,
2075
+ onMouseDown: keepSelection,
2076
+ onClick: props.onClick,
2077
+ },
2078
+ props.glyph ? h('span', { className: 'dsa-tool-glyph dsa-tool-glyph-' + props.glyph, 'aria-hidden': 'true' }) : null,
2079
+ h('span', null, props.label),
2080
+ props.kbd ? h('span', { className: 'dsa-kbd', 'aria-hidden': 'true' }, props.kbd) : null,
2081
+ )
2082
+ }
2083
+
2084
+ // Wrap a material name in 《》 unless it already starts with a title mark.
2085
+ function bookTitle(title) {
2086
+ var text = String(title || '').trim() || '—'
2087
+ return /^[《「“"]/.test(text) ? text : '《' + text + '》'
2088
+ }
2089
+
2090
+ function referenceReady(draft) {
2091
+ if (!draft) return false
2092
+ if (draft.kind === 'url') return /^https?:\/\/\S+$/i.test(String(draft.url || '').trim())
2093
+ var length = String(draft.content || '').trim().length
2094
+ return length > 0 && length <= MAX_MATERIAL
2095
+ }
2096
+
2097
+ // The action bar the Chat view mounts next to a selection. `props` carry the
2098
+ // area-local surface actions (dismiss / readText / clearSelection) plus the
2099
+ // standard session seat (sessionId, inputActions).
2100
+ function SelectionActions(props) {
2101
+ var t = props.t
2102
+ var sessionId = typeof props.sessionId === 'string' ? props.sessionId : null
2103
+ var current = useControllerState()
2104
+ var noteState = useState(null)
2105
+ var draft = noteState[0]
2106
+ var setDraft = noteState[1]
2107
+ var inputRef = useRef(null)
2108
+
2109
+ useEffect(
2110
+ function () {
2111
+ if (sessionId !== null && current.sessionId !== sessionId) controller.setCurrentSession(sessionId)
2112
+ },
2113
+ [sessionId, current.sessionId],
2114
+ )
2115
+ var focusKey = draft === null ? '' : draft.style
2116
+ useEffect(
2117
+ function () {
2118
+ if (focusKey !== '' && inputRef.current && typeof inputRef.current.focus === 'function') {
2119
+ try {
2120
+ inputRef.current.focus()
2121
+ } catch (error) {
2122
+ /* focus is best effort */
2123
+ }
2124
+ }
2125
+ },
2126
+ [focusKey],
2127
+ )
2128
+
2129
+ function dismiss() {
2130
+ if (typeof props.dismiss === 'function') props.dismiss()
2131
+ }
2132
+
2133
+ function finish() {
2134
+ if (typeof props.clearSelection === 'function') props.clearSelection()
2135
+ dismiss()
2136
+ }
2137
+
2138
+ function mark(style) {
2139
+ var range = readLiveRange()
2140
+ if (range === null) {
2141
+ dismiss()
2142
+ return
2143
+ }
2144
+ var built = buildRecord(range, style)
2145
+ if (built === null) {
2146
+ dismiss()
2147
+ return
2148
+ }
2149
+ if (style === 'move') {
2150
+ controller.startMove(built)
2151
+ paintNow()
2152
+ finish()
2153
+ return
2154
+ }
2155
+ if (style === 'reference') {
2156
+ controller.startReference(built)
2157
+ paintNow()
2158
+ finish()
2159
+ return
2160
+ }
2161
+ if (NOTE_STYLES[style] === true) {
2162
+ setDraft({ style: style, built: built, text: '' })
2163
+ return
2164
+ }
2165
+ controller.addAnnotation(built.record, built.message)
2166
+ paintNow()
2167
+ finish()
2168
+ }
2169
+
2170
+ function unmark() {
2171
+ var range = readLiveRange()
2172
+ if (range === null) {
2173
+ dismiss()
2174
+ return
2175
+ }
2176
+ var hits = annotationsIntersecting(range)
2177
+ if (hits.length > 0) {
2178
+ controller.removeAnnotations(hits)
2179
+ paintNow()
2180
+ }
2181
+ finish()
2182
+ }
2183
+
2184
+ function quote() {
2185
+ var text = typeof props.readText === 'function' ? props.readText() : null
2186
+ if (text === null) {
2187
+ dismiss()
2188
+ return
2189
+ }
2190
+ var actions = props.inputActions
2191
+ if (actions && typeof actions.insertQuote === 'function' && actions.insertQuote(text) === false) return
2192
+ finish()
2193
+ }
2194
+
2195
+ function submitDraft() {
2196
+ if (draft === null) return
2197
+ var text = String(draft.text || '').trim()
2198
+ if (text.length === 0 || text.length > MAX_NOTE) return
2199
+ draft.built.record.note = text
2200
+ controller.addAnnotation(draft.built.record, draft.built.message)
2201
+ setDraft(null)
2202
+ paintNow()
2203
+ finish()
2204
+ }
2205
+
2206
+ if (draft !== null) {
2207
+ var isRewrite = draft.style === 'rewrite'
2208
+ return h(
2209
+ 'div',
2210
+ { className: 'dsa-toolbar is-note', role: 'dialog', 'aria-label': t(draft.style), 'data-dsh-mindmark-ui': '1' },
2211
+ h(
2212
+ 'div',
2213
+ { className: 'dsa-note-head' },
2214
+ h('span', { className: 'dsa-tool-glyph dsa-tool-glyph-' + draft.style, 'aria-hidden': 'true' }),
2215
+ h('span', null, t(draft.style)),
2216
+ ),
2217
+ h('p', { className: 'dsa-note-quote' }, previewQuote(draft.built.record.quote, 160)),
2218
+ h('textarea', {
2219
+ ref: inputRef,
2220
+ className: 'dsa-note-input',
2221
+ placeholder: t(isRewrite ? 'rewritePlaceholder' : 'commentPlaceholder'),
2222
+ value: draft.text,
2223
+ maxLength: MAX_NOTE,
2224
+ rows: 3,
2225
+ onChange: function (event) {
2226
+ setDraft({ style: draft.style, built: draft.built, text: event.target.value })
2227
+ },
2228
+ onKeyDown: function (event) {
2229
+ if (event.key === 'Escape') {
2230
+ event.stopPropagation()
2231
+ setDraft(null)
2232
+ dismiss()
2233
+ } else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
2234
+ event.preventDefault()
2235
+ submitDraft()
2236
+ }
2237
+ },
2238
+ }),
2239
+ h(
2240
+ 'div',
2241
+ { className: 'dsa-note-actions' },
2242
+ h(
2243
+ 'button',
2244
+ {
2245
+ type: 'button',
2246
+ className: 'dsa-btn',
2247
+ onClick: function () {
2248
+ setDraft(null)
2249
+ dismiss()
2250
+ },
2251
+ },
2252
+ t('cancel'),
2253
+ ),
2254
+ h(
2255
+ 'button',
2256
+ { type: 'button', className: 'dsa-btn is-primary', disabled: String(draft.text || '').trim().length === 0, onClick: submitDraft },
2257
+ t('confirm'),
2258
+ ),
2259
+ ),
2260
+ )
2261
+ }
2262
+
2263
+ // While a passage waits to be dropped, a selection in the answer is the
2264
+ // text it would replace: offer exactly that.
2265
+ if (current.pendingMove !== null) {
2266
+ var pendingTarget = current.pendingMove.target
2267
+ var canReplace = pendingTarget !== null && Boolean(pendingTarget.quote) && !current.pendingMove.error
2268
+ return h(
2269
+ 'div',
2270
+ { className: 'dsa-toolbar', role: 'toolbar', 'aria-label': t('move'), 'data-dsh-mindmark-ui': '1' },
2271
+ canReplace
2272
+ ? h(ToolButton, {
2273
+ label: t('movePlaceReplace'),
2274
+ title: t('moveReplaceReady', { quote: previewQuote(pendingTarget.quote, 30) }),
2275
+ glyph: 'move',
2276
+ kbd: 'Alt+V',
2277
+ onClick: function () {
2278
+ if (controller.placeMove()) paintNow()
2279
+ finish()
2280
+ },
2281
+ })
2282
+ : h('span', { className: 'dsa-move-state is-error', style: { padding: '0 8px' } }, t(current.pendingMove.error || 'moveHowTo')),
2283
+ h(
2284
+ 'button',
2285
+ {
2286
+ type: 'button',
2287
+ className: 'dsa-tool-close',
2288
+ title: t('cancel'),
2289
+ 'aria-label': t('cancel'),
2290
+ onPointerDown: keepSelection,
2291
+ onMouseDown: keepSelection,
2292
+ onClick: function () {
2293
+ controller.cancelMove()
2294
+ paintNow()
2295
+ finish()
2296
+ },
2297
+ },
2298
+ '×',
2299
+ ),
2300
+ )
2301
+ }
2302
+
2303
+ var hasQuote = props.inputActions && typeof props.inputActions.insertQuote === 'function'
2304
+ function styleButton(style) {
2305
+ return h(ToolButton, {
2306
+ key: style,
2307
+ label: t(style),
2308
+ title: t('hint.' + style),
2309
+ glyph: style,
2310
+ kbd: style === 'move' ? 'Alt+C' : null,
2311
+ onClick: function () {
2312
+ mark(style)
2313
+ },
2314
+ })
2315
+ }
2316
+ return h(
2317
+ 'div',
2318
+ { className: 'dsa-toolbar is-rows', role: 'toolbar', 'aria-label': t('toolbarLabel'), 'data-dsh-mindmark-ui': '1' },
2319
+ h(
2320
+ 'div',
2321
+ { className: 'dsa-tool-row' },
2322
+ hasQuote ? h(ToolButton, { label: t('quote'), title: t('hint.quote'), glyph: 'quote', onClick: quote }) : null,
2323
+ hasQuote ? h('span', { className: 'dsa-tool-divider', 'aria-hidden': 'true' }) : null,
2324
+ QUICK_STYLES.map(styleButton),
2325
+ h('span', { className: 'dsa-tool-divider', 'aria-hidden': 'true' }),
2326
+ h(ToolButton, { label: t('unmark'), title: t('unmark'), onClick: unmark }),
2327
+ h('span', { className: 'dsa-spacer', 'aria-hidden': 'true' }),
2328
+ h(
2329
+ 'button',
2330
+ {
2331
+ type: 'button',
2332
+ className: 'dsa-tool-close',
2333
+ title: t('close'),
2334
+ 'aria-label': t('close'),
2335
+ onPointerDown: keepSelection,
2336
+ onMouseDown: keepSelection,
2337
+ onClick: dismiss,
2338
+ },
2339
+ '×',
2340
+ ),
2341
+ ),
2342
+ h('div', { className: 'dsa-tool-row' }, INPUT_STYLES.map(styleButton)),
2343
+ )
2344
+ }
2345
+
2346
+ function ModeSwitch(props) {
2347
+ var t = props.t
2348
+ var sessionId = typeof props.sessionId === 'string' && props.sessionId.length > 0 ? props.sessionId : null
2349
+ var current = useControllerState()
2350
+ useEffect(
2351
+ function () {
2352
+ if (sessionId !== null && current.sessionId !== sessionId) controller.setCurrentSession(sessionId)
2353
+ },
2354
+ [sessionId, current.sessionId],
2355
+ )
2356
+ var inputActions = props.inputActions
2357
+ useEffect(
2358
+ function () {
2359
+ if (inputActions && typeof inputActions.setDraft === 'function') {
2360
+ draftSetter = function (text) {
2361
+ inputActions.setDraft(text)
2362
+ }
2363
+ return function () {
2364
+ draftSetter = null
2365
+ }
2366
+ }
2367
+ return undefined
2368
+ },
2369
+ [inputActions],
2370
+ )
2371
+ var isCurrent = sessionId !== null && current.sessionId === sessionId
2372
+ var pending = isCurrent ? pendingCount(current) : 0
2373
+ var mode = isCurrent ? current.mode : 'brief'
2374
+ var locked = props.locked === true
2375
+ return h(
2376
+ 'div',
2377
+ { className: 'dsa-mode', 'data-dsh-mindmark-ui': '1', title: t('modeTitle'), role: 'group', 'aria-label': t('modeLabel') },
2378
+ h('span', { className: 'dsa-mode-label' }, h(MarkerIcon, { size: 13 }), h('span', null, t('modeLabel'))),
2379
+ h(
2380
+ 'span',
2381
+ { className: 'dsa-mode-seg' },
2382
+ MODES.map(function (option) {
2383
+ return h(
2384
+ 'button',
2385
+ {
2386
+ key: option,
2387
+ type: 'button',
2388
+ className: 'dsa-mode-btn' + (mode === option ? ' is-on' : ''),
2389
+ title: t(option === 'full' ? 'modeFullHint' : 'modeBriefHint'),
2390
+ 'aria-pressed': mode === option ? 'true' : 'false',
2391
+ disabled: locked || !isCurrent,
2392
+ onClick: function () {
2393
+ controller.setMode(option)
2394
+ },
2395
+ },
2396
+ t(option === 'full' ? 'modeFull' : 'modeBrief'),
2397
+ )
2398
+ }),
2399
+ ),
2400
+ pending > 0 ? h('span', { className: 'dsa-mode-badge', title: t('pendingCount', { count: pending }) }, String(pending)) : null,
2401
+ )
2402
+ }
2403
+
2404
+ function AnnotationItem(props) {
2405
+ var t = props.t
2406
+ var annotation = props.annotation
2407
+ var resolved = annotation.status === 'resolved'
2408
+ var time = formatTimestamp(annotation.createdAt)
2409
+ var by = annotation.resolvedBy === 'model' ? t('byModel') : annotation.resolvedBy === 'cap' ? t('byCap') : annotation.resolvedBy === 'user' ? t('byUser') : ''
2410
+ var note = null
2411
+ if (annotation.note) {
2412
+ var noteLabel = { rewrite: 'rewriteLabel', move: 'reasonLabel', reference: 'requirementLabel' }[annotation.style] || 'noteLabel'
2413
+ note = h('p', { className: 'dsa-note' }, h('b', null, t(noteLabel)), annotation.note)
2414
+ }
2415
+ var detail = null
2416
+ if (annotation.style === 'move') {
2417
+ detail = h(
2418
+ 'p',
2419
+ { className: 'dsa-note' },
2420
+ h('b', null, t(annotation.targetQuote ? 'moveReplaceLabel' : 'moveTargetLabel')),
2421
+ annotation.targetQuote
2422
+ ? '「' + previewQuote(annotation.targetQuote, 60) + '」'
2423
+ : '…' + previewQuote(annotation.targetPrefix, 400).slice(-18) + ' ▮ ' + previewQuote(annotation.targetSuffix, 18).replace(/…$/, '') + '…',
2424
+ )
2425
+ } else if (annotation.style === 'reference' && annotation.material) {
2426
+ var material = annotation.material
2427
+ detail = h(
2428
+ 'p',
2429
+ { className: 'dsa-note' },
2430
+ h('b', null, t('materialLabel')),
2431
+ material.kind === 'url'
2432
+ ? material.url
2433
+ : bookTitle(material.title) + ' ' + t('chars', { count: material.length }),
2434
+ )
2435
+ }
2436
+ return h(
2437
+ 'div',
2438
+ { className: 'dsa-item' + (resolved ? ' is-resolved' : '') },
2439
+ h('span', { className: 'dsa-chip dsa-chip-' + annotation.style }, t(annotation.style)),
2440
+ h(
2441
+ 'div',
2442
+ { className: 'dsa-item-main' },
2443
+ h('p', { className: 'dsa-quote' }, previewQuote(annotation.quote)),
2444
+ detail,
2445
+ note,
2446
+ h(
2447
+ 'p',
2448
+ { className: 'dsa-meta' },
2449
+ h('span', { className: 'dsa-status' + (resolved ? '' : ' is-pending') }, resolved ? t('statusResolved') : t('statusPending')),
2450
+ resolved && by ? h('span', null, by) : null,
2451
+ time === '' ? null : h('span', null, time),
2452
+ ),
2453
+ ),
2454
+ h(
2455
+ 'div',
2456
+ { className: 'dsa-item-actions' },
2457
+ h(
2458
+ 'button',
2459
+ {
2460
+ type: 'button',
2461
+ className: 'dsa-item-btn',
2462
+ title: resolved ? t('reopen') : t('resolve'),
2463
+ 'aria-label': resolved ? t('reopen') : t('resolve'),
2464
+ onClick: function () {
2465
+ if (resolved) controller.reopen([annotation.id])
2466
+ else controller.resolve([annotation.id])
2467
+ paintNow()
2468
+ },
2469
+ },
2470
+ resolved ? '↺' : '✓',
2471
+ ),
2472
+ h(
2473
+ 'button',
2474
+ {
2475
+ type: 'button',
2476
+ className: 'dsa-item-btn is-del',
2477
+ title: t('delete'),
2478
+ 'aria-label': t('delete'),
2479
+ onClick: function () {
2480
+ controller.removeAnnotations([annotation.id])
2481
+ paintNow()
2482
+ },
2483
+ },
2484
+ '×',
2485
+ ),
2486
+ ),
2487
+ )
2488
+ }
2489
+
2490
+ function AnnotationPanel(props) {
2491
+ var t = props.t
2492
+ var current = props.state
2493
+ var canHighlight = props.canHighlight
2494
+ var annotations = Array.isArray(current.annotations) ? current.annotations : []
2495
+ var lessons = Array.isArray(current.lessons) ? current.lessons : []
2496
+ var pending = pendingCount(current)
2497
+ var loading = current.loading === true
2498
+ var items = annotations
2499
+ .slice()
2500
+ .reverse()
2501
+ .map(function (annotation) {
2502
+ return h(AnnotationItem, { key: annotation.id, t: t, annotation: annotation })
2503
+ })
2504
+ var body =
2505
+ loading && annotations.length === 0
2506
+ ? h('p', { className: 'dsa-loading' }, t('loading'))
2507
+ : annotations.length === 0
2508
+ ? h('p', { className: 'dsa-empty' }, t('empty'))
2509
+ : items
2510
+ return h(
2511
+ 'div',
2512
+ { className: 'dsa-panel', role: 'dialog', 'aria-label': t('panelTitle'), 'aria-labelledby': PANEL_TITLE_ID },
2513
+ h(
2514
+ 'div',
2515
+ { className: 'dsa-panel-head' },
2516
+ h('span', { className: 'dsa-panel-title', id: PANEL_TITLE_ID }, t('panelTitle')),
2517
+ annotations.length > 0 ? h('span', { className: 'dsa-panel-count' }, t('pendingCount', { count: pending })) : null,
2518
+ h('span', { className: 'dsa-spacer', 'aria-hidden': 'true' }),
2519
+ h(
2520
+ 'button',
2521
+ {
2522
+ type: 'button',
2523
+ className: 'dsa-panel-close',
2524
+ title: t('close'),
2525
+ 'aria-label': t('close'),
2526
+ onClick: function () {
2527
+ controller.setPanelOpen(false)
2528
+ },
2529
+ },
2530
+ '×',
2531
+ ),
2532
+ ),
2533
+ canHighlight ? null : h('p', { className: 'dsa-warning', role: 'status' }, t('warning')),
2534
+ current.error ? h('p', { className: 'dsa-error', role: 'alert' }, errorText(t, current.error)) : null,
2535
+ h('div', { className: 'dsa-panel-body' }, body),
2536
+ h(
2537
+ 'div',
2538
+ { className: 'dsa-lessons' },
2539
+ h('p', { className: 'dsa-lessons-title' }, t('lessonsTitle') + (lessons.length > 0 ? ' · ' + lessons.length : '')),
2540
+ lessons.length === 0
2541
+ ? h('p', { className: 'dsa-lessons-empty' }, t('lessonsEmpty'))
2542
+ : lessons.map(function (lesson, index) {
2543
+ return h(
2544
+ 'div',
2545
+ { className: 'dsa-lesson', key: lesson.text + index },
2546
+ h('span', null, lesson.text),
2547
+ lesson.date ? h('small', null, lesson.date) : null,
2548
+ h(
2549
+ 'button',
2550
+ {
2551
+ type: 'button',
2552
+ className: 'dsa-item-btn is-del',
2553
+ title: t('forget'),
2554
+ 'aria-label': t('forget'),
2555
+ onClick: function () {
2556
+ controller.forgetLesson(lesson.text)
2557
+ },
2558
+ },
2559
+ '×',
2560
+ ),
2561
+ )
2562
+ }),
2563
+ ),
2564
+ h(
2565
+ 'div',
2566
+ { className: 'dsa-panel-foot' },
2567
+ h('p', { className: 'dsa-hint' }, t('footerHint')),
2568
+ h(
2569
+ 'button',
2570
+ {
2571
+ type: 'button',
2572
+ className: 'dsa-btn is-primary',
2573
+ title: t('distillHint'),
2574
+ disabled: annotations.length === 0,
2575
+ onClick: function () {
2576
+ if (controller.requestDistill(t('distillPrompt'))) controller.setPanelOpen(false)
2577
+ },
2578
+ },
2579
+ t('distill'),
2580
+ ),
2581
+ h(
2582
+ 'button',
2583
+ {
2584
+ type: 'button',
2585
+ className: 'dsa-btn',
2586
+ disabled: pending === 0,
2587
+ onClick: function () {
2588
+ controller.resolve([])
2589
+ paintNow()
2590
+ },
2591
+ },
2592
+ t('resolveAll'),
2593
+ ),
2594
+ h(
2595
+ 'button',
2596
+ {
2597
+ type: 'button',
2598
+ className: 'dsa-btn',
2599
+ disabled: annotations.length === 0,
2600
+ onClick: function () {
2601
+ controller.clearAll()
2602
+ paintNow()
2603
+ },
2604
+ },
2605
+ t('clearAll'),
2606
+ ),
2607
+ ),
2608
+ )
2609
+ }
2610
+
2611
+ function MoveBanner(props) {
2612
+ var t = props.t
2613
+ var pending = props.pending
2614
+ var target = pending.target
2615
+ var status
2616
+ if (pending.error) status = h('span', { className: 'dsa-move-state is-error' }, t(pending.error))
2617
+ else if (target && target.quote) {
2618
+ status = h('span', { className: 'dsa-move-state is-ready' }, t('moveReplaceReady', { quote: previewQuote(target.quote, 30) }))
2619
+ } else if (target) {
2620
+ status = h(
2621
+ 'span',
2622
+ { className: 'dsa-move-state is-ready' },
2623
+ t('moveReady', {
2624
+ before: previewQuote(target.prefix, 400).slice(-12),
2625
+ after: previewQuote(target.suffix, 12).replace(/…$/, ''),
2626
+ }),
2627
+ )
2628
+ } else status = h('span', { className: 'dsa-move-state' }, t('moveHowTo'))
2629
+ return h(
2630
+ 'div',
2631
+ { className: 'dsa-move-banner', role: 'status', 'aria-live': 'polite' },
2632
+ h(
2633
+ 'div',
2634
+ { className: 'dsa-move-text' },
2635
+ h('span', { className: 'dsa-move-title' }, t('moveBanner', { quote: previewQuote(pending.built.record.quote, 24) })),
2636
+ status,
2637
+ ),
2638
+ h('input', {
2639
+ className: 'dsa-move-reason',
2640
+ type: 'text',
2641
+ maxLength: MAX_NOTE,
2642
+ placeholder: t('moveReasonPlaceholder'),
2643
+ value: pending.reason,
2644
+ onChange: function (event) {
2645
+ controller.setMoveReason(event.target.value)
2646
+ },
2647
+ onKeyDown: function (event) {
2648
+ if (event.key === 'Enter') {
2649
+ event.preventDefault()
2650
+ if (controller.placeMove()) paintNow()
2651
+ }
2652
+ },
2653
+ }),
2654
+ h(
2655
+ 'button',
2656
+ {
2657
+ type: 'button',
2658
+ className: 'dsa-btn is-primary',
2659
+ disabled: !target || pending.error === 'moveUnanchored',
2660
+ onMouseDown: keepSelection,
2661
+ onClick: function () {
2662
+ if (controller.placeMove()) paintNow()
2663
+ },
2664
+ },
2665
+ t('movePlace'),
2666
+ ),
2667
+ h(
2668
+ 'button',
2669
+ {
2670
+ type: 'button',
2671
+ className: 'dsa-btn',
2672
+ onMouseDown: keepSelection,
2673
+ onClick: function () {
2674
+ controller.cancelMove()
2675
+ paintNow()
2676
+ },
2677
+ },
2678
+ t('cancel'),
2679
+ ),
2680
+ )
2681
+ }
2682
+
2683
+ // The reference form, rendered in the overlay so a native file dialog
2684
+ // (which blurs the window) cannot dismiss it.
2685
+ function ReferenceDialog(props) {
2686
+ var t = props.t
2687
+ var draft = props.draft
2688
+ var inputRef = useRef(null)
2689
+ var fileRef = useRef(null)
2690
+ var length = String(draft.content || '').trim().length
2691
+
2692
+ useEffect(
2693
+ function () {
2694
+ if (inputRef.current && typeof inputRef.current.focus === 'function') {
2695
+ try {
2696
+ inputRef.current.focus()
2697
+ } catch (error) {
2698
+ /* focus is best effort */
2699
+ }
2700
+ }
2701
+ },
2702
+ [draft.kind],
2703
+ )
2704
+
2705
+ function patch(next) {
2706
+ controller.patchReference(next)
2707
+ }
2708
+
2709
+ function submit() {
2710
+ var problem = controller.submitReference()
2711
+ if (problem) patch({ error: t(problem) })
2712
+ else paintNow()
2713
+ }
2714
+
2715
+ function cancel() {
2716
+ controller.cancelReference()
2717
+ paintNow()
2718
+ }
2719
+
2720
+ function keys(event) {
2721
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
2722
+ event.preventDefault()
2723
+ submit()
2724
+ }
2725
+ }
2726
+
2727
+ function chooseFile() {
2728
+ var input = fileRef.current
2729
+ if (!input) return
2730
+ try {
2731
+ input.value = ''
2732
+ input.click()
2733
+ } catch (error) {
2734
+ patch({ error: t('refFileError') })
2735
+ }
2736
+ }
2737
+
2738
+ function readFile(event) {
2739
+ var input = event && event.target
2740
+ var file = input && input.files && input.files[0]
2741
+ if (!file) return
2742
+ if (typeof file.size === 'number' && file.size > MAX_MATERIAL_FILE_BYTES) {
2743
+ patch({ error: t('refTooLong', { max: MAX_MATERIAL }), content: '', fileName: '' })
2744
+ return
2745
+ }
2746
+ try {
2747
+ var reader = new FileReader()
2748
+ reader.onload = function () {
2749
+ var text = typeof reader.result === 'string' ? reader.result : ''
2750
+ var current = controller.getState().referenceDraft
2751
+ if (!current) return
2752
+ if (text.indexOf('\u0000') >= 0 || text.trim().length === 0) {
2753
+ patch({ error: t('refFileError'), content: '', fileName: '' })
2754
+ } else if (text.length > MAX_MATERIAL) {
2755
+ patch({ error: t('refTooLong', { max: MAX_MATERIAL }), content: '', fileName: '' })
2756
+ } else {
2757
+ patch({ content: text, fileName: file.name, title: current.title || file.name, error: '' })
2758
+ }
2759
+ }
2760
+ reader.onerror = function () {
2761
+ patch({ error: t('refFileError') })
2762
+ }
2763
+ reader.readAsText(file)
2764
+ } catch (error) {
2765
+ patch({ error: t('refFileError') })
2766
+ }
2767
+ }
2768
+
2769
+ var source
2770
+ if (draft.kind === 'url') {
2771
+ source = h('input', {
2772
+ ref: inputRef,
2773
+ className: 'dsa-ref-line',
2774
+ type: 'url',
2775
+ placeholder: t('refUrlPlaceholder'),
2776
+ value: draft.url,
2777
+ onChange: function (event) {
2778
+ patch({ url: event.target.value, error: '' })
2779
+ },
2780
+ onKeyDown: keys,
2781
+ })
2782
+ } else if (draft.kind === 'file') {
2783
+ source = h(
2784
+ 'div',
2785
+ { className: 'dsa-ref-file' },
2786
+ h('button', { ref: inputRef, type: 'button', className: 'dsa-btn', onClick: chooseFile }, t('refFileChoose')),
2787
+ h('input', { ref: fileRef, type: 'file', accept: MATERIAL_FILE_ACCEPT, tabIndex: -1, onChange: readFile }),
2788
+ h('span', { title: draft.fileName }, draft.fileName ? draft.fileName + ' · ' + t('chars', { count: length }) : t('refFileNone')),
2789
+ )
2790
+ } else {
2791
+ source = h('textarea', {
2792
+ ref: inputRef,
2793
+ className: 'dsa-note-input',
2794
+ placeholder: t('refTextPlaceholder'),
2795
+ value: draft.content,
2796
+ rows: 5,
2797
+ onChange: function (event) {
2798
+ patch({ content: event.target.value, error: '' })
2799
+ },
2800
+ onKeyDown: keys,
2801
+ })
2802
+ }
2803
+
2804
+ return h(
2805
+ 'div',
2806
+ { className: 'dsa-toolbar is-note is-ref dsa-ref-dialog', role: 'dialog', 'aria-label': t('reference') },
2807
+ h(
2808
+ 'div',
2809
+ { className: 'dsa-note-head' },
2810
+ h('span', { className: 'dsa-tool-glyph dsa-tool-glyph-reference', 'aria-hidden': 'true' }),
2811
+ h('span', null, t('reference')),
2812
+ ),
2813
+ h('p', { className: 'dsa-note-quote' }, previewQuote(draft.built.record.quote, 160)),
2814
+ h(
2815
+ 'div',
2816
+ { className: 'dsa-ref-tabs', role: 'tablist' },
2817
+ MATERIAL_KINDS.map(function (kind) {
2818
+ var label = kind === 'url' ? 'refTabUrl' : kind === 'file' ? 'refTabFile' : 'refTabText'
2819
+ return h(
2820
+ 'button',
2821
+ {
2822
+ key: kind,
2823
+ type: 'button',
2824
+ role: 'tab',
2825
+ 'aria-selected': draft.kind === kind ? 'true' : 'false',
2826
+ className: 'dsa-ref-tab' + (draft.kind === kind ? ' is-on' : ''),
2827
+ onClick: function () {
2828
+ patch({ kind: kind, error: '' })
2829
+ },
2830
+ },
2831
+ t(label),
2832
+ )
2833
+ }),
2834
+ ),
2835
+ draft.kind === 'url'
2836
+ ? null
2837
+ : h('input', {
2838
+ className: 'dsa-ref-line',
2839
+ type: 'text',
2840
+ maxLength: 120,
2841
+ placeholder: t('refTitlePlaceholder'),
2842
+ value: draft.title,
2843
+ onChange: function (event) {
2844
+ patch({ title: event.target.value })
2845
+ },
2846
+ onKeyDown: keys,
2847
+ }),
2848
+ source,
2849
+ draft.kind === 'text'
2850
+ ? h('div', { className: 'dsa-ref-meta' }, h('span', null, ''), h('span', null, t('chars', { count: length })))
2851
+ : draft.kind === 'file'
2852
+ ? h('div', { className: 'dsa-ref-meta' }, h('span', null, t('refFileHint')))
2853
+ : null,
2854
+ h('textarea', {
2855
+ className: 'dsa-note-input is-small',
2856
+ placeholder: t('refNotePlaceholder'),
2857
+ value: draft.text,
2858
+ maxLength: MAX_NOTE,
2859
+ rows: 2,
2860
+ onChange: function (event) {
2861
+ patch({ text: event.target.value })
2862
+ },
2863
+ onKeyDown: keys,
2864
+ }),
2865
+ draft.error ? h('p', { className: 'dsa-ref-error', role: 'alert' }, draft.error) : null,
2866
+ h(
2867
+ 'div',
2868
+ { className: 'dsa-note-actions' },
2869
+ h('button', { type: 'button', className: 'dsa-btn', onClick: cancel }, t('cancel')),
2870
+ h('button', { type: 'button', className: 'dsa-btn is-primary', disabled: !referenceReady(draft), onClick: submit }, t('confirm')),
2871
+ ),
2872
+ )
2873
+ }
2874
+
2875
+ function AnnotationOverlay(props) {
2876
+ var t = props.t
2877
+ var current = useControllerState()
2878
+ var moving = current.pendingMove !== null && current.sessionId !== null
2879
+ var referencing = current.referenceDraft !== null && current.sessionId !== null
2880
+ if (!current.panelOpen && !moving && !referencing) return null
2881
+ return h(
2882
+ 'div',
2883
+ { className: 'dsa-layer', 'data-dsh-mindmark-ui': '1' },
2884
+ current.panelOpen ? h(AnnotationPanel, { t: t, state: current, canHighlight: supportsHighlights() }) : null,
2885
+ moving && !referencing ? h(MoveBanner, { t: t, pending: current.pendingMove }) : null,
2886
+ referencing ? h(ReferenceDialog, { t: t, draft: current.referenceDraft }) : null,
2887
+ )
2888
+ }
2889
+
2890
+ function AnnotationHeader(props) {
2891
+ var t = props.t
2892
+ var sessionId = typeof props.sessionId === 'string' && props.sessionId.length > 0 ? props.sessionId : null
2893
+ var current = useControllerState()
2894
+ useEffect(
2895
+ function () {
2896
+ controller.setCurrentSession(sessionId)
2897
+ return function () {
2898
+ controller.setCurrentSession(null)
2899
+ }
2900
+ },
2901
+ [sessionId],
2902
+ )
2903
+ var isCurrent = sessionId !== null && current.sessionId === sessionId
2904
+ var count = isCurrent ? pendingCount(current) : 0
2905
+ var panelOpen = isCurrent && current.panelOpen === true
2906
+ var title = count > 0 ? t('headerTitle', { count: count }) : t('headerLabel')
2907
+ return h(
2908
+ 'button',
2909
+ {
2910
+ type: 'button',
2911
+ 'data-dsh-mindmark-ui': '1',
2912
+ className: 'dsa-header-btn' + (panelOpen ? ' is-active' : ''),
2913
+ title: title,
2914
+ 'aria-label': title,
2915
+ 'aria-expanded': panelOpen ? 'true' : 'false',
2916
+ onClick: function () {
2917
+ controller.togglePanel()
2918
+ },
2919
+ },
2920
+ h(MarkerIcon, { size: 16 }),
2921
+ count > 0 ? h('span', { className: 'dsa-header-badge', 'aria-hidden': 'true' }, String(count)) : null,
2922
+ )
2923
+ }
2924
+
2925
+ // ---------------------------------------------------------------- runtime
2926
+
2927
+ function addListener(target, type, handler, capture) {
2928
+ var useCapture = capture === true
2929
+ try {
2930
+ target.addEventListener(type, handler, useCapture)
2931
+ } catch (error) {
2932
+ console.error('dsh-mindmark: cannot listen for ' + type, error)
2933
+ }
2934
+ return function () {
2935
+ try {
2936
+ target.removeEventListener(type, handler, useCapture)
2937
+ } catch (error) {
2938
+ console.error('dsh-mindmark: cannot stop listening for ' + type, error)
2939
+ }
2940
+ }
2941
+ }
2942
+
2943
+ function observeMutations(target, handler) {
2944
+ try {
2945
+ if (typeof MutationObserver !== 'function' || !target || typeof target.nodeType !== 'number') return function () {}
2946
+ var observer = new MutationObserver(handler)
2947
+ observer.observe(target, { childList: true, subtree: true, characterData: true })
2948
+ return function () {
2949
+ try {
2950
+ observer.disconnect()
2951
+ } catch (error) {
2952
+ console.error('dsh-mindmark: cannot disconnect the mutation observer', error)
2953
+ }
2954
+ }
2955
+ } catch (error) {
2956
+ console.error('dsh-mindmark: cannot observe the DOM', error)
2957
+ return function () {}
2958
+ }
2959
+ }
2960
+
2961
+ // Re-anchoring plumbing only: the Chat view owns selection gestures now.
2962
+ function installRuntime() {
2963
+ var disposers = []
2964
+ var disposed = false
2965
+ var watchedSessionId = getState().sessionId
2966
+ var watchedAnnotations = getState().annotations
2967
+ var watchedMove = getState().pendingMove
2968
+ var watchedRef = getState().referenceDraft
2969
+
2970
+ function onScrollOrResize() {
2971
+ if (disposed) return
2972
+ hideCaretsWhileScrolling()
2973
+ schedulePaint(MUTATION_DEBOUNCE)
2974
+ }
2975
+
2976
+ function isEditableTarget(target) {
2977
+ var element = elementOfNode(target)
2978
+ if (!element) return false
2979
+ var tag = typeof element.tagName === 'string' ? element.tagName.toLowerCase() : ''
2980
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') return true
2981
+ try {
2982
+ return element.closest('[contenteditable=""],[contenteditable="true"],[contenteditable="plaintext-only"]') !== null
2983
+ } catch (error) {
2984
+ return false
2985
+ }
2986
+ }
2987
+
2988
+ // Alt+C: pick up the selected passage of an answer.
2989
+ function beginMoveFromSelection() {
2990
+ if (getState().sessionId === null) return false
2991
+ var range = readLiveRange()
2992
+ if (range === null) return false
2993
+ var body = messageBodyOf(range.startContainer)
2994
+ if (body === null || body !== messageBodyOf(range.endContainer)) return false
2995
+ var built = buildRecord(range, 'move')
2996
+ if (built === null) return false
2997
+ controller.startMove(built)
2998
+ try {
2999
+ window.getSelection().removeAllRanges()
3000
+ } catch (error) {
3001
+ /* the selection stays; harmless */
3002
+ }
3003
+ paintNow()
3004
+ return true
3005
+ }
3006
+
3007
+ function onKeyDown(event) {
3008
+ if (disposed || !event) return
3009
+ var code = event.code
3010
+ if (
3011
+ event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey &&
3012
+ (code === 'KeyC' || code === 'KeyV')
3013
+ ) {
3014
+ // Typing Alt+C in the composer or any other field is not ours.
3015
+ if (isEditableTarget(event.target) && !isOurUiNode(event.target)) return
3016
+ if (event.repeat) {
3017
+ if (code === 'KeyC' || getState().pendingMove) event.preventDefault()
3018
+ return
3019
+ }
3020
+ if (code === 'KeyC') {
3021
+ if (beginMoveFromSelection()) {
3022
+ event.preventDefault()
3023
+ event.stopPropagation()
3024
+ }
3025
+ return
3026
+ }
3027
+ if (getState().pendingMove) {
3028
+ event.preventDefault()
3029
+ event.stopPropagation()
3030
+ if (!isOurUiNode(event.target)) {
3031
+ var target = caretTarget()
3032
+ if (target !== null) controller.setMoveTarget(target)
3033
+ }
3034
+ if (controller.placeMove()) paintNow()
3035
+ }
3036
+ return
3037
+ }
3038
+ if (event.key !== 'Escape' && event.key !== 'Esc') return
3039
+ if (getState().referenceDraft) {
3040
+ controller.cancelReference()
3041
+ paintNow()
3042
+ return
3043
+ }
3044
+ if (getState().pendingMove) {
3045
+ controller.cancelMove()
3046
+ paintNow()
3047
+ return
3048
+ }
3049
+ if (getState().panelOpen === true && !isOurUiNode(event.target)) controller.setPanelOpen(false)
3050
+ }
3051
+
3052
+ // While a passage waits to be dropped, every click in an answer moves the target.
3053
+ function onSelectionChange() {
3054
+ if (disposed || !getState().pendingMove) return
3055
+ var target = caretTarget()
3056
+ if (target !== null) controller.setMoveTarget(target)
3057
+ }
3058
+
3059
+ function onMutations(mutations) {
3060
+ if (disposed) return
3061
+ try {
3062
+ for (var index = 0; index < mutations.length; index += 1) {
3063
+ if (!isOurUiNode(mutations[index].target)) {
3064
+ schedulePaint(MUTATION_DEBOUNCE)
3065
+ return
3066
+ }
3067
+ }
3068
+ } catch (error) {
3069
+ console.error('dsh-mindmark: mutation handling failed', error)
3070
+ }
3071
+ }
3072
+
3073
+ function onControllerChange() {
3074
+ if (disposed) return
3075
+ var current = getState()
3076
+ if (
3077
+ current.sessionId !== watchedSessionId ||
3078
+ current.annotations !== watchedAnnotations ||
3079
+ current.pendingMove !== watchedMove ||
3080
+ (current.referenceDraft === null) !== (watchedRef === null)
3081
+ ) {
3082
+ watchedRef = current.referenceDraft
3083
+ watchedSessionId = current.sessionId
3084
+ watchedAnnotations = current.annotations
3085
+ watchedMove = current.pendingMove
3086
+ schedulePaint(STATE_REPAINT_DELAY)
3087
+ }
3088
+ }
3089
+
3090
+ if (typeof document !== 'undefined') {
3091
+ disposers.push(addListener(document, 'keydown', onKeyDown, true))
3092
+ disposers.push(addListener(document, 'selectionchange', onSelectionChange, false))
3093
+ disposers.push(addListener(document, 'scroll', onScrollOrResize, true))
3094
+ if (typeof window !== 'undefined') disposers.push(addListener(window, 'resize', onScrollOrResize, false))
3095
+ if (document.body) disposers.push(observeMutations(document.body, onMutations))
3096
+ }
3097
+ disposers.push(subscribeState(onControllerChange))
3098
+
3099
+ return function () {
3100
+ disposed = true
3101
+ cancelPaintTimer()
3102
+ for (var index = 0; index < disposers.length; index += 1) {
3103
+ try {
3104
+ disposers[index]()
3105
+ } catch (error) {
3106
+ console.error('dsh-mindmark: disposer failed', error)
3107
+ }
3108
+ }
3109
+ disposers.length = 0
3110
+ clearHighlights()
3111
+ }
3112
+ }
3113
+
3114
+ function installStyles() {
3115
+ if (typeof document === 'undefined') return function () {}
3116
+ var tag = document.createElement('style')
3117
+ tag.setAttribute('data-plugin-css', CSS_ID)
3118
+ tag.textContent = CSS_TEXT
3119
+ var mount = document.head || document.documentElement
3120
+ if (!mount) return function () {}
3121
+ mount.appendChild(tag)
3122
+ return function () {
3123
+ if (tag.parentNode !== null) tag.parentNode.removeChild(tag)
3124
+ }
3125
+ }
3126
+
3127
+ function injectSlot(slots, name, options, component) {
3128
+ try {
3129
+ slots.inject(name, function () {
3130
+ return slots.register(options, component)
3131
+ })
3132
+ } catch (error) {
3133
+ console.error('dsh-mindmark: cannot register into ' + name, error)
3134
+ }
3135
+ }
3136
+
3137
+ function getService(ctx, key) {
3138
+ try {
3139
+ if (ctx && typeof ctx.get === 'function') {
3140
+ var found = ctx.get(key)
3141
+ if (found) return found
3142
+ }
3143
+ } catch (error) {
3144
+ /* fall through */
3145
+ }
3146
+ try {
3147
+ return ctx ? ctx[key] : null
3148
+ } catch (error) {
3149
+ return null
3150
+ }
3151
+ }
3152
+
3153
+ // ------------------------------------------------------------------ plugin
3154
+
3155
+ function apply(ctx) {
3156
+ var locale = getService(ctx, 'locale')
3157
+ if (locale && typeof locale.getSnapshot === 'function' && typeof locale.subscribe === 'function') {
3158
+ localeService = locale
3159
+ }
3160
+
3161
+ try {
3162
+ if (ctx && typeof ctx.effect === 'function') {
3163
+ ctx.effect(installStyles, 'dsh-mindmark: styles')
3164
+ ctx.effect(installRuntime, 'dsh-mindmark: re-anchoring runtime')
3165
+ } else {
3166
+ installStyles()
3167
+ installRuntime()
3168
+ }
3169
+ } catch (error) {
3170
+ console.error('dsh-mindmark: cannot install the client runtime', error)
3171
+ }
3172
+
3173
+ var slots = getService(ctx, 'slots')
3174
+ if (!slots || typeof slots.inject !== 'function' || typeof slots.register !== 'function') {
3175
+ console.error('dsh-mindmark: the slots service is unavailable; the client half cannot render')
3176
+ return
3177
+ }
3178
+
3179
+ var actions = WithTranslate(SelectionActions)
3180
+ // Take over the Quote plugin's selection surface (it still admits the
3181
+ // gesture and we keep Quote as the first action) …
3182
+ injectSlot(
3183
+ slots,
3184
+ 'conversation.chat.text-interaction',
3185
+ { name: 'conversation.chat.text-interaction', key: 'quote', priority: -10 },
3186
+ actions,
3187
+ )
3188
+ // … and own a surface of our own for hosts without the Quote plugin.
3189
+ injectSlot(
3190
+ slots,
3191
+ 'conversation.chat.text-interaction',
3192
+ { name: 'conversation.chat.text-interaction', key: SURFACE_KEY },
3193
+ actions,
3194
+ )
3195
+ var conversation = getService(ctx, 'uiConversation')
3196
+ if (conversation && conversation.interactions && typeof conversation.interactions.register === 'function') {
3197
+ try {
3198
+ ctx.effect(
3199
+ function () {
3200
+ return conversation.interactions.register({
3201
+ id: SURFACE_KEY,
3202
+ onInteraction: function (request) {
3203
+ if (request.trigger !== 'selection' || request.readText() === null) return
3204
+ request.open()
3205
+ },
3206
+ })
3207
+ },
3208
+ 'dsh-mindmark: selection interaction',
3209
+ )
3210
+ } catch (error) {
3211
+ console.error('dsh-mindmark: cannot register the selection interaction', error)
3212
+ }
3213
+ }
3214
+
3215
+ injectSlot(
3216
+ slots,
3217
+ 'conversation.input.left',
3218
+ { name: 'conversation.input.left', id: 'dsh-mindmark.mode', order: 60 },
3219
+ WithTranslate(ModeSwitch),
3220
+ )
3221
+ injectSlot(
3222
+ slots,
3223
+ 'conversation.session.header.utilities',
3224
+ { name: 'conversation.session.header.utilities', id: 'dsh-mindmark', order: 40 },
3225
+ WithTranslate(AnnotationHeader),
3226
+ )
3227
+ injectSlot(
3228
+ slots,
3229
+ 'shell.overlay',
3230
+ { name: 'shell.overlay', id: 'dsh-mindmark.overlay', order: 40 },
3231
+ WithTranslate(AnnotationOverlay),
3232
+ )
3233
+ }
3234
+
3235
+ exports.apply = apply
3236
+ exports.inject = ['slots']
3237
+ return module.exports
3238
+ },
3239
+ })