dsh-mindmark 0.0.0-stage → 0.3.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,2296 @@
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.
14
+ //
15
+ // Annotations are text anchors, never host-DOM references: the selection is
16
+ // converted into character offsets over the nearest scroll container, stored as
17
+ // a quote + prefix/suffix + CSS path record on the Host, and re-anchored by
18
+ // scoring every `indexOf(quote)` candidate against the saved context. The same
19
+ // selection is also located inside its message body so the Host can render a
20
+ // full revision view. Painting uses the CSS Custom Highlight API, so no DOM
21
+ // inside messages is ever mutated.
22
+ //
23
+ // Everything is plain ES5-flavoured JavaScript with `React.createElement`; no
24
+ // Harness Client packages are imported, all chrome follows the `--dsw-alias-*`
25
+ // theme tokens and everything is namespaced under the `dsa-` class prefix.
26
+
27
+ window.__ModuleLoader__.load({
28
+ id: 'dsh-mindmark',
29
+ factory: (require) => {
30
+ var module = { exports: {} }
31
+ var exports = module.exports
32
+
33
+ var React = require('react')
34
+ var h = React.createElement
35
+ var useEffect = React.useEffect
36
+ var useState = React.useState
37
+ var useRef = React.useRef
38
+ var useSyncExternalStore = React.useSyncExternalStore
39
+
40
+ var ROUTE = '/plugins/dsh-mindmark/annotations'
41
+ var UI_ATTR = 'data-dsh-mindmark-ui'
42
+ var UI_SELECTOR = '[' + UI_ATTR + ']'
43
+ var CSS_ID = 'dsh-mindmark'
44
+ var STYLES = ['highlight', 'underline', 'strike', 'comment', 'rewrite']
45
+ var NOTE_STYLES = { comment: true, rewrite: true }
46
+ var MODES = ['brief', 'full']
47
+ var MAX_QUOTE = 2000
48
+ var MAX_NOTE = 2000
49
+ var MAX_MESSAGE_TEXT = 20000
50
+ var CONTEXT_MAX = 80
51
+ var SELECTOR_MAX = 300
52
+ var ID_MAX = 120
53
+ var MUTATION_DEBOUNCE = 150
54
+ var STATE_REPAINT_DELAY = 60
55
+ var PANEL_TITLE_ID = 'dsa-annotate-panel-title'
56
+ var SURFACE_KEY = 'dsh-mindmark'
57
+
58
+ // ------------------------------------------------------------- dictionaries
59
+
60
+ var DICT = {
61
+ zh: {
62
+ headerLabel: '标注',
63
+ headerTitle: '标注 · {count} 条待处理',
64
+ panelTitle: '我的标注',
65
+ toolbarLabel: '标注操作',
66
+ count: '{count} 条',
67
+ pendingCount: '{count} 条待处理',
68
+ quote: '引用',
69
+ highlight: '高亮',
70
+ underline: '下划线',
71
+ strike: '删除',
72
+ comment: '批注',
73
+ rewrite: '改写',
74
+ 'hint.highlight': '这是我要的:保留并强化',
75
+ 'hint.underline': '这里不够:展开或给依据',
76
+ 'hint.strike': '去掉:下一版不要出现',
77
+ 'hint.comment': '写一条意见,让助手按它处理',
78
+ 'hint.rewrite': '把这段改成你要的样子',
79
+ 'hint.quote': '把选中的文字引用到输入框',
80
+ unmark: '清除标记',
81
+ close: '关闭',
82
+ delete: '删除',
83
+ clearAll: '清空全部',
84
+ resolve: '标为已处理',
85
+ reopen: '重新提交',
86
+ resolveAll: '全部标为已处理',
87
+ confirm: '确定',
88
+ cancel: '取消',
89
+ commentPlaceholder: '写下你的意见…',
90
+ rewritePlaceholder: '改成…',
91
+ statusPending: '待处理',
92
+ statusResolved: '已处理',
93
+ byModel: '助手已处理',
94
+ byUser: '你已处理',
95
+ byCap: '多轮未处理,已自动收起',
96
+ noteLabel: '批注',
97
+ rewriteLabel: '改为',
98
+ modeLabel: '标注注入',
99
+ modeBrief: '精简',
100
+ modeFull: '完整',
101
+ modeBriefHint: '精简:下一轮只发送被标注的段落和少量上下文',
102
+ modeFullHint: '完整:下一轮发送整条回答的修订视图',
103
+ modeTitle: '标注如何送给助手',
104
+ loading: '加载中…',
105
+ empty: '还没有标注。在回答里选中文字,工具条会浮出来。',
106
+ footerHint: '待处理的标注会在下一轮自动送给助手;助手处理后会标为已处理。',
107
+ distill: '沉淀为习惯',
108
+ distillHint: '让助手把这些标注归纳成长期偏好,写进你的全局 AGENTS.md,新对话自动遵守',
109
+ distillPrompt: '请回顾我在这个对话里做过的全部标注(用 annotations 工具 action=list 查看),归纳出我反复表现出的偏好,每条一句、可直接执行、不要带具体内容,然后用 annotations 工具 action=distill 把它们写入 lessons。写完后把沉淀的偏好列给我看。',
110
+ lessonsTitle: '已沉淀的偏好',
111
+ lessonsEmpty: '还没有沉淀过偏好。标注积累几条后,点「沉淀为习惯」让助手归纳。',
112
+ forget: '移除',
113
+ warning: '当前浏览器不支持 CSS Custom Highlight API:标注仍会保存,但不会显示在页面上。',
114
+ 'err.generic': '操作失败,请稍后重试。',
115
+ 'err.network': '无法连接到 Harness,标注没有保存。',
116
+ 'err.http': '标注服务返回了错误。',
117
+ 'err.load': '加载标注失败。',
118
+ 'err.add': '保存标注失败。',
119
+ 'err.remove': '删除标注失败。',
120
+ 'err.clear': '清空标注失败。',
121
+ 'err.resolve': '更新标注状态失败。',
122
+ 'err.mode': '切换模式失败。',
123
+ 'err.invalid': '标注数据不完整,没有保存。',
124
+ },
125
+ en: {
126
+ headerLabel: 'Annotations',
127
+ headerTitle: 'Annotations · {count} pending',
128
+ panelTitle: 'My annotations',
129
+ toolbarLabel: 'Annotate selection',
130
+ count: '{count}',
131
+ pendingCount: '{count} pending',
132
+ quote: 'Quote',
133
+ highlight: 'Highlight',
134
+ underline: 'Underline',
135
+ strike: 'Strike',
136
+ comment: 'Comment',
137
+ rewrite: 'Rewrite',
138
+ 'hint.highlight': 'This is what I want: keep and strengthen it',
139
+ 'hint.underline': 'Not enough here: expand or justify',
140
+ 'hint.strike': 'Drop this next time',
141
+ 'hint.comment': 'Leave a note the assistant must act on',
142
+ 'hint.rewrite': 'Replace this passage with your own words',
143
+ 'hint.quote': 'Quote the selection into the composer',
144
+ unmark: 'Remove marks',
145
+ close: 'Close',
146
+ delete: 'Delete',
147
+ clearAll: 'Clear all',
148
+ resolve: 'Mark handled',
149
+ reopen: 'Send again',
150
+ resolveAll: 'Mark all handled',
151
+ confirm: 'OK',
152
+ cancel: 'Cancel',
153
+ commentPlaceholder: 'Your note…',
154
+ rewritePlaceholder: 'Replace with…',
155
+ statusPending: 'Pending',
156
+ statusResolved: 'Handled',
157
+ byModel: 'Handled by the assistant',
158
+ byUser: 'Handled by you',
159
+ byCap: 'Auto-settled after several turns',
160
+ noteLabel: 'Note',
161
+ rewriteLabel: 'Replace with',
162
+ modeLabel: 'Annotation feed',
163
+ modeBrief: 'Brief',
164
+ modeFull: 'Full',
165
+ modeBriefHint: 'Brief: next turn sends only the annotated passages with a little context',
166
+ modeFullHint: 'Full: next turn sends the whole answer as a revision view',
167
+ modeTitle: 'How annotations reach the assistant',
168
+ loading: 'Loading…',
169
+ empty: 'No annotations yet. Select text in an answer and the toolbar appears.',
170
+ footerHint: 'Pending annotations are sent to the assistant on the next turn; it marks them handled afterwards.',
171
+ distill: 'Keep as habit',
172
+ distillHint: 'Ask the assistant to distill these annotations into long-term preferences in your global AGENTS.md',
173
+ 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.',
174
+ lessonsTitle: 'Distilled preferences',
175
+ lessonsEmpty: 'Nothing distilled yet. After a few annotations, click "Keep as habit" to let the assistant summarize them.',
176
+ forget: 'Remove',
177
+ warning: 'This browser does not support the CSS Custom Highlight API: annotations are still saved but will not be painted.',
178
+ 'err.generic': 'Something went wrong. Try again.',
179
+ 'err.network': 'Could not reach the Harness; the annotation was not saved.',
180
+ 'err.http': 'The annotation service returned an error.',
181
+ 'err.load': 'Could not load annotations.',
182
+ 'err.add': 'Could not save the annotation.',
183
+ 'err.remove': 'Could not delete the annotation.',
184
+ 'err.clear': 'Could not clear annotations.',
185
+ 'err.resolve': 'Could not update the annotation.',
186
+ 'err.mode': 'Could not switch the mode.',
187
+ 'err.invalid': 'The annotation data was incomplete and was not saved.',
188
+ },
189
+ }
190
+
191
+ // ---------------------------------------------------------------- locale
192
+
193
+ var fallbackLocale = {
194
+ subscribe: function () {
195
+ return function () {}
196
+ },
197
+ getSnapshot: function () {
198
+ return { active: 'zh', revision: 0 }
199
+ },
200
+ }
201
+ var localeService = fallbackLocale
202
+
203
+ function subscribeLocale(listener) {
204
+ try {
205
+ if (localeService && typeof localeService.subscribe === 'function') return localeService.subscribe(listener)
206
+ } catch (error) {
207
+ console.error('dsh-mindmark: locale subscribe failed', error)
208
+ }
209
+ return function () {}
210
+ }
211
+
212
+ function localeRevision() {
213
+ try {
214
+ var snapshot = localeService.getSnapshot()
215
+ if (snapshot && typeof snapshot.revision === 'number') return snapshot.revision
216
+ if (snapshot && typeof snapshot.active === 'string') return snapshot.active
217
+ } catch (error) {
218
+ /* fall through */
219
+ }
220
+ return 'default'
221
+ }
222
+
223
+ function useLocaleRevision() {
224
+ return useSyncExternalStore(subscribeLocale, localeRevision, localeRevision)
225
+ }
226
+
227
+ function translate(key, vars) {
228
+ var active = 'zh'
229
+ try {
230
+ var snapshot = localeService.getSnapshot()
231
+ if (snapshot && typeof snapshot.active === 'string') active = snapshot.active
232
+ } catch (error) {
233
+ active = 'zh'
234
+ }
235
+ var dict = String(active).toLowerCase().indexOf('zh') === 0 ? DICT.zh : DICT.en
236
+ var value = dict[key]
237
+ if (value === undefined) value = DICT.en[key]
238
+ if (value === undefined) value = key
239
+ if (vars && typeof value === 'string') {
240
+ return value.replace(/\{(\w+)\}/g, function (match, name) {
241
+ return vars[name] !== undefined ? String(vars[name]) : match
242
+ })
243
+ }
244
+ return value
245
+ }
246
+
247
+ function WithTranslate(component) {
248
+ return function Translated(props) {
249
+ useLocaleRevision()
250
+ var next = {}
251
+ for (var key in props) next[key] = props[key]
252
+ next.t = translate
253
+ return h(component, next)
254
+ }
255
+ }
256
+
257
+ // ------------------------------------------------------------------ styles
258
+
259
+ var MARK_COLORS = {
260
+ highlight: { pending: 'background-color:#f5c542;color:#1b1b1f', resolved: 'background-color:color-mix(in srgb,#f5c542 45%,transparent)' },
261
+ underline: {
262
+ pending: 'text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:2px;text-decoration-color:#4d7cfe',
263
+ resolved: 'text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:2px;text-decoration-color:color-mix(in srgb,#4d7cfe 45%,transparent)',
264
+ },
265
+ strike: {
266
+ pending: 'text-decoration:line-through;text-decoration-thickness:2px;text-decoration-color:#e5484d;background-color:color-mix(in srgb,#e5484d 14%,transparent)',
267
+ resolved: 'text-decoration:line-through;text-decoration-thickness:2px;text-decoration-color:color-mix(in srgb,#e5484d 50%,transparent)',
268
+ },
269
+ comment: {
270
+ pending: 'background-color:color-mix(in srgb,#2fb36f 24%,transparent);text-decoration:underline dotted;text-decoration-color:#2fb36f;text-underline-offset:2px',
271
+ resolved: 'text-decoration:underline dotted;text-decoration-color:color-mix(in srgb,#2fb36f 55%,transparent);text-underline-offset:2px',
272
+ },
273
+ rewrite: {
274
+ pending: 'background-color:color-mix(in srgb,#a06bff 22%,transparent);text-decoration:line-through;text-decoration-color:#a06bff',
275
+ resolved: 'text-decoration:line-through;text-decoration-color:color-mix(in srgb,#a06bff 50%,transparent)',
276
+ },
277
+ }
278
+
279
+ function highlightName(style, status) {
280
+ return 'dsa-' + style + (status === 'resolved' ? '-resolved' : '')
281
+ }
282
+
283
+ var CSS_LINES = [
284
+ '[data-dsh-mindmark-ui]{box-sizing:border-box}',
285
+ '[data-dsh-mindmark-ui] *{box-sizing:border-box}',
286
+ '.dsa-header-btn{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:4px;',
287
+ 'height:26px;min-width:26px;padding:0 6px;border:1px solid transparent;border-radius:7px;background:transparent;',
288
+ 'color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:12px;line-height:1;cursor:pointer}',
289
+ '.dsa-header-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#343844);color:var(--dsw-alias-label-primary,#f2f4f7)}',
290
+ '.dsa-header-btn.is-active{color:var(--dsw-alias-brand-primary,#4d7cfe);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
291
+ '.dsa-header-btn:focus-visible,.dsa-tool-btn:focus-visible,.dsa-tool-close:focus-visible,.dsa-panel-close:focus-visible,',
292
+ '.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}',
293
+ '.dsa-header-btn svg{display:block;flex:none}',
294
+ '.dsa-header-badge{min-width:15px;height:15px;padding:0 4px;border-radius:999px;',
295
+ 'background:var(--dsw-alias-brand-primary,#4d7cfe);color:var(--dsw-alias-label-primary-foreground,#10131a);',
296
+ 'font-size:10px;line-height:15px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums}',
297
+ // selection action bar (rendered inside the Chat view's own surface)
298
+ '.dsa-toolbar{display:flex;align-items:center;gap:2px;padding:4px;',
299
+ 'border-radius:10px;background:var(--dsw-alias-button-floating-fill,var(--dsw-alias-bg-overlay,#2a2d36));',
300
+ 'border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l1,#3b3f4a));',
301
+ 'box-shadow:var(--dsw-elevation-panel,0 10px 28px rgba(0,0,0,.32));color:var(--dsw-alias-label-primary,#f2f4f7);',
302
+ 'font-family:inherit;font-size:13px;line-height:1;white-space:nowrap;pointer-events:auto}',
303
+ '.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)}',
304
+ '.dsa-tool-btn{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 8px;border:0;border-radius:7px;',
305
+ 'background:transparent;color:inherit;font:inherit;font-size:12.5px;line-height:1;cursor:pointer;white-space:nowrap}',
306
+ '.dsa-tool-btn:hover{background:var(--dsw-alias-button-floating-hover,var(--dsw-alias-interactive-bg-hover,#343844))}',
307
+ '.dsa-tool-glyph{width:10px;height:10px;flex:none;border-radius:2px}',
308
+ '.dsa-tool-glyph-highlight{background:#f5c542}',
309
+ '.dsa-tool-glyph-underline{height:9px;border-radius:0;border-bottom:2px solid #4d7cfe}',
310
+ '.dsa-tool-glyph-strike{height:9px;border-radius:0;background:linear-gradient(transparent 40%,#e5484d 40%,#e5484d 60%,transparent 60%)}',
311
+ '.dsa-tool-glyph-comment{border-radius:50%;background:#2fb36f}',
312
+ '.dsa-tool-glyph-rewrite{background:#a06bff}',
313
+ '.dsa-tool-glyph-quote{width:9px;height:9px;border-left:3px solid var(--dsw-alias-label-secondary,#a3a8b4);border-radius:0}',
314
+ '.dsa-tool-divider{width:1px;height:16px;margin:0 2px;flex:none;background:var(--dsw-alias-border-l1,#3b3f4a)}',
315
+ '.dsa-tool-close{width:26px;height:26px;padding:0;display:inline-grid;place-items:center;border:0;border-radius:7px;',
316
+ 'background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:15px;line-height:1;cursor:pointer}',
317
+ '.dsa-tool-close:hover{color:var(--dsw-alias-label-primary,#f2f4f7);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
318
+ '.dsa-note-head{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
319
+ '.dsa-note-quote{margin:0;max-height:56px;overflow:hidden;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary,#a3a8b4);',
320
+ 'border-left:2px solid var(--dsw-alias-border-l1,#3b3f4a);padding-left:8px;white-space:normal;word-break:break-word}',
321
+ '.dsa-note-input{width:100%;min-height:58px;max-height:160px;resize:vertical;padding:7px 9px;border-radius:8px;',
322
+ 'border:1px solid var(--dsw-alias-border-l1,#3b3f4a);background:var(--dsw-alias-bg-layer-1,#20232b);color:var(--dsw-alias-label-primary,#f2f4f7);',
323
+ 'font:inherit;font-size:13px;line-height:1.5;white-space:pre-wrap}',
324
+ '.dsa-note-actions{display:flex;justify-content:flex-end;gap:6px}',
325
+ // composer mode switch
326
+ '.dsa-mode{display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 4px 0 8px;border-radius:8px;',
327
+ '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}',
328
+ '.dsa-mode-label{display:inline-flex;align-items:center;gap:4px}',
329
+ '.dsa-mode-label svg{display:block}',
330
+ '.dsa-mode-seg{display:inline-flex;padding:2px;border-radius:6px;background:var(--dsw-alias-bg-layer-2,#343844);gap:2px}',
331
+ '.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}',
332
+ '.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)}',
333
+ '.dsa-mode-btn:disabled{cursor:default;opacity:.6}',
334
+ '.dsa-mode-badge{min-width:15px;height:15px;padding:0 4px;border-radius:999px;background:var(--dsw-alias-brand-primary,#4d7cfe);',
335
+ '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}',
336
+ '@container (max-width: 520px){.dsa-mode-label span{display:none}}',
337
+ // panel
338
+ '[data-dsh-mindmark-ui].dsa-layer{position:fixed;inset:0;z-index:70;pointer-events:none}',
339
+ '.dsa-panel{position:fixed;z-index:70;pointer-events:auto;top:64px;right:16px;width:360px;',
340
+ 'max-width:calc(100vw - 24px);max-height:min(600px,calc(100vh - 96px));display:flex;flex-direction:column;',
341
+ 'border-radius:12px;border:1px solid var(--dsw-alias-border-l1,#3b3f4a);background:var(--dsw-alias-bg-overlay,#2a2d36);',
342
+ 'color:var(--dsw-alias-label-primary,#f2f4f7);box-shadow:0 18px 48px rgba(0,0,0,.36);font-family:inherit;',
343
+ 'font-size:13px;overflow:hidden;animation:dsa-panel-in 140ms ease-out}',
344
+ '@keyframes dsa-panel-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}',
345
+ '.dsa-panel-head{flex:none;display:flex;align-items:center;gap:8px;padding:10px 12px;',
346
+ 'border-bottom:1px solid var(--dsw-alias-border-l1,#3b3f4a)}',
347
+ '.dsa-panel-title{font-size:13.5px;font-weight:600;line-height:20px}',
348
+ '.dsa-panel-count{flex:none;padding:0 6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2,#343844);',
349
+ 'color:var(--dsw-alias-label-secondary,#a3a8b4);font-size:11px;line-height:16px;font-variant-numeric:tabular-nums}',
350
+ '.dsa-spacer{flex:1}',
351
+ '.dsa-panel-close{width:24px;height:24px;padding:0;display:inline-grid;place-items:center;border:0;border-radius:6px;',
352
+ 'background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;font-size:15px;line-height:1;cursor:pointer}',
353
+ '.dsa-panel-close:hover{color:var(--dsw-alias-label-primary,#f2f4f7);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
354
+ '.dsa-panel-body{flex:1;min-height:40px;overflow-y:auto;overscroll-behavior:contain;padding:6px 8px;',
355
+ 'display:flex;flex-direction:column;gap:2px}',
356
+ '.dsa-empty,.dsa-loading{margin:0;padding:18px 10px;color:var(--dsw-alias-label-secondary,#a3a8b4);',
357
+ 'font-size:12.5px;line-height:1.7;text-align:center}',
358
+ '.dsa-item{display:flex;align-items:flex-start;gap:8px;padding:8px;border-radius:8px}',
359
+ '.dsa-item:hover{background:var(--dsw-alias-interactive-bg-hover,#343844)}',
360
+ '.dsa-item.is-resolved{opacity:.72}',
361
+ '.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)}',
362
+ '.dsa-chip-highlight{background:color-mix(in srgb,#f5c542 32%,transparent)}',
363
+ '.dsa-chip-underline{border:1px solid color-mix(in srgb,#4d7cfe 55%,transparent);color:#7ea0ff}',
364
+ '.dsa-chip-strike{background:color-mix(in srgb,#e5484d 22%,transparent)}',
365
+ '.dsa-chip-comment{background:color-mix(in srgb,#2fb36f 24%,transparent)}',
366
+ '.dsa-chip-rewrite{background:color-mix(in srgb,#a06bff 24%,transparent)}',
367
+ '.dsa-item-main{flex:1;min-width:0}',
368
+ '.dsa-quote{margin:0;font-size:12.5px;line-height:1.55;color:var(--dsw-alias-label-primary,#f2f4f7);',
369
+ 'overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;word-break:break-word}',
370
+ '.dsa-note{margin:3px 0 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-primary,#f2f4f7);word-break:break-word;',
371
+ 'border-left:2px solid var(--dsw-alias-border-l1,#3b3f4a);padding-left:7px;white-space:pre-wrap}',
372
+ '.dsa-note b{font-weight:600;color:var(--dsw-alias-label-secondary,#a3a8b4);margin-right:4px}',
373
+ '.dsa-meta{margin:3px 0 0;font-size:11px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f9c);',
374
+ 'font-variant-numeric:tabular-nums;display:flex;gap:6px;flex-wrap:wrap;align-items:center}',
375
+ '.dsa-status{padding:0 5px;border-radius:4px;background:var(--dsw-alias-bg-layer-2,#343844)}',
376
+ '.dsa-status.is-pending{color:var(--dsw-alias-brand-primary,#4d7cfe)}',
377
+ '.dsa-item-actions{flex:none;display:flex;gap:2px}',
378
+ '.dsa-item-btn{width:22px;height:22px;padding:0;display:inline-grid;place-items:center;border:0;',
379
+ 'border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#a3a8b4);font:inherit;',
380
+ 'font-size:13px;line-height:1;cursor:pointer;opacity:.7}',
381
+ '.dsa-item-btn:hover{opacity:1;background:var(--dsw-alias-interactive-bg-hover,#343844);color:var(--dsw-alias-label-primary,#f2f4f7)}',
382
+ '.dsa-item-btn.is-del:hover{color:var(--dsw-alias-state-error-primary,#e5484d);',
383
+ 'background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#e5484d) 12%,transparent)}',
384
+ '.dsa-lessons{flex:none;max-height:170px;overflow-y:auto;border-top:1px solid var(--dsw-alias-border-l1,#3b3f4a);padding:6px 10px 4px}',
385
+ '.dsa-lessons-title{margin:0 0 4px;font-size:11.5px;font-weight:600;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
386
+ '.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)}',
387
+ '.dsa-lesson span{flex:1;min-width:0;word-break:break-word}',
388
+ '.dsa-lesson small{flex:none;color:var(--dsw-alias-label-tertiary,#8a8f9c);font-variant-numeric:tabular-nums}',
389
+ '.dsa-lessons-empty{margin:0 0 4px;font-size:11.5px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a8f9c)}',
390
+ '.dsa-panel-foot{flex:none;display:flex;align-items:center;gap:8px;padding:8px 12px 10px;flex-wrap:wrap;',
391
+ 'border-top:1px solid var(--dsw-alias-border-l1,#3b3f4a)}',
392
+ '.dsa-hint{flex:1;min-width:0;margin:0;font-size:11px;line-height:15px;color:var(--dsw-alias-label-secondary,#a3a8b4)}',
393
+ '.dsa-btn{flex:none;height:26px;padding:0 10px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1,#3b3f4a);',
394
+ 'background:transparent;color:var(--dsw-alias-label-primary,#f2f4f7);font:inherit;font-size:12px;cursor:pointer}',
395
+ '.dsa-btn.is-primary{background:var(--dsw-alias-brand-primary,#4d7cfe);border-color:transparent;color:var(--dsw-alias-label-primary-foreground,#10131a)}',
396
+ '.dsa-btn:hover:not(:disabled){filter:brightness(1.1);background:var(--dsw-alias-interactive-bg-hover,#343844)}',
397
+ '.dsa-btn.is-primary:hover:not(:disabled){background:var(--dsw-alias-brand-primary,#4d7cfe)}',
398
+ '.dsa-btn:disabled{opacity:.5;cursor:default}',
399
+ '.dsa-warning,.dsa-error{flex:none;margin:8px 10px 0;padding:7px 9px;border-radius:8px;font-size:11.5px;line-height:16px}',
400
+ '.dsa-warning{color:var(--dsw-alias-state-warn-primary,#f0b35b);',
401
+ 'background:color-mix(in srgb,var(--dsw-alias-state-warn-primary,#f0b35b) 12%,transparent)}',
402
+ '.dsa-error{color:var(--dsw-alias-state-error-primary,#ff6b6b);',
403
+ 'background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#e5484d) 12%,transparent)}',
404
+ '@media (max-width:560px){.dsa-panel{top:56px;right:8px;left:8px;width:auto;max-width:none}}',
405
+ '@media (prefers-reduced-motion:reduce){.dsa-panel{animation:none}}',
406
+ ]
407
+ STYLES.forEach(function (style) {
408
+ CSS_LINES.push('::highlight(' + highlightName(style, 'pending') + '){' + MARK_COLORS[style].pending + '}')
409
+ CSS_LINES.push('::highlight(' + highlightName(style, 'resolved') + '){' + MARK_COLORS[style].resolved + '}')
410
+ })
411
+ var CSS_TEXT = CSS_LINES.join('\n')
412
+
413
+ // ------------------------------------------------------------------- icons
414
+
415
+ function MarkerIcon(props) {
416
+ var size = props && typeof props.size === 'number' ? props.size : 16
417
+ return h(
418
+ 'svg',
419
+ { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true', focusable: 'false' },
420
+ 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' }),
421
+ h('path', { d: 'M8.5 3.7l3.8 3.8', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }),
422
+ h('path', { d: 'M3.3 14.2h9.4', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }),
423
+ )
424
+ }
425
+
426
+ // ------------------------------------------------------------------- utils
427
+
428
+ function hasOwn(object, key) {
429
+ return Object.prototype.hasOwnProperty.call(object, key)
430
+ }
431
+
432
+ function clipString(value, max) {
433
+ if (typeof value !== 'string') return ''
434
+ return value.length > max ? value.slice(0, max) : value
435
+ }
436
+
437
+ function pad2(value) {
438
+ return String(value).padStart(2, '0')
439
+ }
440
+
441
+ function formatTimestamp(value) {
442
+ try {
443
+ var date = new Date(value)
444
+ if (Number.isNaN(date.getTime())) return ''
445
+ return (
446
+ date.getFullYear() + '-' + pad2(date.getMonth() + 1) + '-' + pad2(date.getDate()) +
447
+ ' ' + pad2(date.getHours()) + ':' + pad2(date.getMinutes())
448
+ )
449
+ } catch (error) {
450
+ return ''
451
+ }
452
+ }
453
+
454
+ function previewQuote(quote, max) {
455
+ var limit = typeof max === 'number' ? max : 140
456
+ var text = String(quote || '').replace(/\s+/g, ' ').trim()
457
+ if (text.length > limit) return text.slice(0, limit) + '…'
458
+ return text
459
+ }
460
+
461
+ function compareCreatedAt(left, right) {
462
+ var leftTime = Date.parse(left && left.createdAt) || 0
463
+ var rightTime = Date.parse(right && right.createdAt) || 0
464
+ if (leftTime === rightTime) return 0
465
+ return leftTime < rightTime ? -1 : 1
466
+ }
467
+
468
+ function createClientId() {
469
+ return 'ann_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8)
470
+ }
471
+
472
+ function errorText(t, error) {
473
+ if (!error || typeof error !== 'object') return ''
474
+ if (error.code === 'http' && typeof error.message === 'string' && error.message.length > 0) return error.message
475
+ var key = 'err.' + (typeof error.code === 'string' ? error.code : 'generic')
476
+ var localized = t(key)
477
+ if (localized !== key) return localized
478
+ if (typeof error.message === 'string' && error.message.length > 0) return error.message
479
+ return t('err.generic')
480
+ }
481
+
482
+ function failureToError(failure, operation) {
483
+ var code = failure && typeof failure.code === 'string' ? failure.code : 'http'
484
+ var message = failure && typeof failure.message === 'string' ? failure.message : ''
485
+ if (code === 'network') return { code: 'network', operation: operation, message: message }
486
+ if (code === 'http') return { code: 'http', operation: operation, message: message }
487
+ return { code: operation || 'generic', message: message }
488
+ }
489
+
490
+ function isStyle(value) {
491
+ return STYLES.indexOf(value) >= 0
492
+ }
493
+
494
+ function normalizeMode(value) {
495
+ return MODES.indexOf(value) >= 0 ? value : 'brief'
496
+ }
497
+
498
+ // ------------------------------------------------------------ DOM helpers
499
+
500
+ function elementOfNode(node) {
501
+ if (!node) return null
502
+ if (node.nodeType === 1) return node
503
+ if (node.parentElement) return node.parentElement
504
+ return null
505
+ }
506
+
507
+ function isOurUiNode(node) {
508
+ try {
509
+ var element = elementOfNode(node)
510
+ if (!element || typeof element.closest !== 'function') return false
511
+ return element.closest(UI_SELECTOR) !== null
512
+ } catch (error) {
513
+ return false
514
+ }
515
+ }
516
+
517
+ function isOurUiElement(element) {
518
+ if (!element || element.nodeType !== 1 || typeof element.closest !== 'function') return false
519
+ try {
520
+ return element.closest(UI_SELECTOR) !== null
521
+ } catch (error) {
522
+ return false
523
+ }
524
+ }
525
+
526
+ function isSkippedElement(element, checkOwnUi) {
527
+ if (!element || element.nodeType !== 1) return false
528
+ var tag = typeof element.tagName === 'string' ? element.tagName.toLowerCase() : ''
529
+ if (tag === 'script' || tag === 'style' || tag === 'noscript') return true
530
+ if (checkOwnUi === false) return false
531
+ return isOurUiElement(element)
532
+ }
533
+
534
+ function isScrollContainer(element) {
535
+ try {
536
+ if (!element || element.nodeType !== 1) return false
537
+ if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') return false
538
+ var style = window.getComputedStyle(element)
539
+ if (!style) return false
540
+ var overflowY = style.overflowY
541
+ if (overflowY !== 'auto' && overflowY !== 'scroll') return false
542
+ return element.scrollHeight > element.clientHeight + 20
543
+ } catch (error) {
544
+ return false
545
+ }
546
+ }
547
+
548
+ // The nearest scrollable ancestor of the selection is the indexing root; when
549
+ // there is none the whole body is. Host class names are never consulted.
550
+ function findRoot(range) {
551
+ try {
552
+ var current = elementOfNode(range && range.commonAncestorContainer)
553
+ while (current && current !== document.documentElement) {
554
+ if (!isOurUiElement(current) && isScrollContainer(current)) return current
555
+ current = current.parentElement
556
+ }
557
+ } catch (error) {
558
+ console.error('dsh-mindmark: cannot find the selection root', error)
559
+ }
560
+ return document.body
561
+ }
562
+
563
+ // Raw text-node values in document order (never whitespace-normalized), with
564
+ // cumulative offsets, skipping our own UI and script/style subtrees.
565
+ function buildIndex(root) {
566
+ var nodes = []
567
+ var starts = new Map()
568
+ var text = ''
569
+ try {
570
+ if (!root) return { nodes: nodes, text: text, starts: starts }
571
+ var checkOwnUi = root === document.body
572
+ var walker = document.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */, null)
573
+ var node = walker.nextNode()
574
+ while (node !== null) {
575
+ if (!isSkippedElement(node.parentElement, checkOwnUi)) {
576
+ var value = node.nodeValue
577
+ if (typeof value === 'string' && value.length > 0) {
578
+ nodes.push({ node: node, start: text.length, length: value.length })
579
+ starts.set(node, text.length)
580
+ text += value
581
+ }
582
+ }
583
+ node = walker.nextNode()
584
+ }
585
+ } catch (error) {
586
+ console.error('dsh-mindmark: text indexing failed', error)
587
+ }
588
+ return { nodes: nodes, text: text, starts: starts }
589
+ }
590
+
591
+ function firstIndexedTextNodeIn(subtree, index) {
592
+ if (!subtree) return null
593
+ if (subtree.nodeType === 3) return index.starts.has(subtree) ? subtree : null
594
+ if (subtree.nodeType !== 1) return null
595
+ try {
596
+ var walker = document.createTreeWalker(subtree, 4, null)
597
+ var node = walker.nextNode()
598
+ while (node !== null) {
599
+ if (index.starts.has(node)) return node
600
+ node = walker.nextNode()
601
+ }
602
+ } catch (error) {
603
+ /* the subtree is unreadable: treat it as containing no text */
604
+ }
605
+ return null
606
+ }
607
+
608
+ function lastIndexedTextNodeIn(container, index) {
609
+ try {
610
+ if (!container || typeof document.createTreeWalker !== 'function') return null
611
+ var walker = document.createTreeWalker(container, 4, null)
612
+ var node = walker.nextNode()
613
+ var last = null
614
+ while (node !== null) {
615
+ if (index.starts.has(node)) last = node
616
+ node = walker.nextNode()
617
+ }
618
+ return last
619
+ } catch (error) {
620
+ return null
621
+ }
622
+ }
623
+
624
+ function offsetOf(index, container, offset) {
625
+ try {
626
+ if (!index || !container) return 0
627
+ if (container.nodeType === 3) {
628
+ var known = index.starts.get(container)
629
+ if (typeof known === 'number') {
630
+ var length = typeof container.nodeValue === 'string' ? container.nodeValue.length : 0
631
+ var local = typeof offset === 'number' ? offset : 0
632
+ return known + Math.max(0, Math.min(local, length))
633
+ }
634
+ return index.text.length
635
+ }
636
+ var children = container.childNodes
637
+ if (!children) return index.text.length
638
+ var position = typeof offset === 'number' ? Math.max(0, Math.min(offset, children.length)) : 0
639
+ for (var childIndexValue = position; childIndexValue < children.length; childIndexValue += 1) {
640
+ var staged = firstIndexedTextNodeIn(children[childIndexValue], index)
641
+ if (staged !== null) {
642
+ var stagedStart = index.starts.get(staged)
643
+ if (typeof stagedStart === 'number') return stagedStart
644
+ }
645
+ }
646
+ var lastText = lastIndexedTextNodeIn(container, index)
647
+ if (lastText !== null) {
648
+ var lastStart = index.starts.get(lastText)
649
+ if (typeof lastStart === 'number') {
650
+ return lastStart + (typeof lastText.nodeValue === 'string' ? lastText.nodeValue.length : 0)
651
+ }
652
+ }
653
+ return index.text.length
654
+ } catch (error) {
655
+ console.error('dsh-mindmark: offset lookup failed', error)
656
+ return 0
657
+ }
658
+ }
659
+
660
+ function escapeIdent(value) {
661
+ var text = String(value)
662
+ try {
663
+ if (typeof CSS !== 'undefined' && CSS && typeof CSS.escape === 'function') return CSS.escape(text)
664
+ } catch (error) {
665
+ /* fall through to the hand-rolled escape */
666
+ }
667
+ return text.replace(/([^a-zA-Z0-9_-])/g, '\\$1')
668
+ }
669
+
670
+ function elementSiblingIndex(element) {
671
+ var index = 1
672
+ var sibling = element
673
+ while (sibling && sibling.previousElementSibling) {
674
+ sibling = sibling.previousElementSibling
675
+ index += 1
676
+ }
677
+ return index
678
+ }
679
+
680
+ function cssPath(element) {
681
+ try {
682
+ if (!element || element.nodeType !== 1) return ''
683
+ var segments = []
684
+ var current = element
685
+ var depth = 0
686
+ while (current && current.nodeType === 1 && depth < 6) {
687
+ if (current === document.documentElement) {
688
+ segments.unshift('html')
689
+ break
690
+ }
691
+ if (current === document.body) {
692
+ segments.unshift('body')
693
+ break
694
+ }
695
+ var tag = typeof current.tagName === 'string' ? current.tagName.toLowerCase() : ''
696
+ if (tag.length === 0) break
697
+ var segment = tag
698
+ if (current.id) {
699
+ segment += '#' + escapeIdent(current.id)
700
+ segments.unshift(segment)
701
+ break
702
+ }
703
+ var classList = current.classList
704
+ var classCount = 0
705
+ if (classList && classList.length > 0) {
706
+ for (var index = 0; index < classList.length && classCount < 3; index += 1) {
707
+ var className = classList[index]
708
+ if (typeof className !== 'string' || className.length === 0 || className.length > 40) continue
709
+ segment += '.' + escapeIdent(className)
710
+ classCount += 1
711
+ }
712
+ }
713
+ var parent = current.parentElement
714
+ if (parent) segment += ':nth-child(' + elementSiblingIndex(current) + ')'
715
+ segments.unshift(segment)
716
+ current = parent
717
+ depth += 1
718
+ }
719
+ var path = segments.join(' > ')
720
+ while (segments.length > 1 && path.length > SELECTOR_MAX) {
721
+ segments.shift()
722
+ path = segments.join(' > ')
723
+ }
724
+ return path.length > SELECTOR_MAX ? '' : path
725
+ } catch (error) {
726
+ console.error('dsh-mindmark: cannot build a CSS path', error)
727
+ return ''
728
+ }
729
+ }
730
+
731
+ function resolveRoot(selector) {
732
+ try {
733
+ if (typeof selector === 'string' && selector.length > 0 && selector.length <= SELECTOR_MAX) {
734
+ var element = document.querySelector(selector)
735
+ if (element && element.nodeType === 1 && !isOurUiElement(element)) return element
736
+ }
737
+ } catch (error) {
738
+ /* a stale or malformed selector falls back to body */
739
+ }
740
+ return document.body
741
+ }
742
+
743
+ // --------------------------------------------------------- anchoring
744
+
745
+ function commonPrefixLen(left, right) {
746
+ if (typeof left !== 'string' || typeof right !== 'string') return 0
747
+ var max = Math.min(left.length, right.length)
748
+ var index = 0
749
+ while (index < max && left.charCodeAt(index) === right.charCodeAt(index)) index += 1
750
+ return index
751
+ }
752
+
753
+ function commonSuffixLen(left, right) {
754
+ if (typeof left !== 'string' || typeof right !== 'string') return 0
755
+ var max = Math.min(left.length, right.length)
756
+ var index = 0
757
+ while (index < max && left.charCodeAt(left.length - 1 - index) === right.charCodeAt(right.length - 1 - index)) {
758
+ index += 1
759
+ }
760
+ return index
761
+ }
762
+
763
+ function positionAtOffset(index, offset) {
764
+ var nodes = index.nodes
765
+ if (!nodes || nodes.length === 0) return null
766
+ if (offset <= 0) return { node: nodes[0].node, offset: 0 }
767
+ if (offset >= index.text.length) {
768
+ var last = nodes[nodes.length - 1]
769
+ var lastLength = typeof last.node.nodeValue === 'string' ? last.node.nodeValue.length : 0
770
+ return { node: last.node, offset: lastLength }
771
+ }
772
+ var low = 0
773
+ var high = nodes.length - 1
774
+ var found = 0
775
+ while (low <= high) {
776
+ var mid = (low + high) >> 1
777
+ if (nodes[mid].start <= offset) {
778
+ found = mid
779
+ low = mid + 1
780
+ } else {
781
+ high = mid - 1
782
+ }
783
+ }
784
+ var entry = nodes[found]
785
+ var local = offset - entry.start
786
+ var maxLocal = typeof entry.node.nodeValue === 'string' ? entry.node.nodeValue.length : 0
787
+ return { node: entry.node, offset: Math.max(0, Math.min(local, maxLocal)) }
788
+ }
789
+
790
+ function rangeFromOffsets(index, start, end) {
791
+ var maxOffset = index.text.length
792
+ var safeStart = Math.max(0, Math.min(start, maxOffset))
793
+ var safeEnd = Math.max(0, Math.min(end, maxOffset))
794
+ if (safeEnd <= safeStart) return null
795
+ var startPosition = positionAtOffset(index, safeStart)
796
+ var endPosition = positionAtOffset(index, safeEnd)
797
+ if (startPosition === null || endPosition === null) return null
798
+ try {
799
+ var range = document.createRange()
800
+ range.setStart(startPosition.node, startPosition.offset)
801
+ range.setEnd(endPosition.node, endPosition.offset)
802
+ return range
803
+ } catch (error) {
804
+ return null
805
+ }
806
+ }
807
+
808
+ function locateAnnotationRange(annotation, index) {
809
+ try {
810
+ if (!annotation || typeof annotation.quote !== 'string' || annotation.quote.length === 0) return null
811
+ var text = index.text
812
+ if (!text || text.length === 0) return null
813
+ var quote = annotation.quote
814
+ var prefix = typeof annotation.prefix === 'string' ? annotation.prefix : ''
815
+ var suffix = typeof annotation.suffix === 'string' ? annotation.suffix : ''
816
+ var bestStart = -1
817
+ var bestScore = -1
818
+ var bestPossible = prefix.length + suffix.length
819
+ var searchFrom = 0
820
+ var guard = 0
821
+ while (guard < 500) {
822
+ var found = text.indexOf(quote, searchFrom)
823
+ if (found === -1) break
824
+ var score = 0
825
+ var beforeContext = text.slice(Math.max(0, found - prefix.length), found)
826
+ score += commonSuffixLen(prefix, beforeContext)
827
+ var afterContext = text.slice(found + quote.length, found + quote.length + suffix.length)
828
+ score += commonPrefixLen(suffix, afterContext)
829
+ if (score > bestScore) {
830
+ bestScore = score
831
+ bestStart = found
832
+ }
833
+ if (bestScore >= bestPossible) break
834
+ searchFrom = found + 1
835
+ guard += 1
836
+ }
837
+ if (bestStart < 0) return null
838
+ return rangeFromOffsets(index, bestStart, bestStart + quote.length)
839
+ } catch (error) {
840
+ return null
841
+ }
842
+ }
843
+
844
+ function ensureIndexEntry(cache, selector) {
845
+ var key = typeof selector === 'string' ? selector : ''
846
+ if (hasOwn(cache, key)) return cache[key]
847
+ var entry = null
848
+ try {
849
+ var root = resolveRoot(key)
850
+ entry = { root: root, index: buildIndex(root) }
851
+ } catch (error) {
852
+ entry = null
853
+ }
854
+ cache[key] = entry
855
+ return entry
856
+ }
857
+
858
+ function collectRanges(annotations) {
859
+ var resolved = []
860
+ var cache = {}
861
+ for (var index = 0; index < annotations.length; index += 1) {
862
+ var annotation = annotations[index]
863
+ try {
864
+ var entry = ensureIndexEntry(cache, annotation.rootSelector)
865
+ if (entry === null) continue
866
+ var range = locateAnnotationRange(annotation, entry.index)
867
+ if (range !== null) resolved.push({ annotation: annotation, range: range })
868
+ } catch (error) {
869
+ /* one bad record must not stop the others */
870
+ }
871
+ }
872
+ return resolved
873
+ }
874
+
875
+ // ------------------------------------------------------------- painting
876
+
877
+ function supportsHighlights() {
878
+ try {
879
+ if (typeof Highlight !== 'function') return false
880
+ if (typeof CSS === 'undefined' || CSS === null) return false
881
+ return CSS.highlights !== undefined && CSS.highlights !== null
882
+ } catch (error) {
883
+ return false
884
+ }
885
+ }
886
+
887
+ function setHighlightGroup(name, ranges) {
888
+ try {
889
+ if (!supportsHighlights()) return
890
+ var registry = CSS.highlights
891
+ if (ranges.length === 0) {
892
+ registry.delete(name)
893
+ return
894
+ }
895
+ var group = null
896
+ try {
897
+ group = new Highlight(...ranges)
898
+ } catch (error) {
899
+ group = null
900
+ }
901
+ if (group === null) {
902
+ group = new Highlight()
903
+ for (var index = 0; index < ranges.length; index += 1) group.add(ranges[index])
904
+ }
905
+ registry.set(name, group)
906
+ } catch (error) {
907
+ console.error('dsh-mindmark: cannot paint highlights', error)
908
+ }
909
+ }
910
+
911
+ function clearHighlights() {
912
+ try {
913
+ if (!supportsHighlights()) return
914
+ STYLES.forEach(function (style) {
915
+ CSS.highlights.delete(highlightName(style, 'pending'))
916
+ CSS.highlights.delete(highlightName(style, 'resolved'))
917
+ })
918
+ } catch (error) {
919
+ console.error('dsh-mindmark: cannot clear highlights', error)
920
+ }
921
+ }
922
+
923
+ var applyTimer = null
924
+
925
+ function paintHighlightsNow() {
926
+ try {
927
+ if (!supportsHighlights()) return
928
+ var current = getState()
929
+ var annotations = current.sessionId !== null && Array.isArray(current.annotations) ? current.annotations : []
930
+ var resolved = annotations.length === 0 ? [] : collectRanges(annotations)
931
+ var groups = {}
932
+ STYLES.forEach(function (style) {
933
+ groups[highlightName(style, 'pending')] = []
934
+ groups[highlightName(style, 'resolved')] = []
935
+ })
936
+ for (var index = 0; index < resolved.length; index += 1) {
937
+ var item = resolved[index]
938
+ var name = highlightName(item.annotation.style, item.annotation.status)
939
+ if (groups[name]) groups[name].push(item.range)
940
+ }
941
+ Object.keys(groups).forEach(function (name) {
942
+ setHighlightGroup(name, groups[name])
943
+ })
944
+ } catch (error) {
945
+ console.error('dsh-mindmark: repaint failed', error)
946
+ }
947
+ }
948
+
949
+ function cancelPaintTimer() {
950
+ if (applyTimer !== null) {
951
+ clearTimeout(applyTimer)
952
+ applyTimer = null
953
+ }
954
+ }
955
+
956
+ function schedulePaint(delay) {
957
+ try {
958
+ if (applyTimer !== null) return
959
+ var wait = typeof delay === 'number' && delay >= 0 ? delay : MUTATION_DEBOUNCE
960
+ applyTimer = setTimeout(function () {
961
+ applyTimer = null
962
+ paintHighlightsNow()
963
+ }, wait)
964
+ } catch (error) {
965
+ console.error('dsh-mindmark: cannot schedule a repaint', error)
966
+ }
967
+ }
968
+
969
+ function paintNow() {
970
+ cancelPaintTimer()
971
+ paintHighlightsNow()
972
+ }
973
+
974
+ // ----------------------------------------------- selection → record
975
+
976
+ function readLiveRange() {
977
+ var nativeSelection = null
978
+ try {
979
+ nativeSelection = typeof window.getSelection === 'function' ? window.getSelection() : null
980
+ } catch (error) {
981
+ return null
982
+ }
983
+ if (!nativeSelection || nativeSelection.rangeCount === 0 || nativeSelection.isCollapsed) return null
984
+ var text = ''
985
+ try {
986
+ text = nativeSelection.toString()
987
+ } catch (error) {
988
+ return null
989
+ }
990
+ if (typeof text !== 'string' || text.trim().length === 0 || text.length > MAX_QUOTE) return null
991
+ try {
992
+ var range = nativeSelection.getRangeAt(0)
993
+ if (!range || !range.startContainer || !range.endContainer) return null
994
+ if (isOurUiNode(range.startContainer) || isOurUiNode(range.endContainer)) return null
995
+ return range
996
+ } catch (error) {
997
+ return null
998
+ }
999
+ }
1000
+
1001
+ // The message body is the Chat view's own interaction source element (the
1002
+ // rendered Markdown of one assistant answer); the flow item above it carries
1003
+ // the node key and the turn. Only attribute names the Chat view documents
1004
+ // for plugins are consulted, and a miss simply yields an unanchored record.
1005
+ function locateMessage(range) {
1006
+ try {
1007
+ var element = elementOfNode(range.commonAncestorContainer)
1008
+ if (!element || typeof element.closest !== 'function') return null
1009
+ var body = element.closest('[data-text-interaction-source]')
1010
+ if (!body) return null
1011
+ var item = body.closest('[data-chat-node-key]')
1012
+ var key = item && typeof item.getAttribute === 'function' ? item.getAttribute('data-chat-node-key') : null
1013
+ var turnRaw = item && typeof item.getAttribute === 'function' ? item.getAttribute('data-chat-turn') : null
1014
+ var turn = turnRaw !== null && /^\d+$/.test(turnRaw) ? Number(turnRaw) : undefined
1015
+ var index = buildIndex(body)
1016
+ if (!index.text || index.text.length === 0 || index.text.length > MAX_MESSAGE_TEXT) return null
1017
+ var start = offsetOf(index, range.startContainer, range.startOffset)
1018
+ var end = offsetOf(index, range.endContainer, range.endOffset)
1019
+ if (!(end > start)) return null
1020
+ if (!key) key = 'text:' + hashText(index.text)
1021
+ return { key: clipString(key, 200), text: index.text, turn: turn, start: start, end: end }
1022
+ } catch (error) {
1023
+ return null
1024
+ }
1025
+ }
1026
+
1027
+ function hashText(text) {
1028
+ var hash = 5381
1029
+ for (var index = 0; index < text.length; index += 1) hash = ((hash << 5) + hash + text.charCodeAt(index)) | 0
1030
+ return (hash >>> 0).toString(36)
1031
+ }
1032
+
1033
+ function buildRecord(range, style) {
1034
+ try {
1035
+ var root = findRoot(range)
1036
+ var index = buildIndex(root)
1037
+ if (!index.text || index.nodes.length === 0) return null
1038
+ var start = offsetOf(index, range.startContainer, range.startOffset)
1039
+ var end = offsetOf(index, range.endContainer, range.endOffset)
1040
+ if (!(end > start)) return null
1041
+ var quote = index.text.slice(start, end)
1042
+ if (!quote || quote.trim().length === 0 || quote.length > MAX_QUOTE) return null
1043
+ var message = locateMessage(range)
1044
+ var record = {
1045
+ id: createClientId(),
1046
+ style: isStyle(style) ? style : 'highlight',
1047
+ quote: quote,
1048
+ note: '',
1049
+ prefix: index.text.slice(Math.max(0, start - CONTEXT_MAX), start),
1050
+ suffix: index.text.slice(end, Math.min(index.text.length, end + CONTEXT_MAX)),
1051
+ rootSelector: cssPath(root),
1052
+ createdAt: new Date().toISOString(),
1053
+ status: 'pending',
1054
+ }
1055
+ if (message !== null) {
1056
+ record.messageKey = message.key
1057
+ record.messageStart = message.start
1058
+ record.messageEnd = message.end
1059
+ if (typeof message.turn === 'number') record.turn = message.turn
1060
+ }
1061
+ return { record: record, message: message === null ? null : { key: message.key, text: message.text, turn: message.turn } }
1062
+ } catch (error) {
1063
+ console.error('dsh-mindmark: cannot build the annotation record', error)
1064
+ return null
1065
+ }
1066
+ }
1067
+
1068
+ function rangesIntersect(left, right) {
1069
+ try {
1070
+ if (left.compareBoundaryPoints(1, right) >= 0) return false
1071
+ if (right.compareBoundaryPoints(1, left) >= 0) return false
1072
+ return true
1073
+ } catch (error) {
1074
+ return false
1075
+ }
1076
+ }
1077
+
1078
+ function annotationsIntersecting(range) {
1079
+ var current = getState()
1080
+ var hits = []
1081
+ if (current.sessionId === null || current.annotations.length === 0) return hits
1082
+ var cache = {}
1083
+ for (var index = 0; index < current.annotations.length; index += 1) {
1084
+ var annotation = current.annotations[index]
1085
+ var entry = ensureIndexEntry(cache, annotation.rootSelector)
1086
+ if (entry === null) continue
1087
+ var annotationRange = locateAnnotationRange(annotation, entry.index)
1088
+ if (annotationRange !== null && rangesIntersect(annotationRange, range)) hits.push(annotation.id)
1089
+ }
1090
+ return hits
1091
+ }
1092
+
1093
+ // -------------------------------------------------------------- controller
1094
+
1095
+ var state = {
1096
+ sessionId: null,
1097
+ annotations: [],
1098
+ mode: 'brief',
1099
+ lessons: [],
1100
+ loading: false,
1101
+ error: null,
1102
+ panelOpen: false,
1103
+ }
1104
+ var stateListeners = new Set()
1105
+ var loadToken = 0
1106
+ var mutationQueue = Promise.resolve()
1107
+
1108
+ function getState() {
1109
+ return state
1110
+ }
1111
+
1112
+ function subscribeState(listener) {
1113
+ stateListeners.add(listener)
1114
+ return function () {
1115
+ stateListeners.delete(listener)
1116
+ }
1117
+ }
1118
+
1119
+ function publishState(patch) {
1120
+ var next = {}
1121
+ for (var key in state) next[key] = state[key]
1122
+ for (var patchKey in patch) next[patchKey] = patch[patchKey]
1123
+ state = next
1124
+ stateListeners.forEach(function (listener) {
1125
+ try {
1126
+ listener()
1127
+ } catch (error) {
1128
+ console.error('dsh-mindmark: state listener failed', error)
1129
+ }
1130
+ })
1131
+ }
1132
+
1133
+ function enqueueMutation(run) {
1134
+ mutationQueue = mutationQueue.then(run, run).catch(function (error) {
1135
+ console.error('dsh-mindmark: mutation failed', error)
1136
+ })
1137
+ return mutationQueue
1138
+ }
1139
+
1140
+ function normalizeAnnotation(raw) {
1141
+ if (!raw || typeof raw !== 'object') return null
1142
+ var id = typeof raw.id === 'string' ? raw.id : ''
1143
+ if (id.length === 0 || id.length > ID_MAX) return null
1144
+ if (!isStyle(raw.style)) return null
1145
+ var quote = typeof raw.quote === 'string' ? raw.quote : ''
1146
+ if (quote.length === 0 || quote.trim().length === 0 || quote.length > MAX_QUOTE) return null
1147
+ var record = {
1148
+ id: id,
1149
+ style: raw.style,
1150
+ quote: quote,
1151
+ note: clipString(raw.note, MAX_NOTE),
1152
+ prefix: clipString(raw.prefix, CONTEXT_MAX),
1153
+ suffix: clipString(raw.suffix, CONTEXT_MAX),
1154
+ rootSelector: clipString(raw.rootSelector, SELECTOR_MAX),
1155
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : '',
1156
+ status: raw.status === 'resolved' ? 'resolved' : 'pending',
1157
+ resolvedBy: typeof raw.resolvedBy === 'string' ? raw.resolvedBy : '',
1158
+ injections: typeof raw.injections === 'number' ? raw.injections : 0,
1159
+ }
1160
+ if (typeof raw.messageKey === 'string' && raw.messageKey.length > 0) {
1161
+ record.messageKey = raw.messageKey
1162
+ record.messageStart = raw.messageStart
1163
+ record.messageEnd = raw.messageEnd
1164
+ }
1165
+ if (typeof raw.turn === 'number') record.turn = raw.turn
1166
+ return record
1167
+ }
1168
+
1169
+ function normalizeAnnotationList(raw) {
1170
+ var list = []
1171
+ if (!Array.isArray(raw)) return list
1172
+ for (var index = 0; index < raw.length; index += 1) {
1173
+ var item = normalizeAnnotation(raw[index])
1174
+ if (item !== null) list.push(item)
1175
+ }
1176
+ list.sort(compareCreatedAt)
1177
+ return list
1178
+ }
1179
+
1180
+ function wireRecord(record) {
1181
+ var wire = {
1182
+ id: record.id,
1183
+ style: record.style,
1184
+ quote: record.quote,
1185
+ note: record.note,
1186
+ prefix: record.prefix,
1187
+ suffix: record.suffix,
1188
+ rootSelector: record.rootSelector,
1189
+ createdAt: record.createdAt,
1190
+ }
1191
+ if (typeof record.messageKey === 'string') {
1192
+ wire.messageKey = record.messageKey
1193
+ wire.messageStart = record.messageStart
1194
+ wire.messageEnd = record.messageEnd
1195
+ }
1196
+ if (typeof record.turn === 'number') wire.turn = record.turn
1197
+ return wire
1198
+ }
1199
+
1200
+ function networkFailure(cause) {
1201
+ var failure = new Error(cause && cause.message ? cause.message : 'network error')
1202
+ failure.code = 'network'
1203
+ return failure
1204
+ }
1205
+
1206
+ function requestJson(url, options) {
1207
+ var pending = null
1208
+ try {
1209
+ if (typeof fetch !== 'function') return Promise.reject(networkFailure(new Error('fetch is unavailable')))
1210
+ pending = fetch(url, options)
1211
+ } catch (failure) {
1212
+ return Promise.reject(networkFailure(failure))
1213
+ }
1214
+ if (!pending || typeof pending.then !== 'function') {
1215
+ return Promise.reject(networkFailure(new Error('fetch returned no promise')))
1216
+ }
1217
+ return pending.then(
1218
+ function (response) {
1219
+ if (!response || typeof response.text !== 'function') throw networkFailure(new Error('empty response'))
1220
+ return response.text().then(
1221
+ function (text) {
1222
+ var data = null
1223
+ if (typeof text === 'string' && text.length > 0) {
1224
+ try {
1225
+ data = JSON.parse(text)
1226
+ } catch (error) {
1227
+ data = null
1228
+ }
1229
+ }
1230
+ if (response.ok === true && data && data.ok === true) return data
1231
+ var failure = new Error('HTTP ' + String(response.status))
1232
+ failure.code = 'http'
1233
+ if (data && data.error && typeof data.error.message === 'string') failure.message = data.error.message
1234
+ throw failure
1235
+ },
1236
+ function (failure) {
1237
+ throw networkFailure(failure)
1238
+ },
1239
+ )
1240
+ },
1241
+ function (failure) {
1242
+ throw networkFailure(failure)
1243
+ },
1244
+ )
1245
+ }
1246
+
1247
+ function normalizeLessons(raw) {
1248
+ var list = []
1249
+ if (!Array.isArray(raw)) return list
1250
+ for (var index = 0; index < raw.length; index += 1) {
1251
+ var item = raw[index]
1252
+ if (item && typeof item.text === 'string' && item.text.length > 0) {
1253
+ list.push({ text: clipString(item.text, 300), date: typeof item.date === 'string' ? item.date : '' })
1254
+ }
1255
+ }
1256
+ return list
1257
+ }
1258
+
1259
+ // The composer-side slot hands us its draft setter so the panel (root
1260
+ // scope, no composer access) can prefill the distill request.
1261
+ var draftSetter = null
1262
+
1263
+ function requestDistill(prompt) {
1264
+ if (typeof draftSetter !== 'function') return false
1265
+ try {
1266
+ draftSetter(prompt)
1267
+ return true
1268
+ } catch (error) {
1269
+ console.error('dsh-mindmark: cannot prefill the composer', error)
1270
+ return false
1271
+ }
1272
+ }
1273
+
1274
+ function forgetLesson(text) {
1275
+ var sessionId = state.sessionId
1276
+ if (sessionId === null || typeof text !== 'string') return
1277
+ var previous = state.lessons
1278
+ publishState({
1279
+ lessons: previous.filter(function (item) {
1280
+ return item.text !== text
1281
+ }),
1282
+ error: null,
1283
+ })
1284
+ enqueueMutation(function () {
1285
+ return postAction({ action: 'forget-lesson', sessionId: sessionId, lessons: [text] }).then(
1286
+ function (data) {
1287
+ if (state.sessionId !== sessionId) return
1288
+ applyServerPayload(data)
1289
+ },
1290
+ function (failure) {
1291
+ if (state.sessionId !== sessionId) return
1292
+ publishState({ lessons: previous, error: failureToError(failure, 'resolve') })
1293
+ },
1294
+ )
1295
+ })
1296
+ }
1297
+
1298
+ function applyServerPayload(data, extra) {
1299
+ var patch = extra || {}
1300
+ if (Array.isArray(data.annotations)) patch.annotations = normalizeAnnotationList(data.annotations)
1301
+ if (typeof data.mode === 'string') patch.mode = normalizeMode(data.mode)
1302
+ if (Array.isArray(data.lessons)) patch.lessons = normalizeLessons(data.lessons)
1303
+ if (patch.error === undefined) patch.error = null
1304
+ publishState(patch)
1305
+ }
1306
+
1307
+ function loadSession(sessionId) {
1308
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return
1309
+ loadToken += 1
1310
+ var token = loadToken
1311
+ publishState({ loading: true, error: null })
1312
+ requestJson(ROUTE + '?sessionId=' + encodeURIComponent(sessionId), {
1313
+ method: 'GET',
1314
+ headers: { accept: 'application/json' },
1315
+ }).then(
1316
+ function (data) {
1317
+ if (token !== loadToken || state.sessionId !== sessionId) return
1318
+ applyServerPayload(data, { loading: false })
1319
+ },
1320
+ function (failure) {
1321
+ if (token !== loadToken || state.sessionId !== sessionId) return
1322
+ publishState({ loading: false, error: failureToError(failure, 'load') })
1323
+ },
1324
+ )
1325
+ }
1326
+
1327
+ function setCurrentSession(rawSessionId) {
1328
+ var sessionId = typeof rawSessionId === 'string' && rawSessionId.length > 0 ? rawSessionId : null
1329
+ if (sessionId === state.sessionId) return
1330
+ loadToken += 1
1331
+ publishState({
1332
+ sessionId: sessionId,
1333
+ annotations: [],
1334
+ mode: 'brief',
1335
+ loading: sessionId !== null,
1336
+ error: null,
1337
+ panelOpen: sessionId === null ? false : state.panelOpen,
1338
+ })
1339
+ if (sessionId !== null) loadSession(sessionId)
1340
+ }
1341
+
1342
+ function reload() {
1343
+ var sessionId = state.sessionId
1344
+ if (sessionId === null) return
1345
+ loadSession(sessionId)
1346
+ }
1347
+
1348
+ function postAction(body) {
1349
+ return requestJson(ROUTE, {
1350
+ method: 'POST',
1351
+ headers: { 'content-type': 'application/json' },
1352
+ body: JSON.stringify(body),
1353
+ })
1354
+ }
1355
+
1356
+ function addAnnotation(annotation, message) {
1357
+ var sessionId = state.sessionId
1358
+ if (sessionId === null) return
1359
+ var record = normalizeAnnotation(annotation)
1360
+ if (record === null) {
1361
+ publishState({ error: { code: 'invalid', message: '' } })
1362
+ return
1363
+ }
1364
+ loadToken += 1
1365
+ publishState({ annotations: state.annotations.concat([record]), loading: false, error: null })
1366
+ var body = { action: 'add', sessionId: sessionId, annotation: wireRecord(record) }
1367
+ if (message && typeof message.text === 'string') body.message = message
1368
+ enqueueMutation(function () {
1369
+ return postAction(body).then(
1370
+ function (data) {
1371
+ if (state.sessionId !== sessionId) return
1372
+ applyServerPayload(data)
1373
+ },
1374
+ function (failure) {
1375
+ if (state.sessionId !== sessionId) return
1376
+ publishState({
1377
+ annotations: state.annotations.filter(function (item) {
1378
+ return item.id !== record.id
1379
+ }),
1380
+ error: failureToError(failure, 'add'),
1381
+ })
1382
+ },
1383
+ )
1384
+ })
1385
+ }
1386
+
1387
+ function uniqueIds(ids) {
1388
+ var seen = {}
1389
+ var unique = []
1390
+ if (!Array.isArray(ids)) return unique
1391
+ for (var index = 0; index < ids.length; index += 1) {
1392
+ var id = ids[index]
1393
+ if (typeof id === 'string' && id.length > 0 && seen[id] !== true) {
1394
+ seen[id] = true
1395
+ unique.push(id)
1396
+ }
1397
+ }
1398
+ return unique
1399
+ }
1400
+
1401
+ function removeAnnotations(ids) {
1402
+ var sessionId = state.sessionId
1403
+ if (sessionId === null) return
1404
+ var unique = uniqueIds(ids)
1405
+ if (unique.length === 0) return
1406
+ var seen = {}
1407
+ unique.forEach(function (id) {
1408
+ seen[id] = true
1409
+ })
1410
+ var removed = state.annotations.filter(function (item) {
1411
+ return seen[item.id] === true
1412
+ })
1413
+ if (removed.length === 0) return
1414
+ loadToken += 1
1415
+ publishState({
1416
+ annotations: state.annotations.filter(function (item) {
1417
+ return seen[item.id] !== true
1418
+ }),
1419
+ loading: false,
1420
+ error: null,
1421
+ })
1422
+ enqueueMutation(function () {
1423
+ return postAction({ action: 'remove', sessionId: sessionId, ids: unique }).then(
1424
+ function (data) {
1425
+ if (state.sessionId !== sessionId) return
1426
+ applyServerPayload(data)
1427
+ },
1428
+ function (failure) {
1429
+ if (state.sessionId !== sessionId) return
1430
+ var present = {}
1431
+ state.annotations.forEach(function (item) {
1432
+ present[item.id] = true
1433
+ })
1434
+ var restored = state.annotations.concat(
1435
+ removed.filter(function (item) {
1436
+ return present[item.id] !== true
1437
+ }),
1438
+ )
1439
+ restored.sort(compareCreatedAt)
1440
+ publishState({ annotations: restored, error: failureToError(failure, 'remove') })
1441
+ },
1442
+ )
1443
+ })
1444
+ }
1445
+
1446
+ function clearAll() {
1447
+ var sessionId = state.sessionId
1448
+ if (sessionId === null) return
1449
+ var previous = state.annotations
1450
+ if (previous.length === 0) {
1451
+ publishState({ error: null })
1452
+ return
1453
+ }
1454
+ loadToken += 1
1455
+ publishState({ annotations: [], loading: false, error: null })
1456
+ enqueueMutation(function () {
1457
+ return postAction({ action: 'clear', sessionId: sessionId }).then(
1458
+ function (data) {
1459
+ if (state.sessionId !== sessionId) return
1460
+ applyServerPayload(data)
1461
+ },
1462
+ function (failure) {
1463
+ if (state.sessionId !== sessionId) return
1464
+ publishState({ annotations: previous, error: failureToError(failure, 'clear') })
1465
+ },
1466
+ )
1467
+ })
1468
+ }
1469
+
1470
+ function setStatus(ids, status) {
1471
+ var sessionId = state.sessionId
1472
+ if (sessionId === null) return
1473
+ var unique = uniqueIds(ids)
1474
+ var all = unique.length === 0
1475
+ var previous = state.annotations
1476
+ var changed = false
1477
+ var next = previous.map(function (item) {
1478
+ if (!all && unique.indexOf(item.id) < 0) return item
1479
+ if (item.status === status && status === 'resolved') return item
1480
+ if (item.status === status && status === 'pending' && item.injections === 0) return item
1481
+ changed = true
1482
+ var copy = {}
1483
+ for (var key in item) copy[key] = item[key]
1484
+ copy.status = status
1485
+ copy.resolvedBy = status === 'resolved' ? 'user' : ''
1486
+ if (status === 'pending') copy.injections = 0
1487
+ return copy
1488
+ })
1489
+ if (!changed) return
1490
+ loadToken += 1
1491
+ publishState({ annotations: next, loading: false, error: null })
1492
+ enqueueMutation(function () {
1493
+ return postAction({ action: status === 'resolved' ? 'resolve' : 'reopen', sessionId: sessionId, ids: unique }).then(
1494
+ function (data) {
1495
+ if (state.sessionId !== sessionId) return
1496
+ applyServerPayload(data)
1497
+ },
1498
+ function (failure) {
1499
+ if (state.sessionId !== sessionId) return
1500
+ publishState({ annotations: previous, error: failureToError(failure, 'resolve') })
1501
+ },
1502
+ )
1503
+ })
1504
+ }
1505
+
1506
+ function setMode(mode) {
1507
+ var sessionId = state.sessionId
1508
+ var next = normalizeMode(mode)
1509
+ if (sessionId === null || next === state.mode) return
1510
+ var previous = state.mode
1511
+ publishState({ mode: next, error: null })
1512
+ enqueueMutation(function () {
1513
+ return postAction({ action: 'set-mode', sessionId: sessionId, mode: next }).then(
1514
+ function (data) {
1515
+ if (state.sessionId !== sessionId) return
1516
+ applyServerPayload(data)
1517
+ },
1518
+ function (failure) {
1519
+ if (state.sessionId !== sessionId) return
1520
+ publishState({ mode: previous, error: failureToError(failure, 'mode') })
1521
+ },
1522
+ )
1523
+ })
1524
+ }
1525
+
1526
+ function setPanelOpen(open) {
1527
+ var next = open === true
1528
+ if (state.panelOpen === next) return
1529
+ publishState({ panelOpen: next })
1530
+ if (next && state.sessionId !== null) reload()
1531
+ }
1532
+
1533
+ function togglePanel() {
1534
+ if (state.sessionId === null && state.panelOpen !== true) return
1535
+ setPanelOpen(state.panelOpen !== true)
1536
+ }
1537
+
1538
+ var controller = {
1539
+ getState: getState,
1540
+ subscribe: subscribeState,
1541
+ setCurrentSession: setCurrentSession,
1542
+ reload: reload,
1543
+ addAnnotation: addAnnotation,
1544
+ removeAnnotations: removeAnnotations,
1545
+ clearAll: clearAll,
1546
+ resolve: function (ids) {
1547
+ setStatus(ids, 'resolved')
1548
+ },
1549
+ reopen: function (ids) {
1550
+ setStatus(ids, 'pending')
1551
+ },
1552
+ setMode: setMode,
1553
+ forgetLesson: forgetLesson,
1554
+ requestDistill: requestDistill,
1555
+ togglePanel: togglePanel,
1556
+ setPanelOpen: setPanelOpen,
1557
+ }
1558
+
1559
+ function useControllerState() {
1560
+ return useSyncExternalStore(subscribeState, getState, getState)
1561
+ }
1562
+
1563
+ function pendingCount(current) {
1564
+ var count = 0
1565
+ for (var index = 0; index < current.annotations.length; index += 1) {
1566
+ if (current.annotations[index].status !== 'resolved') count += 1
1567
+ }
1568
+ return count
1569
+ }
1570
+
1571
+ // ------------------------------------------------------------- components
1572
+
1573
+ function keepSelection(event) {
1574
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1575
+ }
1576
+
1577
+ function ToolButton(props) {
1578
+ return h(
1579
+ 'button',
1580
+ {
1581
+ type: 'button',
1582
+ className: 'dsa-tool-btn',
1583
+ title: props.title,
1584
+ 'aria-label': props.label,
1585
+ onPointerDown: keepSelection,
1586
+ onMouseDown: keepSelection,
1587
+ onClick: props.onClick,
1588
+ },
1589
+ props.glyph ? h('span', { className: 'dsa-tool-glyph dsa-tool-glyph-' + props.glyph, 'aria-hidden': 'true' }) : null,
1590
+ h('span', null, props.label),
1591
+ )
1592
+ }
1593
+
1594
+ // The action bar the Chat view mounts next to a selection. `props` carry the
1595
+ // area-local surface actions (dismiss / readText / clearSelection) plus the
1596
+ // standard session seat (sessionId, inputActions).
1597
+ function SelectionActions(props) {
1598
+ var t = props.t
1599
+ var sessionId = typeof props.sessionId === 'string' ? props.sessionId : null
1600
+ var current = useControllerState()
1601
+ var noteState = useState(null)
1602
+ var draft = noteState[0]
1603
+ var setDraft = noteState[1]
1604
+ var inputRef = useRef(null)
1605
+
1606
+ useEffect(
1607
+ function () {
1608
+ if (sessionId !== null && current.sessionId !== sessionId) controller.setCurrentSession(sessionId)
1609
+ },
1610
+ [sessionId, current.sessionId],
1611
+ )
1612
+ useEffect(
1613
+ function () {
1614
+ if (draft !== null && inputRef.current && typeof inputRef.current.focus === 'function') {
1615
+ try {
1616
+ inputRef.current.focus()
1617
+ } catch (error) {
1618
+ /* focus is best effort */
1619
+ }
1620
+ }
1621
+ },
1622
+ [draft],
1623
+ )
1624
+
1625
+ function dismiss() {
1626
+ if (typeof props.dismiss === 'function') props.dismiss()
1627
+ }
1628
+
1629
+ function finish() {
1630
+ if (typeof props.clearSelection === 'function') props.clearSelection()
1631
+ dismiss()
1632
+ }
1633
+
1634
+ function mark(style) {
1635
+ var range = readLiveRange()
1636
+ if (range === null) {
1637
+ dismiss()
1638
+ return
1639
+ }
1640
+ var built = buildRecord(range, style)
1641
+ if (built === null) {
1642
+ dismiss()
1643
+ return
1644
+ }
1645
+ if (NOTE_STYLES[style] === true) {
1646
+ setDraft({ style: style, built: built, text: '' })
1647
+ return
1648
+ }
1649
+ controller.addAnnotation(built.record, built.message)
1650
+ paintNow()
1651
+ finish()
1652
+ }
1653
+
1654
+ function unmark() {
1655
+ var range = readLiveRange()
1656
+ if (range === null) {
1657
+ dismiss()
1658
+ return
1659
+ }
1660
+ var hits = annotationsIntersecting(range)
1661
+ if (hits.length > 0) {
1662
+ controller.removeAnnotations(hits)
1663
+ paintNow()
1664
+ }
1665
+ finish()
1666
+ }
1667
+
1668
+ function quote() {
1669
+ var text = typeof props.readText === 'function' ? props.readText() : null
1670
+ if (text === null) {
1671
+ dismiss()
1672
+ return
1673
+ }
1674
+ var actions = props.inputActions
1675
+ if (actions && typeof actions.insertQuote === 'function' && actions.insertQuote(text) === false) return
1676
+ finish()
1677
+ }
1678
+
1679
+ function submitDraft() {
1680
+ if (draft === null) return
1681
+ var text = String(draft.text || '').trim()
1682
+ if (text.length === 0 || text.length > MAX_NOTE) return
1683
+ draft.built.record.note = text
1684
+ controller.addAnnotation(draft.built.record, draft.built.message)
1685
+ setDraft(null)
1686
+ paintNow()
1687
+ finish()
1688
+ }
1689
+
1690
+ if (draft !== null) {
1691
+ var isRewrite = draft.style === 'rewrite'
1692
+ return h(
1693
+ 'div',
1694
+ { className: 'dsa-toolbar is-note', role: 'dialog', 'aria-label': t(draft.style), 'data-dsh-mindmark-ui': '1' },
1695
+ h(
1696
+ 'div',
1697
+ { className: 'dsa-note-head' },
1698
+ h('span', { className: 'dsa-tool-glyph dsa-tool-glyph-' + draft.style, 'aria-hidden': 'true' }),
1699
+ h('span', null, t(draft.style)),
1700
+ ),
1701
+ h('p', { className: 'dsa-note-quote' }, previewQuote(draft.built.record.quote, 160)),
1702
+ h('textarea', {
1703
+ ref: inputRef,
1704
+ className: 'dsa-note-input',
1705
+ placeholder: t(isRewrite ? 'rewritePlaceholder' : 'commentPlaceholder'),
1706
+ value: draft.text,
1707
+ maxLength: MAX_NOTE,
1708
+ rows: 3,
1709
+ onChange: function (event) {
1710
+ setDraft({ style: draft.style, built: draft.built, text: event.target.value })
1711
+ },
1712
+ onKeyDown: function (event) {
1713
+ if (event.key === 'Escape') {
1714
+ event.stopPropagation()
1715
+ setDraft(null)
1716
+ dismiss()
1717
+ } else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
1718
+ event.preventDefault()
1719
+ submitDraft()
1720
+ }
1721
+ },
1722
+ }),
1723
+ h(
1724
+ 'div',
1725
+ { className: 'dsa-note-actions' },
1726
+ h(
1727
+ 'button',
1728
+ {
1729
+ type: 'button',
1730
+ className: 'dsa-btn',
1731
+ onClick: function () {
1732
+ setDraft(null)
1733
+ dismiss()
1734
+ },
1735
+ },
1736
+ t('cancel'),
1737
+ ),
1738
+ h(
1739
+ 'button',
1740
+ { type: 'button', className: 'dsa-btn is-primary', disabled: String(draft.text || '').trim().length === 0, onClick: submitDraft },
1741
+ t('confirm'),
1742
+ ),
1743
+ ),
1744
+ )
1745
+ }
1746
+
1747
+ var hasQuote = props.inputActions && typeof props.inputActions.insertQuote === 'function'
1748
+ return h(
1749
+ 'div',
1750
+ { className: 'dsa-toolbar', role: 'toolbar', 'aria-label': t('toolbarLabel'), 'data-dsh-mindmark-ui': '1' },
1751
+ hasQuote ? h(ToolButton, { label: t('quote'), title: t('hint.quote'), glyph: 'quote', onClick: quote }) : null,
1752
+ hasQuote ? h('span', { className: 'dsa-tool-divider', 'aria-hidden': 'true' }) : null,
1753
+ STYLES.map(function (style) {
1754
+ return h(ToolButton, {
1755
+ key: style,
1756
+ label: t(style),
1757
+ title: t('hint.' + style),
1758
+ glyph: style,
1759
+ onClick: function () {
1760
+ mark(style)
1761
+ },
1762
+ })
1763
+ }),
1764
+ h('span', { className: 'dsa-tool-divider', 'aria-hidden': 'true' }),
1765
+ h(ToolButton, { label: t('unmark'), title: t('unmark'), onClick: unmark }),
1766
+ h(
1767
+ 'button',
1768
+ {
1769
+ type: 'button',
1770
+ className: 'dsa-tool-close',
1771
+ title: t('close'),
1772
+ 'aria-label': t('close'),
1773
+ onPointerDown: keepSelection,
1774
+ onMouseDown: keepSelection,
1775
+ onClick: dismiss,
1776
+ },
1777
+ '×',
1778
+ ),
1779
+ )
1780
+ }
1781
+
1782
+ function ModeSwitch(props) {
1783
+ var t = props.t
1784
+ var sessionId = typeof props.sessionId === 'string' && props.sessionId.length > 0 ? props.sessionId : null
1785
+ var current = useControllerState()
1786
+ useEffect(
1787
+ function () {
1788
+ if (sessionId !== null && current.sessionId !== sessionId) controller.setCurrentSession(sessionId)
1789
+ },
1790
+ [sessionId, current.sessionId],
1791
+ )
1792
+ var inputActions = props.inputActions
1793
+ useEffect(
1794
+ function () {
1795
+ if (inputActions && typeof inputActions.setDraft === 'function') {
1796
+ draftSetter = function (text) {
1797
+ inputActions.setDraft(text)
1798
+ }
1799
+ return function () {
1800
+ draftSetter = null
1801
+ }
1802
+ }
1803
+ return undefined
1804
+ },
1805
+ [inputActions],
1806
+ )
1807
+ var isCurrent = sessionId !== null && current.sessionId === sessionId
1808
+ var pending = isCurrent ? pendingCount(current) : 0
1809
+ var mode = isCurrent ? current.mode : 'brief'
1810
+ var locked = props.locked === true
1811
+ return h(
1812
+ 'div',
1813
+ { className: 'dsa-mode', 'data-dsh-mindmark-ui': '1', title: t('modeTitle'), role: 'group', 'aria-label': t('modeLabel') },
1814
+ h('span', { className: 'dsa-mode-label' }, h(MarkerIcon, { size: 13 }), h('span', null, t('modeLabel'))),
1815
+ h(
1816
+ 'span',
1817
+ { className: 'dsa-mode-seg' },
1818
+ MODES.map(function (option) {
1819
+ return h(
1820
+ 'button',
1821
+ {
1822
+ key: option,
1823
+ type: 'button',
1824
+ className: 'dsa-mode-btn' + (mode === option ? ' is-on' : ''),
1825
+ title: t(option === 'full' ? 'modeFullHint' : 'modeBriefHint'),
1826
+ 'aria-pressed': mode === option ? 'true' : 'false',
1827
+ disabled: locked || !isCurrent,
1828
+ onClick: function () {
1829
+ controller.setMode(option)
1830
+ },
1831
+ },
1832
+ t(option === 'full' ? 'modeFull' : 'modeBrief'),
1833
+ )
1834
+ }),
1835
+ ),
1836
+ pending > 0 ? h('span', { className: 'dsa-mode-badge', title: t('pendingCount', { count: pending }) }, String(pending)) : null,
1837
+ )
1838
+ }
1839
+
1840
+ function AnnotationItem(props) {
1841
+ var t = props.t
1842
+ var annotation = props.annotation
1843
+ var resolved = annotation.status === 'resolved'
1844
+ var time = formatTimestamp(annotation.createdAt)
1845
+ var by = annotation.resolvedBy === 'model' ? t('byModel') : annotation.resolvedBy === 'cap' ? t('byCap') : annotation.resolvedBy === 'user' ? t('byUser') : ''
1846
+ var note = null
1847
+ if (annotation.note) {
1848
+ note = h('p', { className: 'dsa-note' }, h('b', null, t(annotation.style === 'rewrite' ? 'rewriteLabel' : 'noteLabel')), annotation.note)
1849
+ }
1850
+ return h(
1851
+ 'div',
1852
+ { className: 'dsa-item' + (resolved ? ' is-resolved' : '') },
1853
+ h('span', { className: 'dsa-chip dsa-chip-' + annotation.style }, t(annotation.style)),
1854
+ h(
1855
+ 'div',
1856
+ { className: 'dsa-item-main' },
1857
+ h('p', { className: 'dsa-quote' }, previewQuote(annotation.quote)),
1858
+ note,
1859
+ h(
1860
+ 'p',
1861
+ { className: 'dsa-meta' },
1862
+ h('span', { className: 'dsa-status' + (resolved ? '' : ' is-pending') }, resolved ? t('statusResolved') : t('statusPending')),
1863
+ resolved && by ? h('span', null, by) : null,
1864
+ time === '' ? null : h('span', null, time),
1865
+ ),
1866
+ ),
1867
+ h(
1868
+ 'div',
1869
+ { className: 'dsa-item-actions' },
1870
+ h(
1871
+ 'button',
1872
+ {
1873
+ type: 'button',
1874
+ className: 'dsa-item-btn',
1875
+ title: resolved ? t('reopen') : t('resolve'),
1876
+ 'aria-label': resolved ? t('reopen') : t('resolve'),
1877
+ onClick: function () {
1878
+ if (resolved) controller.reopen([annotation.id])
1879
+ else controller.resolve([annotation.id])
1880
+ paintNow()
1881
+ },
1882
+ },
1883
+ resolved ? '↺' : '✓',
1884
+ ),
1885
+ h(
1886
+ 'button',
1887
+ {
1888
+ type: 'button',
1889
+ className: 'dsa-item-btn is-del',
1890
+ title: t('delete'),
1891
+ 'aria-label': t('delete'),
1892
+ onClick: function () {
1893
+ controller.removeAnnotations([annotation.id])
1894
+ paintNow()
1895
+ },
1896
+ },
1897
+ '×',
1898
+ ),
1899
+ ),
1900
+ )
1901
+ }
1902
+
1903
+ function AnnotationPanel(props) {
1904
+ var t = props.t
1905
+ var current = props.state
1906
+ var canHighlight = props.canHighlight
1907
+ var annotations = Array.isArray(current.annotations) ? current.annotations : []
1908
+ var lessons = Array.isArray(current.lessons) ? current.lessons : []
1909
+ var pending = pendingCount(current)
1910
+ var loading = current.loading === true
1911
+ var items = annotations
1912
+ .slice()
1913
+ .reverse()
1914
+ .map(function (annotation) {
1915
+ return h(AnnotationItem, { key: annotation.id, t: t, annotation: annotation })
1916
+ })
1917
+ var body =
1918
+ loading && annotations.length === 0
1919
+ ? h('p', { className: 'dsa-loading' }, t('loading'))
1920
+ : annotations.length === 0
1921
+ ? h('p', { className: 'dsa-empty' }, t('empty'))
1922
+ : items
1923
+ return h(
1924
+ 'div',
1925
+ { className: 'dsa-panel', role: 'dialog', 'aria-label': t('panelTitle'), 'aria-labelledby': PANEL_TITLE_ID },
1926
+ h(
1927
+ 'div',
1928
+ { className: 'dsa-panel-head' },
1929
+ h('span', { className: 'dsa-panel-title', id: PANEL_TITLE_ID }, t('panelTitle')),
1930
+ annotations.length > 0 ? h('span', { className: 'dsa-panel-count' }, t('pendingCount', { count: pending })) : null,
1931
+ h('span', { className: 'dsa-spacer', 'aria-hidden': 'true' }),
1932
+ h(
1933
+ 'button',
1934
+ {
1935
+ type: 'button',
1936
+ className: 'dsa-panel-close',
1937
+ title: t('close'),
1938
+ 'aria-label': t('close'),
1939
+ onClick: function () {
1940
+ controller.setPanelOpen(false)
1941
+ },
1942
+ },
1943
+ '×',
1944
+ ),
1945
+ ),
1946
+ canHighlight ? null : h('p', { className: 'dsa-warning', role: 'status' }, t('warning')),
1947
+ current.error ? h('p', { className: 'dsa-error', role: 'alert' }, errorText(t, current.error)) : null,
1948
+ h('div', { className: 'dsa-panel-body' }, body),
1949
+ h(
1950
+ 'div',
1951
+ { className: 'dsa-lessons' },
1952
+ h('p', { className: 'dsa-lessons-title' }, t('lessonsTitle') + (lessons.length > 0 ? ' · ' + lessons.length : '')),
1953
+ lessons.length === 0
1954
+ ? h('p', { className: 'dsa-lessons-empty' }, t('lessonsEmpty'))
1955
+ : lessons.map(function (lesson, index) {
1956
+ return h(
1957
+ 'div',
1958
+ { className: 'dsa-lesson', key: lesson.text + index },
1959
+ h('span', null, lesson.text),
1960
+ lesson.date ? h('small', null, lesson.date) : null,
1961
+ h(
1962
+ 'button',
1963
+ {
1964
+ type: 'button',
1965
+ className: 'dsa-item-btn is-del',
1966
+ title: t('forget'),
1967
+ 'aria-label': t('forget'),
1968
+ onClick: function () {
1969
+ controller.forgetLesson(lesson.text)
1970
+ },
1971
+ },
1972
+ '×',
1973
+ ),
1974
+ )
1975
+ }),
1976
+ ),
1977
+ h(
1978
+ 'div',
1979
+ { className: 'dsa-panel-foot' },
1980
+ h('p', { className: 'dsa-hint' }, t('footerHint')),
1981
+ h(
1982
+ 'button',
1983
+ {
1984
+ type: 'button',
1985
+ className: 'dsa-btn is-primary',
1986
+ title: t('distillHint'),
1987
+ disabled: annotations.length === 0,
1988
+ onClick: function () {
1989
+ if (controller.requestDistill(t('distillPrompt'))) controller.setPanelOpen(false)
1990
+ },
1991
+ },
1992
+ t('distill'),
1993
+ ),
1994
+ h(
1995
+ 'button',
1996
+ {
1997
+ type: 'button',
1998
+ className: 'dsa-btn',
1999
+ disabled: pending === 0,
2000
+ onClick: function () {
2001
+ controller.resolve([])
2002
+ paintNow()
2003
+ },
2004
+ },
2005
+ t('resolveAll'),
2006
+ ),
2007
+ h(
2008
+ 'button',
2009
+ {
2010
+ type: 'button',
2011
+ className: 'dsa-btn',
2012
+ disabled: annotations.length === 0,
2013
+ onClick: function () {
2014
+ controller.clearAll()
2015
+ paintNow()
2016
+ },
2017
+ },
2018
+ t('clearAll'),
2019
+ ),
2020
+ ),
2021
+ )
2022
+ }
2023
+
2024
+ function AnnotationOverlay(props) {
2025
+ var t = props.t
2026
+ var current = useControllerState()
2027
+ if (!current.panelOpen) return null
2028
+ return h(
2029
+ 'div',
2030
+ { className: 'dsa-layer', 'data-dsh-mindmark-ui': '1' },
2031
+ h(AnnotationPanel, { t: t, state: current, canHighlight: supportsHighlights() }),
2032
+ )
2033
+ }
2034
+
2035
+ function AnnotationHeader(props) {
2036
+ var t = props.t
2037
+ var sessionId = typeof props.sessionId === 'string' && props.sessionId.length > 0 ? props.sessionId : null
2038
+ var current = useControllerState()
2039
+ useEffect(
2040
+ function () {
2041
+ controller.setCurrentSession(sessionId)
2042
+ return function () {
2043
+ controller.setCurrentSession(null)
2044
+ }
2045
+ },
2046
+ [sessionId],
2047
+ )
2048
+ var isCurrent = sessionId !== null && current.sessionId === sessionId
2049
+ var count = isCurrent ? pendingCount(current) : 0
2050
+ var panelOpen = isCurrent && current.panelOpen === true
2051
+ var title = count > 0 ? t('headerTitle', { count: count }) : t('headerLabel')
2052
+ return h(
2053
+ 'button',
2054
+ {
2055
+ type: 'button',
2056
+ 'data-dsh-mindmark-ui': '1',
2057
+ className: 'dsa-header-btn' + (panelOpen ? ' is-active' : ''),
2058
+ title: title,
2059
+ 'aria-label': title,
2060
+ 'aria-expanded': panelOpen ? 'true' : 'false',
2061
+ onClick: function () {
2062
+ controller.togglePanel()
2063
+ },
2064
+ },
2065
+ h(MarkerIcon, { size: 16 }),
2066
+ count > 0 ? h('span', { className: 'dsa-header-badge', 'aria-hidden': 'true' }, String(count)) : null,
2067
+ )
2068
+ }
2069
+
2070
+ // ---------------------------------------------------------------- runtime
2071
+
2072
+ function addListener(target, type, handler, capture) {
2073
+ var useCapture = capture === true
2074
+ try {
2075
+ target.addEventListener(type, handler, useCapture)
2076
+ } catch (error) {
2077
+ console.error('dsh-mindmark: cannot listen for ' + type, error)
2078
+ }
2079
+ return function () {
2080
+ try {
2081
+ target.removeEventListener(type, handler, useCapture)
2082
+ } catch (error) {
2083
+ console.error('dsh-mindmark: cannot stop listening for ' + type, error)
2084
+ }
2085
+ }
2086
+ }
2087
+
2088
+ function observeMutations(target, handler) {
2089
+ try {
2090
+ if (typeof MutationObserver !== 'function' || !target || typeof target.nodeType !== 'number') return function () {}
2091
+ var observer = new MutationObserver(handler)
2092
+ observer.observe(target, { childList: true, subtree: true, characterData: true })
2093
+ return function () {
2094
+ try {
2095
+ observer.disconnect()
2096
+ } catch (error) {
2097
+ console.error('dsh-mindmark: cannot disconnect the mutation observer', error)
2098
+ }
2099
+ }
2100
+ } catch (error) {
2101
+ console.error('dsh-mindmark: cannot observe the DOM', error)
2102
+ return function () {}
2103
+ }
2104
+ }
2105
+
2106
+ // Re-anchoring plumbing only: the Chat view owns selection gestures now.
2107
+ function installRuntime() {
2108
+ var disposers = []
2109
+ var disposed = false
2110
+ var watchedSessionId = getState().sessionId
2111
+ var watchedAnnotations = getState().annotations
2112
+
2113
+ function onScrollOrResize() {
2114
+ if (disposed) return
2115
+ schedulePaint(MUTATION_DEBOUNCE)
2116
+ }
2117
+
2118
+ function onKeyDown(event) {
2119
+ if (disposed) return
2120
+ if (!event || (event.key !== 'Escape' && event.key !== 'Esc')) return
2121
+ if (getState().panelOpen === true && !isOurUiNode(event.target)) controller.setPanelOpen(false)
2122
+ }
2123
+
2124
+ function onMutations(mutations) {
2125
+ if (disposed) return
2126
+ try {
2127
+ for (var index = 0; index < mutations.length; index += 1) {
2128
+ if (!isOurUiNode(mutations[index].target)) {
2129
+ schedulePaint(MUTATION_DEBOUNCE)
2130
+ return
2131
+ }
2132
+ }
2133
+ } catch (error) {
2134
+ console.error('dsh-mindmark: mutation handling failed', error)
2135
+ }
2136
+ }
2137
+
2138
+ function onControllerChange() {
2139
+ if (disposed) return
2140
+ var current = getState()
2141
+ if (current.sessionId !== watchedSessionId || current.annotations !== watchedAnnotations) {
2142
+ watchedSessionId = current.sessionId
2143
+ watchedAnnotations = current.annotations
2144
+ schedulePaint(STATE_REPAINT_DELAY)
2145
+ }
2146
+ }
2147
+
2148
+ if (typeof document !== 'undefined') {
2149
+ disposers.push(addListener(document, 'keydown', onKeyDown, true))
2150
+ disposers.push(addListener(document, 'scroll', onScrollOrResize, true))
2151
+ if (typeof window !== 'undefined') disposers.push(addListener(window, 'resize', onScrollOrResize, false))
2152
+ if (document.body) disposers.push(observeMutations(document.body, onMutations))
2153
+ }
2154
+ disposers.push(subscribeState(onControllerChange))
2155
+
2156
+ return function () {
2157
+ disposed = true
2158
+ cancelPaintTimer()
2159
+ for (var index = 0; index < disposers.length; index += 1) {
2160
+ try {
2161
+ disposers[index]()
2162
+ } catch (error) {
2163
+ console.error('dsh-mindmark: disposer failed', error)
2164
+ }
2165
+ }
2166
+ disposers.length = 0
2167
+ clearHighlights()
2168
+ }
2169
+ }
2170
+
2171
+ function installStyles() {
2172
+ if (typeof document === 'undefined') return function () {}
2173
+ var tag = document.createElement('style')
2174
+ tag.setAttribute('data-plugin-css', CSS_ID)
2175
+ tag.textContent = CSS_TEXT
2176
+ var mount = document.head || document.documentElement
2177
+ if (!mount) return function () {}
2178
+ mount.appendChild(tag)
2179
+ return function () {
2180
+ if (tag.parentNode !== null) tag.parentNode.removeChild(tag)
2181
+ }
2182
+ }
2183
+
2184
+ function injectSlot(slots, name, options, component) {
2185
+ try {
2186
+ slots.inject(name, function () {
2187
+ return slots.register(options, component)
2188
+ })
2189
+ } catch (error) {
2190
+ console.error('dsh-mindmark: cannot register into ' + name, error)
2191
+ }
2192
+ }
2193
+
2194
+ function getService(ctx, key) {
2195
+ try {
2196
+ if (ctx && typeof ctx.get === 'function') {
2197
+ var found = ctx.get(key)
2198
+ if (found) return found
2199
+ }
2200
+ } catch (error) {
2201
+ /* fall through */
2202
+ }
2203
+ try {
2204
+ return ctx ? ctx[key] : null
2205
+ } catch (error) {
2206
+ return null
2207
+ }
2208
+ }
2209
+
2210
+ // ------------------------------------------------------------------ plugin
2211
+
2212
+ function apply(ctx) {
2213
+ var locale = getService(ctx, 'locale')
2214
+ if (locale && typeof locale.getSnapshot === 'function' && typeof locale.subscribe === 'function') {
2215
+ localeService = locale
2216
+ }
2217
+
2218
+ try {
2219
+ if (ctx && typeof ctx.effect === 'function') {
2220
+ ctx.effect(installStyles, 'dsh-mindmark: styles')
2221
+ ctx.effect(installRuntime, 'dsh-mindmark: re-anchoring runtime')
2222
+ } else {
2223
+ installStyles()
2224
+ installRuntime()
2225
+ }
2226
+ } catch (error) {
2227
+ console.error('dsh-mindmark: cannot install the client runtime', error)
2228
+ }
2229
+
2230
+ var slots = getService(ctx, 'slots')
2231
+ if (!slots || typeof slots.inject !== 'function' || typeof slots.register !== 'function') {
2232
+ console.error('dsh-mindmark: the slots service is unavailable; the client half cannot render')
2233
+ return
2234
+ }
2235
+
2236
+ var actions = WithTranslate(SelectionActions)
2237
+ // Take over the Quote plugin's selection surface (it still admits the
2238
+ // gesture and we keep Quote as the first action) …
2239
+ injectSlot(
2240
+ slots,
2241
+ 'conversation.chat.text-interaction',
2242
+ { name: 'conversation.chat.text-interaction', key: 'quote', priority: -10 },
2243
+ actions,
2244
+ )
2245
+ // … and own a surface of our own for hosts without the Quote plugin.
2246
+ injectSlot(
2247
+ slots,
2248
+ 'conversation.chat.text-interaction',
2249
+ { name: 'conversation.chat.text-interaction', key: SURFACE_KEY },
2250
+ actions,
2251
+ )
2252
+ var conversation = getService(ctx, 'uiConversation')
2253
+ if (conversation && conversation.interactions && typeof conversation.interactions.register === 'function') {
2254
+ try {
2255
+ ctx.effect(
2256
+ function () {
2257
+ return conversation.interactions.register({
2258
+ id: SURFACE_KEY,
2259
+ onInteraction: function (request) {
2260
+ if (request.trigger !== 'selection' || request.readText() === null) return
2261
+ request.open()
2262
+ },
2263
+ })
2264
+ },
2265
+ 'dsh-mindmark: selection interaction',
2266
+ )
2267
+ } catch (error) {
2268
+ console.error('dsh-mindmark: cannot register the selection interaction', error)
2269
+ }
2270
+ }
2271
+
2272
+ injectSlot(
2273
+ slots,
2274
+ 'conversation.input.left',
2275
+ { name: 'conversation.input.left', id: 'dsh-mindmark.mode', order: 60 },
2276
+ WithTranslate(ModeSwitch),
2277
+ )
2278
+ injectSlot(
2279
+ slots,
2280
+ 'conversation.session.header.utilities',
2281
+ { name: 'conversation.session.header.utilities', id: 'dsh-mindmark', order: 40 },
2282
+ WithTranslate(AnnotationHeader),
2283
+ )
2284
+ injectSlot(
2285
+ slots,
2286
+ 'shell.overlay',
2287
+ { name: 'shell.overlay', id: 'dsh-mindmark.overlay', order: 40 },
2288
+ WithTranslate(AnnotationOverlay),
2289
+ )
2290
+ }
2291
+
2292
+ exports.apply = apply
2293
+ exports.inject = ['slots']
2294
+ return module.exports
2295
+ },
2296
+ })