dsh-annotate-upper 0.0.0-stage → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/overlay.js ADDED
@@ -0,0 +1,1601 @@
1
+ // Generated by build.mjs — edit src/overlay.js, src/i18n.js and src/theme.js instead.
2
+ ;(function () {
3
+ /**
4
+ * dsh-annotate — UI message catalog.
5
+ *
6
+ * Deliberately not an ES module: build.mjs prepends this file to the client
7
+ * bundle and wraps it around the injected overlay, and neither is loaded through
8
+ * a module system. Both call `dsaI18n(...)` and get back `{ t, lang, set,
9
+ * toggle, detect }`.
10
+ *
11
+ * Two rules when adding a string:
12
+ * 1. Add the key to BOTH languages below.
13
+ * 2. Call `t('key')` at the use site — never inline a literal.
14
+ * `t` falls back to English and then to the key itself, so a missing
15
+ * translation shows up as a visible key rather than an empty element.
16
+ *
17
+ * Placeholders are `{name}` and are substituted by `t(key, { name: value })`.
18
+ */
19
+ function dsaI18n(preferred) {
20
+ var CATALOG = {
21
+ en: {
22
+ // ---- annotation block sent to the model ------------------------------
23
+ 'payload.head': 'Page annotations · {page} ({count})',
24
+ 'payload.locator': ' Element: ',
25
+ 'payload.selectorAmbiguous': ' (matches {count}; verify target)',
26
+ 'payload.selectorNotFound': ' (no match; verify target)',
27
+ 'payload.selectorInvalid': ' (invalid selector; verify target)',
28
+ 'payload.selectorUnknown': ' (match unverified; verify target)',
29
+ 'payload.selectorMissing': '(no selector; verify target)',
30
+ 'payload.viewport': 'viewport {w}×{h}',
31
+ 'payload.verify': ' Verify: ',
32
+ 'payload.attached': '{count} attached',
33
+ 'payload.removeOne': 'Remove this block from the composer',
34
+ 'payload.removeAll': 'Remove all',
35
+ 'zone.topLeft': 'top left',
36
+ 'zone.topCenter': 'top center',
37
+ 'zone.topRight': 'top right',
38
+ 'zone.middleLeft': 'middle left',
39
+ 'zone.middleCenter': 'center',
40
+ 'zone.middleRight': 'middle right',
41
+ 'zone.bottomLeft': 'bottom left',
42
+ 'zone.bottomCenter': 'bottom center',
43
+ 'zone.bottomRight': 'bottom right',
44
+
45
+ // ---- injected overlay ------------------------------------------------
46
+ 'overlay.saveFailed': 'Annotations cannot be saved in this browser. Attach them to the composer before you navigate away.',
47
+ 'overlay.viewPin': 'View annotation {n}: {comment}',
48
+ 'overlay.viewTitle': 'Annotation',
49
+ 'overlay.editTitle': 'Edit annotation',
50
+ 'overlay.commentLabel': 'Annotation comment',
51
+ 'overlay.details': 'Element details',
52
+ 'overlay.editHint': 'Click the comment to edit',
53
+ 'overlay.cancel': 'Cancel',
54
+ 'overlay.finishDraft': 'Save or discard the unfinished annotation before editing another one.',
55
+ 'page.more': 'More tools',
56
+ 'page.sendOptions': 'Submission options',
57
+ 'page.batch': 'Pending annotations',
58
+ 'page.batchCount': '{count} comments',
59
+ 'page.draft': 'Draft',
60
+ 'page.resumeDraft': 'Resume annotation draft',
61
+ 'page.discardDraft': 'Discard annotation draft',
62
+ 'page.view': 'View annotation',
63
+ 'page.pickHint': 'Select an element · Esc to leave',
64
+ 'overlay.close': 'Close',
65
+ 'overlay.placeholder': 'What should change here?',
66
+ 'overlay.hint': 'Enter to save',
67
+ 'overlay.save': 'Save',
68
+
69
+ // ---- panel: entry points --------------------------------------------
70
+ 'panel.tabTitle': 'Annotations',
71
+ 'panel.tabDescription': 'Pick an element, leave a note.',
72
+ 'panel.noSession': 'Choose a workspace and open a conversation first, then use UI annotations.',
73
+ 'panel.language': 'Language',
74
+ 'panel.languageSwitch': 'Switch to {lang}',
75
+
76
+ // ---- panel: list face -----------------------------------------------
77
+ 'list.detecting': 'Scanning for local services…',
78
+ 'list.detected': '{count} local services found',
79
+ 'list.none': 'No local services found',
80
+ 'list.redetect': 'Scan again',
81
+ 'list.open': 'Open →',
82
+ 'list.project': 'This project',
83
+ 'list.declared': 'Configured port',
84
+ 'list.filesHeader': 'Static pages in this project ({count})',
85
+ 'list.emptyHint': 'No local web server is running ({count} ports scanned). Start one, then refresh:',
86
+ 'list.copy': 'Copy',
87
+ 'list.copied': 'Copied: {text}',
88
+ 'list.autoRefresh': 'Checked every 5 seconds. You can also type a port below to open it directly.',
89
+ 'list.placeholder': '5173 or localhost:3000',
90
+ 'list.addressLabel': 'Local service address',
91
+ 'list.openButton': 'Open',
92
+ 'list.helpHeader': 'Annotate inside the preview',
93
+ 'list.helpPicking': 'Press Mark in the toolbar, then click an element in the page and write a note. Enter saves it so you can select the next element.',
94
+ 'list.helpEscape': 'Press Esc or Mark again to leave annotation mode.',
95
+ 'list.helpCmdClick': '⌘/Ctrl+click an element = save it and send immediately.',
96
+ 'list.helpSendHeader': 'The list and sending',
97
+ 'list.helpSendList': 'The comment count opens a compact list. Select a comment to view it, then click its text to edit.',
98
+ 'list.helpSendActions': '“Send annotations” sends only the annotations; “Add to composer” combines them with your draft so you can add context. Annotations survive a failed send.',
99
+
100
+ // ---- panel: page face -----------------------------------------------
101
+ 'page.back': 'Back',
102
+ 'page.forward': 'Forward',
103
+ 'page.reload': 'Reload',
104
+ 'page.addressPlaceholder': 'Address',
105
+ 'page.widthLabel': 'Preview width',
106
+ 'page.widthFit': 'Fit',
107
+ 'page.widthMobile': 'Mobile',
108
+ 'page.listToggleLabel': 'Annotation list, {count}',
109
+ 'page.listToggleEmpty': 'Annotation list, empty',
110
+ 'page.listExpand': 'Expand the annotation list',
111
+ 'page.listCollapse': 'Collapse the annotation list',
112
+ 'page.listEmpty': 'No annotations',
113
+ 'page.listAria': 'Annotation list',
114
+ 'page.backToList': 'Back to the local service list',
115
+ 'page.help': 'How this works',
116
+ 'page.locate': 'Locate in the preview',
117
+ 'page.delete': 'Delete this annotation',
118
+ 'page.previewTitle': 'Preview',
119
+ 'page.loading': 'Opening the preview…',
120
+ 'page.loadingHint': 'Connecting to the local service. Annotations are restored automatically.',
121
+ 'page.unavailable': 'Preview unavailable',
122
+ 'page.retry': 'Retry',
123
+ 'page.markTitle': 'Mark mode: click an element to write a note (Esc to leave)',
124
+ 'page.mark': 'Mark',
125
+ 'page.marking': 'Marking',
126
+ 'page.openExternal': 'Open in the system browser',
127
+ 'page.unit': '{count}',
128
+ 'page.attach': 'Add to composer',
129
+ 'page.send': 'Send annotations',
130
+ 'page.sending': 'Sending…',
131
+ 'page.sendHint': 'Send only these annotations and keep the composer draft',
132
+ 'notice.undo': 'Undo',
133
+ 'notice.dismiss': 'Dismiss',
134
+ 'notice.deleted': 'Annotation deleted. You can undo this.',
135
+ 'notice.badAddress': 'That does not look like an address. Try localhost:5173 or just 5173.',
136
+ 'notice.notLocal': 'Open a local development service; external sites and Harness itself are not supported.',
137
+ 'notice.previewFailed': 'Could not open the preview',
138
+ 'notice.detectFailed': 'Scan failed: {error}',
139
+ 'notice.unknownError': 'unknown error',
140
+ 'notice.autoOpened': 'One local service found, opened it automatically',
141
+ 'notice.autoOpenedFile': 'One static page found, opened it automatically',
142
+ 'notice.storageUnavailable': 'Browser storage is unavailable. Add the annotations to the composer before closing.',
143
+ 'notice.finishEditing': 'Save or discard the annotation changes before sending.',
144
+ 'notice.noComposer': 'Select a conversation with a composer first.',
145
+ 'notice.attachFailed': 'Could not add to the composer. The annotations are kept.',
146
+ 'notice.attached': 'Added to the composer. Add context and send when ready.',
147
+ 'notice.sendUnsupported': 'This Harness build cannot send directly; use “Add to composer”.',
148
+ 'notice.notAccepted': 'The conversation did not accept this message',
149
+ 'notice.accepted': 'Conversation accepted {count} annotations',
150
+ 'notice.sendFailed': 'Send failed, annotations kept: {error}',
151
+ 'notice.pluginUnavailable': 'The plugin service is unavailable. Confirm that Harness restarted and loaded the plugin.',
152
+ 'notice.loadTimeout': 'The page took too long to load. Check the development service and retry.',
153
+ 'notice.draftUnavailable': 'The draft cannot be persisted. Save the annotation first.',
154
+ 'notice.elementGone': 'The original element changed or disappeared. The annotation is kept — delete it and annotate again.',
155
+ 'host.notLocalTarget': 'Only local development services can be previewed; Harness itself cannot.',
156
+ 'host.notAllowedFile': 'Only an HTML file inside this workspace can be previewed as a file.',
157
+ 'host.notHtmlFile': 'Only .html and .htm files can be opened as a static page.',
158
+ 'host.staticUnavailable': 'That file is no longer available in this workspace.',
159
+ 'host.tooManyPreviews': 'Too many previews are active. Close another preview and retry.',
160
+ 'host.noCommand': 'No start command is configured (this is an optional feature).',
161
+ 'host.noRoot': 'The workspace directory is unknown, so no dev server can be started.',
162
+ 'host.starting': 'A service for this workspace is already starting. Please wait.',
163
+ 'host.portBusy': 'That port is already in use and cannot be confirmed as yours. Open it from the local service list, or change the port.',
164
+ 'host.startFailed': 'Failed to start: {error}',
165
+ 'host.exited': 'The dev server exited ({code})',
166
+ 'host.readyTimeout': 'Timed out waiting for the dev server to become ready ({seconds}s)',
167
+ 'host.originNotAllowed': 'origin not allowed',
168
+ 'host.methodNotAllowed': 'method not allowed',
169
+ 'host.upstreamUnreachable': 'The local service is unreachable. Check the service or its HTTPS certificate.',
170
+ 'host.previewConnectFailed': 'Preview connection failed',
171
+ 'host.connectTimeout': 'Connection timed out',
172
+ },
173
+
174
+ zh: {
175
+ // ---- annotation block sent to the model ------------------------------
176
+ 'payload.head': '页面批注 · {page}({count} 条)',
177
+ 'payload.locator': ' 元素:',
178
+ 'payload.selectorAmbiguous': '(匹配 {count} 个,需核对)',
179
+ 'payload.selectorNotFound': '(未命中,需核对)',
180
+ 'payload.selectorInvalid': '(选择器无效,需核对)',
181
+ 'payload.selectorUnknown': '(匹配未确认,需核对)',
182
+ 'payload.selectorMissing': '(无选择器,需核对)',
183
+ 'payload.viewport': '视口 {w}×{h}',
184
+ 'payload.verify': ' 核对:',
185
+ 'payload.attached': '已附 {count} 条标注',
186
+ 'payload.removeOne': '从输入框移除这段标注',
187
+ 'payload.removeAll': '全部移除',
188
+ 'zone.topLeft': '左上',
189
+ 'zone.topCenter': '上中',
190
+ 'zone.topRight': '右上',
191
+ 'zone.middleLeft': '左中',
192
+ 'zone.middleCenter': '正中',
193
+ 'zone.middleRight': '右中',
194
+ 'zone.bottomLeft': '左下',
195
+ 'zone.bottomCenter': '下中',
196
+ 'zone.bottomRight': '右下',
197
+
198
+ // ---- injected overlay ------------------------------------------------
199
+ 'overlay.saveFailed': '批注无法保存到浏览器,请在离开页面前加入输入框。',
200
+ 'overlay.viewPin': '查看批注 {n}:{comment}',
201
+ 'overlay.viewTitle': '查看批注',
202
+ 'overlay.editTitle': '编辑批注',
203
+ 'overlay.commentLabel': '批注内容',
204
+ 'overlay.details': '元素定位信息',
205
+ 'overlay.editHint': '点击正文编辑',
206
+ 'overlay.cancel': '取消',
207
+ 'overlay.finishDraft': '请先保存或取消未完成的批注,再编辑另一条。',
208
+ 'page.more': '更多工具',
209
+ 'page.sendOptions': '提交选项',
210
+ 'page.batch': '待提交批注',
211
+ 'page.batchCount': '{count} 条批注',
212
+ 'page.draft': '草稿',
213
+ 'page.resumeDraft': '继续编辑草稿',
214
+ 'page.discardDraft': '丢弃批注草稿',
215
+ 'page.view': '查看批注',
216
+ 'page.pickHint': '点选页面元素 · Esc 退出',
217
+ 'overlay.close': '关闭',
218
+ 'overlay.placeholder': '这里需要怎么调整?',
219
+ 'overlay.hint': 'Enter 保存',
220
+ 'overlay.save': '保存',
221
+
222
+ // ---- panel: entry points --------------------------------------------
223
+ 'panel.tabTitle': '页面批注',
224
+ 'panel.tabDescription': '圈选页面元素,写下修改意见。',
225
+ 'panel.noSession': '先选择工作区并打开会话,再使用界面标注。',
226
+ 'panel.language': '语言',
227
+ 'panel.languageSwitch': '切换到{lang}',
228
+
229
+ // ---- panel: list face -----------------------------------------------
230
+ 'list.detecting': '正在检测本地服务…',
231
+ 'list.detected': '检测到 {count} 个本地服务',
232
+ 'list.none': '没有检测到本地服务',
233
+ 'list.redetect': '重新检测',
234
+ 'list.open': '打开 →',
235
+ 'list.project': '当前项目',
236
+ 'list.declared': '配置端口',
237
+ 'list.filesHeader': '本项目内的静态页面({count})',
238
+ 'list.emptyHint': '没有正在运行的本地 web(已扫 {count} 个端口)。先把它跑起来,再点刷新:',
239
+ 'list.copy': '复制',
240
+ 'list.copied': '已复制:{text}',
241
+ 'list.autoRefresh': '每 5 秒自动检查一次。也可在下方输入端口直接打开。',
242
+ 'list.placeholder': '5173 或 localhost:3000',
243
+ 'list.addressLabel': '本地服务地址',
244
+ 'list.openButton': '打开',
245
+ 'list.helpHeader': '在预览里标注',
246
+ 'list.helpPicking': '点工具栏的「标注」,然后点页面里的元素写批注,Enter 保存后可直接选择下一个元素继续标注。',
247
+ 'list.helpEscape': '按 Esc 或再次点「标注」退出标注状态。',
248
+ 'list.helpCmdClick': '⌘/Ctrl+点击元素 = 写完立即发送。',
249
+ 'list.helpSendHeader': '批注列表与发送',
250
+ 'list.helpSendList': '点底部批注数量展开列表,点击批注先查看,点击正文后直接编辑。',
251
+ 'list.helpSendActions': '「发送批注」只发送当前批注;「加入输入框」可与草稿一起补充后发送。失败时批注会保留。',
252
+
253
+ // ---- panel: page face -----------------------------------------------
254
+ 'page.back': '后退',
255
+ 'page.forward': '前进',
256
+ 'page.reload': '重新载入',
257
+ 'page.addressPlaceholder': '地址',
258
+ 'page.widthLabel': '预览宽度',
259
+ 'page.widthFit': '自适应',
260
+ 'page.widthMobile': '移动端',
261
+ 'page.listToggleLabel': '批注列表,{count} 条',
262
+ 'page.listToggleEmpty': '批注列表,暂无批注',
263
+ 'page.listExpand': '展开批注列表',
264
+ 'page.listCollapse': '收起批注列表',
265
+ 'page.listEmpty': '暂无批注',
266
+ 'page.listAria': '批注列表',
267
+ 'page.backToList': '回到本地服务列表',
268
+ 'page.help': '怎么用',
269
+ 'page.locate': '在预览里定位',
270
+ 'page.delete': '删除这条标注',
271
+ 'page.previewTitle': '预览',
272
+ 'page.loading': '正在打开预览…',
273
+ 'page.loadingHint': '正在连接本地服务,批注会自动恢复。',
274
+ 'page.unavailable': '预览暂时不可用',
275
+ 'page.retry': '重试',
276
+ 'page.markTitle': '标记模式:点击元素写批注(Esc 退出)',
277
+ 'page.mark': '标注',
278
+ 'page.marking': '标注中',
279
+ 'page.openExternal': '在系统浏览器打开',
280
+ 'page.unit': '{count} 条',
281
+ 'page.attach': '加入输入框',
282
+ 'page.send': '发送批注',
283
+ 'page.sending': '发送中…',
284
+ 'page.sendHint': '只发送这些批注,保留输入框中的草稿',
285
+ 'notice.undo': '撤销',
286
+ 'notice.dismiss': '知道了',
287
+ 'notice.deleted': '已删除批注,可撤销。',
288
+ 'notice.badAddress': '这个地址看不出来是什么,试试 localhost:5173 或直接输 5173',
289
+ 'notice.notLocal': '请打开本地开发服务;不支持外部网站或 Harness 自身。',
290
+ 'notice.previewFailed': '无法打开预览',
291
+ 'notice.detectFailed': '检测失败:{error}',
292
+ 'notice.unknownError': '未知错误',
293
+ 'notice.autoOpened': '检测到 1 个本地服务,已自动打开',
294
+ 'notice.autoOpenedFile': '检测到 1 个静态页面,已自动打开',
295
+ 'notice.storageUnavailable': '浏览器存储不可用,请在关闭前加入输入框。',
296
+ 'notice.finishEditing': '请先保存或取消批注的未保存修改,再发送。',
297
+ 'notice.noComposer': '请先选择一个有输入框的会话。',
298
+ 'notice.attachFailed': '未能加入输入框,批注已保留。',
299
+ 'notice.attached': '已加入输入框,可补充说明后发送。',
300
+ 'notice.sendUnsupported': '当前 Harness 不支持直接发送,请使用「加入输入框」。',
301
+ 'notice.notAccepted': '会话未接受这条消息',
302
+ 'notice.accepted': '会话已接收 {count} 条批注',
303
+ 'notice.sendFailed': '发送失败,批注已保留:{error}',
304
+ 'notice.pluginUnavailable': '插件服务不可用,请确认 Harness 已重启并加载插件。',
305
+ 'notice.loadTimeout': '页面加载超时。请检查开发服务后重试。',
306
+ 'notice.draftUnavailable': '草稿无法持久保存,请先保存批注。',
307
+ 'notice.elementGone': '原元素已变化或消失,批注仍保留,可删除后重新标注。',
308
+ 'host.notLocalTarget': '仅支持本地开发服务,不可预览 Harness 自身。',
309
+ 'host.notAllowedFile': '只能预览当前工作区内、属于本项目的 HTML 文件。',
310
+ 'host.notHtmlFile': '静态预览只支持 .html / .htm 文件。',
311
+ 'host.staticUnavailable': '该文件在当前工作区中已不可用。',
312
+ 'host.tooManyPreviews': '正在使用的预览已达上限,请关闭其他预览后重试。',
313
+ 'host.noCommand': '未配置启动命令(可选功能)',
314
+ 'host.noRoot': '不知道工作区目录,无法启动 dev server',
315
+ 'host.starting': '当前工作区的服务正在启动,请稍候。',
316
+ 'host.portBusy': '该端口已被占用,无法确认属于当前工作区。请从本地服务列表打开,或更换端口。',
317
+ 'host.startFailed': '启动失败: {error}',
318
+ 'host.exited': 'dev server 退出({code})',
319
+ 'host.readyTimeout': '等待 dev server 就绪超时({seconds}s)',
320
+ 'host.originNotAllowed': '来源不被允许',
321
+ 'host.methodNotAllowed': '请求方法不被允许',
322
+ 'host.upstreamUnreachable': '本地服务无法连接,请检查服务或 HTTPS 证书。',
323
+ 'host.previewConnectFailed': '预览连接失败',
324
+ 'host.connectTimeout': '连接超时',
325
+ },
326
+ }
327
+
328
+ var LABELS = { en: 'EN', zh: '中' }
329
+
330
+ /** `zh-Hans-CN` and `zh` both mean Chinese; anything else falls through. */
331
+ function normalize(value) {
332
+ var text = String(value || '').toLowerCase()
333
+ if (text.indexOf('zh') === 0) return 'zh'
334
+ if (text.indexOf('en') === 0) return 'en'
335
+ return ''
336
+ }
337
+
338
+ function detect() {
339
+ if (typeof navigator === 'undefined') return 'en'
340
+ var tags = navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language]
341
+ for (var i = 0; i < tags.length; i += 1) {
342
+ var match = normalize(tags[i])
343
+ if (match) return match
344
+ }
345
+ return 'en'
346
+ }
347
+
348
+ function format(template, vars) {
349
+ return String(template).replace(/\{(\w+)\}/g, function (match, key) {
350
+ return vars && Object.prototype.hasOwnProperty.call(vars, key) ? String(vars[key]) : match
351
+ })
352
+ }
353
+
354
+ var lang = normalize(preferred) || detect()
355
+
356
+ return {
357
+ get lang() {
358
+ return lang
359
+ },
360
+ label: function () {
361
+ return LABELS[lang] || lang
362
+ },
363
+ /** Name of the language `toggle()` would switch to, for the button title. */
364
+ nextLabel: function () {
365
+ return LABELS[lang === 'en' ? 'zh' : 'en']
366
+ },
367
+ set: function (next) {
368
+ var match = normalize(next)
369
+ if (match) lang = match
370
+ return lang
371
+ },
372
+ toggle: function () {
373
+ lang = lang === 'zh' ? 'en' : 'zh'
374
+ return lang
375
+ },
376
+ detect: detect,
377
+ /** The raw table for one language. `scripts/check.mjs` uses this to assert
378
+ * that both languages define exactly the same keys. */
379
+ catalog: function (which) {
380
+ return CATALOG[which] || CATALOG.en
381
+ },
382
+ t: function (key, vars) {
383
+ var table = CATALOG[lang] || CATALOG.en
384
+ var value = table[key] === undefined ? CATALOG.en[key] : table[key]
385
+ if (value === undefined) return key
386
+ return vars ? format(value, vars) : value
387
+ },
388
+ }
389
+ }
390
+
391
+ /** Shared visual primitives; build.mjs embeds this in both isolated surfaces. */
392
+ function dsaTheme() {
393
+ return {
394
+ marker: '#f0a05a',
395
+ markerInk: '#8b5529',
396
+ focus: '#438bbf',
397
+ toolbarHeight: 48,
398
+ cardWidth: 294,
399
+ sans: 'ui-sans-serif,system-ui,-apple-system,"Segoe UI","PingFang SC",sans-serif',
400
+ mono: 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace',
401
+ light: { ink: '#252525', muted: '#747474', surface: '#ffffff', field: '#f5f5f5', line: '#e3e3e3', action: '#292929', onAction: '#ffffff' },
402
+ dark: { ink: '#ededed', muted: '#a4a4a4', surface: '#242424', field: '#303030', line: '#444444', action: '#ededed', onAction: '#242424' },
403
+ }
404
+ }
405
+
406
+ /**
407
+ * dsh-annotate — injected overlay.
408
+ *
409
+ * Runs INSIDE the previewed app document, on its own loopback preview origin.
410
+ * Owns the picking interaction, the pins and the comment card, and keeps the
411
+ * annotation list in localStorage so a reload does not lose the review. Talks to
412
+ * the panel with postMessage only — the panel never reaches into this document,
413
+ * and this file has no dependency on React, which also makes it testable on its
414
+ * own.
415
+ *
416
+ * Design direction: drafting overlay. Hairline measurement frame with corner
417
+ * ticks, monospace readouts, numbered marker pins, and one warm "marker" accent
418
+ * that cannot be confused with the app's own accent colour.
419
+ */
420
+ (function () {
421
+ var CHANNEL = 'dsh-annotate-overlay'
422
+ var HOST = 'dsh-annotate-panel'
423
+ var STORE_PREFIX = 'dsh-annotate:v2:'
424
+ var session = String(window.__DSH_ANNO_SESSION__ || 'standalone')
425
+ var currentPage = location.pathname + location.search + location.hash
426
+ var liveElements = new Map()
427
+ var undo = null
428
+ var THEME = dsaTheme()
429
+ var MARKER = THEME.marker
430
+ var undoDraft = null
431
+
432
+ if (window.__dshAnnotateReady) return
433
+ window.__dshAnnotateReady = true
434
+
435
+ // The panel owns the language preference and pushes changes over postMessage;
436
+ // until it says otherwise, follow the browser. `dsaI18n` is prepended to this
437
+ // file by build.mjs.
438
+ var i18n = dsaI18n((window.__DSH_ANNO__ && window.__DSH_ANNO__.lang) || '')
439
+ var t = function (key, vars) { return i18n.t(key, vars) }
440
+
441
+ var state = {
442
+ mode: 'idle', // 'idle' | 'picking' | 'writing'
443
+ hover: null,
444
+ selected: null,
445
+ savedDraft: null,
446
+ drafting: null, // { id, selector, ... , comment }
447
+ viewing: null, // id of the read-only comment currently open
448
+ sendOnCommit: false, // ⌘/Ctrl-click submits the batch right away
449
+ annotations: [],
450
+ anchor: null, // element for the open card
451
+ }
452
+
453
+ // ---------------------------------------------------------------- utilities
454
+
455
+ function isDark() {
456
+ try {
457
+ var bg = getComputedStyle(document.body).backgroundColor || ''
458
+ var m = bg.match(/rgba?\(([^)]+)\)/)
459
+ if (!m) return true
460
+ var parts = m[1].split(',').map(Number)
461
+ var l = (0.2126 * parts[0] + 0.7152 * parts[1] + 0.0722 * parts[2]) / 255
462
+ var alpha = parts.length > 3 ? parts[3] : 1
463
+ if (alpha < 0.2) return true
464
+ return l < 0.5
465
+ } catch (e) {
466
+ return true
467
+ }
468
+ }
469
+
470
+ function css() {
471
+ var dark = isDark()
472
+ var palette = dark ? THEME.dark : THEME.light
473
+ var ink = palette.ink
474
+ var muted = palette.muted
475
+ var panelBg = palette.surface
476
+ var hair = palette.line
477
+ var fieldBg = palette.field
478
+ return [
479
+ // Viewport-fixed: apps often scroll an inner container, where document
480
+ // coordinates never change and absolutely-placed pins would sit still.
481
+ '.dsa-layer{position:fixed;inset:0;width:100%;height:100%;margin:0;padding:0;border:0;overflow:visible;background:transparent;z-index:2147483000;pointer-events:none;',
482
+ 'font:12px/1.45 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:' + ink + '}',
483
+ '.dsa-layer *{box-sizing:border-box}.dsa-layer::backdrop{display:none}',
484
+ '.dsa-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-variant-numeric:tabular-nums}',
485
+ // Clicks are intercepted at window capture; leave hit testing and wheel
486
+ // gestures on the real app so the browser keeps its native scroll path.
487
+ '.dsa-capture{position:absolute;inset:0;z-index:1;pointer-events:none}',
488
+ 'html[data-dsa-mode] body,html[data-dsa-mode] body *{cursor:crosshair!important}',
489
+ // measurement frame
490
+ '.dsa-frame{position:absolute;z-index:3;pointer-events:none;border:1px solid ' + MARKER + ';',
491
+ 'background:color-mix(in srgb,' + MARKER + ' 8%,transparent);transition:opacity .12s ease}',
492
+ '.dsa-frame[data-state="hover"]{border-style:dashed;opacity:.85}',
493
+ '.dsa-frame i{position:absolute;width:7px;height:7px;border:1px solid ' + MARKER + ';background:' + panelBg + '}',
494
+ '.dsa-frame i:nth-child(1){left:-4px;top:-4px}.dsa-frame i:nth-child(2){right:-4px;top:-4px}',
495
+ '.dsa-frame i:nth-child(3){left:-4px;bottom:-4px}.dsa-frame i:nth-child(4){right:-4px;bottom:-4px}',
496
+ // hover readout
497
+ '.dsa-readout{position:absolute;z-index:4;pointer-events:none;display:flex;gap:8px;align-items:center;',
498
+ 'padding:3px 7px;border:1px solid ' + hair + ';border-radius:3px;background:' + panelBg + ';',
499
+ 'box-shadow:0 6px 20px -12px rgba(0,0,0,.6);white-space:nowrap;max-width:min(560px,80vw);overflow:hidden}',
500
+ '.dsa-readout b{color:' + MARKER + ';font-weight:600}',
501
+ '.dsa-readout span{color:' + muted + '}',
502
+ // Pins have a quiet 20px visual and a 32px pointer target.
503
+ '.dsa-pin{appearance:none;padding:0;min-width:0;min-height:0;max-width:none;max-height:none;display:block;position:absolute;z-index:5;pointer-events:auto;border-radius:50%;color:#20160c;text-align:center;cursor:pointer;transform-origin:center}',
504
+ '.dsa-pin:hover{transform:scale(1.08)}.dsa-pin[hidden]{display:none!important}',
505
+ '.dsa-layer button:focus-visible{outline:2px solid ' + THEME.focus + ';outline-offset:2px}',
506
+ '.dsa-pin[data-open="true"]{outline:2px solid ' + MARKER + ';outline-offset:1px}',
507
+ '.dsa-card{position:absolute;z-index:6;pointer-events:auto;color:' + ink + ';background:' + panelBg + ';scrollbar-width:thin;scrollbar-color:' + muted + ' transparent}',
508
+ '.dsa-card header{display:flex;align-items:center}',
509
+ '.dsa-card header .dsa-clip{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
510
+ '.dsa-card header button{all:unset;cursor:pointer;text-align:center;border-radius:4px}',
511
+ '.dsa-card header button:hover{background:' + fieldBg + ';color:' + ink + '}',
512
+ '.dsa-card textarea{display:block;width:100%;border:0;outline:none;background:transparent;color:inherit}',
513
+ '.dsa-card footer{display:flex;align-items:center}',
514
+ '.dsa-comment-text{white-space:pre-wrap;overflow-wrap:anywhere}',
515
+ '.dsa-btn{all:unset;cursor:pointer;border-radius:4px}',
516
+ '.dsa-btn:hover{background:' + fieldBg + ';color:' + ink + '}',
517
+ '.dsa-pin{width:32px;height:32px;margin:-16px 0 0 -16px;border:0;background:transparent;box-shadow:none;font:600 10px/32px ' + THEME.sans + '}',
518
+ '.dsa-pin::before{content:"";position:absolute;inset:6px;z-index:-1;border-radius:50%;background:' + MARKER + ';box-shadow:0 0 0 2px ' + panelBg + ',0 2px 6px #0002}',
519
+ '.dsa-card{width:min(' + THEME.cardWidth + 'px,calc(100vw - 20px));max-height:calc(100vh - 16px);overflow:auto;border:1px solid ' + hair + ';border-radius:14px;backdrop-filter:none;box-shadow:0 10px 30px #0002,0 2px 6px #0001;animation:none}',
520
+ '.dsa-card header{padding:9px 10px 0;border-bottom:0;gap:6px}',
521
+ '.dsa-card header button{flex:none;position:relative;width:24px;height:24px;line-height:24px;color:' + muted + '}',
522
+ '.dsa-card header button[data-act="close"]::before{content:"";position:absolute;inset:-4px}',
523
+ '.dsa-card header .dsa-target{display:inline-flex;align-items:center;gap:5px;max-width:calc(100% - 30px);width:auto;height:auto;min-height:22px;line-height:1.5;padding:2px 6px;border-radius:5px;color:' + ink + ';background:' + fieldBg + ';font-size:10px}',
524
+ '.dsa-target .dsa-clip{color:inherit;min-width:0;max-width:100%;font-family:' + THEME.sans + '}',
525
+ '.dsa-number{flex:none;color:' + (dark ? MARKER : THEME.markerInk) + '}',
526
+ '.dsa-details{margin:7px 11px 0;padding:5px 0 8px;border-bottom:1px solid ' + hair + ';color:' + muted + ';font:10px/1.7 ' + THEME.mono + ';overflow-wrap:anywhere}',
527
+ '.dsa-details[hidden]{display:none!important}',
528
+ '.dsa-card textarea{min-height:58px;max-height:180px;resize:none;padding:10px 12px 5px;font:13px/1.7 ' + THEME.sans + '}',
529
+ '.dsa-card:focus-within{border-color:' + (dark ? '#777777' : '#bfc7cd') + '}',
530
+ '.dsa-card footer{border-top:0;padding:2px 10px 9px;gap:7px;min-height:39px}',
531
+ '.dsa-card footer .dsa-hint{margin-left:auto;flex:none;font:10px ' + THEME.sans + '}',
532
+ '.dsa-comment-card{outline:none}.dsa-comment-card textarea{cursor:text;padding-bottom:12px}',
533
+ '.dsa-btn{padding:3px 5px;font:11px/1.5 ' + THEME.sans + ';color:' + muted + ';border:0}',
534
+ '.dsa-btn.primary{display:inline-flex;align-items:center;justify-content:center;flex:none;width:30px;height:30px;padding:0;border:0;border-radius:50%;background:' + palette.action + ';color:' + palette.onAction + '}',
535
+ '.dsa-btn.primary:hover{background:' + palette.action + ';color:' + palette.onAction + '}',
536
+ '.dsa-btn.primary:disabled{opacity:.3;cursor:default}',
537
+ '.dsa-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}',
538
+ '@media(prefers-reduced-motion:reduce){.dsa-layer *{animation:none!important;transition:none!important}}',
539
+ ].join('')
540
+ }
541
+
542
+ function esc(value) {
543
+ return String(value == null ? '' : value).replace(/[&<>"']/g, function (c) {
544
+ return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
545
+ })
546
+ }
547
+
548
+ function clip(text, max) {
549
+ var t = String(text == null ? '' : text).replace(/\s+/g, ' ').trim()
550
+ return t.length > max ? t.slice(0, max - 1) + '…' : t
551
+ }
552
+
553
+ /** Prefer a stable authored hook when the app has one. */
554
+ function testIdOf(el) {
555
+ var attrs = ['data-testid', 'data-test', 'data-test-id', 'data-qa']
556
+ for (var i = 0; i < attrs.length; i++) {
557
+ var value = el.getAttribute && el.getAttribute(attrs[i])
558
+ if (value) return attrs[i] + '=' + value
559
+ }
560
+ return null
561
+ }
562
+
563
+ /** Short, stable, human-readable path: body > main > section.hero > button.cta */
564
+ function selectorOf(el) {
565
+ var parts = []
566
+ var node = el
567
+ var guard = 0
568
+ while (node && node.nodeType === 1 && node !== document.documentElement && guard++ < 12) {
569
+ var tag = node.tagName.toLowerCase()
570
+ if (node.id) {
571
+ parts.unshift(tag + '#' + CSS.escape(node.id))
572
+ break
573
+ }
574
+ var cls = (node.getAttribute('class') || '').split(/\s+/).filter(Boolean).slice(0, 2)
575
+ var sameTag = node.parentElement
576
+ ? Array.prototype.filter.call(node.parentElement.children, function (c) {
577
+ return c.tagName === node.tagName
578
+ })
579
+ : []
580
+ var nth = sameTag.length > 1 ? ':nth-of-type(' + (sameTag.indexOf(node) + 1) + ')' : ''
581
+ parts.unshift(tag + (cls.length ? '.' + cls.map(function (value) { return CSS.escape(value) }).join('.') : '') + nth)
582
+ if (parts.length > 5) break
583
+ node = node.parentElement
584
+ }
585
+ return parts.join(' > ')
586
+ }
587
+
588
+ /** Component chain (up to three names), when the app runs a dev build. */
589
+ function componentChainOf(el) {
590
+ var chain = []
591
+ try {
592
+ var key = Object.keys(el).filter(function (k) {
593
+ return k.indexOf('__reactFiber$') === 0 || k.indexOf('__reactInternalInstance$') === 0
594
+ })[0]
595
+ if (!key) return chain
596
+ var fiber = el[key]
597
+ var guard = 0
598
+ while (fiber && guard++ < 40 && chain.length < 3) {
599
+ var type = fiber.type
600
+ var name = typeof type === 'function' ? type.displayName || type.name : type && type.displayName
601
+ if (name && !/^[a-z]/.test(name) && chain.indexOf(name) === -1) chain.push(name)
602
+ fiber = fiber.return
603
+ }
604
+ } catch (e) {
605
+ /* dev-only nicety */
606
+ }
607
+ return chain
608
+ }
609
+
610
+ /** Where the element sits in the viewport, coarse and readable. */
611
+ function placementOf(rect) {
612
+ var cx = (rect.left + rect.width / 2) / Math.max(1, window.innerWidth)
613
+ var cy = (rect.top + rect.height / 2) / Math.max(1, window.innerHeight)
614
+ var col = cx < 0.34 ? 'Left' : cx > 0.66 ? 'Right' : 'Center'
615
+ var row = cy < 0.34 ? 'Top' : cy > 0.66 ? 'Bottom' : 'Middle'
616
+ return {
617
+ x: Math.round(cx * 100),
618
+ y: Math.round(cy * 100),
619
+ zone: t('zone.' + row.toLowerCase() + col),
620
+ }
621
+ }
622
+
623
+ /** How many elements the generated selector actually matches: 1 means the
624
+ * annotation is unambiguous, >1 or 0 must be told to the agent. */
625
+ function selectorMatches(selector) {
626
+ try {
627
+ return document.querySelectorAll(selector).length
628
+ } catch (e) {
629
+ return -1
630
+ }
631
+ }
632
+
633
+ /** Nearest React component name, when the app runs a dev build. */
634
+ function componentOf(el) {
635
+ try {
636
+ var key = Object.keys(el).filter(function (k) {
637
+ return k.indexOf('__reactFiber$') === 0 || k.indexOf('__reactInternalInstance$') === 0
638
+ })[0]
639
+ if (!key) return null
640
+ var fiber = el[key]
641
+ var guard = 0
642
+ while (fiber && guard++ < 24) {
643
+ var type = fiber.type
644
+ var name = typeof type === 'function' ? type.displayName || type.name : type && type.displayName
645
+ if (name && !/^[a-z]/.test(name)) return name
646
+ fiber = fiber.return
647
+ }
648
+ } catch (e) {
649
+ /* dev-only nicety */
650
+ }
651
+ return null
652
+ }
653
+
654
+ function stylesOf(el) {
655
+ var out = {}
656
+ try {
657
+ var cs = getComputedStyle(el)
658
+ var keys = ['display', 'position', 'gap', 'padding', 'margin', 'width', 'height',
659
+ 'font-size', 'font-weight', 'line-height', 'color', 'background-color', 'border-radius',
660
+ 'border-width', 'box-shadow', 'opacity', 'z-index']
661
+ for (var i = 0; i < keys.length; i++) {
662
+ var v = cs.getPropertyValue(keys[i])
663
+ if (v && v !== 'none' && v !== 'normal' && v !== 'auto' && v !== '0px') out[keys[i]] = v
664
+ }
665
+ } catch (e) {
666
+ /* cross-origin would have failed earlier */
667
+ }
668
+ return out
669
+ }
670
+
671
+ function detailOf(el) {
672
+ var rect = el.getBoundingClientRect()
673
+ var selector = selectorOf(el)
674
+ var chain = componentChainOf(el)
675
+ return {
676
+ selector: selector,
677
+ selectorMatches: selectorMatches(selector),
678
+ testId: testIdOf(el),
679
+ component: chain[0] || componentOf(el),
680
+ componentChain: chain,
681
+ role: el.getAttribute('role') || el.tagName.toLowerCase(),
682
+ ariaLabel: el.getAttribute('aria-label') || null,
683
+ alt: el.getAttribute('alt') || null,
684
+ name: el.getAttribute('name') || null,
685
+ type: el.getAttribute('type') || null,
686
+ tag: el.tagName.toLowerCase(),
687
+ classes: (el.getAttribute('class') || '').split(/\s+/).filter(Boolean).slice(0, 4),
688
+ text: clip(el.textContent || '', 120),
689
+ rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
690
+ // Pins live in document space: mixing a viewport rect with the scroll
691
+ // offset at render time makes them drift instead of following the element.
692
+ doc: {
693
+ x: Math.round(rect.x + window.scrollX),
694
+ y: Math.round(rect.y + window.scrollY),
695
+ w: Math.round(rect.width),
696
+ h: Math.round(rect.height),
697
+ },
698
+ placement: placementOf(rect),
699
+ page: location.pathname + location.search,
700
+ viewport: { w: window.innerWidth, h: window.innerHeight },
701
+ styles: stylesOf(el),
702
+ }
703
+ }
704
+
705
+ // -------------------------------------------------------------- persistence
706
+
707
+ function storeKey() {
708
+ return STORE_PREFIX + encodeURIComponent(session) + ':' + currentPage
709
+ }
710
+
711
+ function load() {
712
+ try {
713
+ var raw = localStorage.getItem(storeKey())
714
+ var list = raw ? JSON.parse(raw) : []
715
+ return Array.isArray(list) ? list : []
716
+ } catch (e) {
717
+ return []
718
+ }
719
+ }
720
+
721
+ function save() {
722
+ try {
723
+ localStorage.setItem(storeKey(), JSON.stringify(state.annotations))
724
+ } catch (e) {
725
+ post('warning', { message: t('overlay.saveFailed') })
726
+ }
727
+ }
728
+
729
+ // ------------------------------------------------------------------- render
730
+
731
+ var root = document.createElement('div')
732
+ var mounted = false
733
+ var pendingHostMessages = []
734
+ root.className = 'dsa-layer'
735
+ var styleEl = document.createElement('style')
736
+ var capture = document.createElement('div')
737
+ capture.className = 'dsa-capture'
738
+ var pinLayer = document.createElement('div')
739
+ var frame = document.createElement('div')
740
+ frame.className = 'dsa-frame'
741
+ frame.innerHTML = '<i></i><i></i><i></i><i></i>'
742
+ var readout = document.createElement('div')
743
+ readout.className = 'dsa-readout dsa-mono'
744
+ var card = null
745
+ var cardObserver = null
746
+ var cardObserving = false
747
+
748
+ function mount() {
749
+ if (mounted) return
750
+ styleEl.textContent = css()
751
+ root.appendChild(styleEl)
752
+ root.appendChild(pinLayer)
753
+ root.appendChild(frame)
754
+ root.appendChild(readout)
755
+ document.documentElement.appendChild(root)
756
+ // The top layer escapes transformed app roots and their clipping contexts.
757
+ if (typeof root.showPopover === 'function') {
758
+ root.setAttribute('popover', 'manual')
759
+ root.showPopover()
760
+ }
761
+ mounted = true
762
+ render()
763
+ post('ready', { annotations: state.annotations, path: location.pathname })
764
+ var pending = pendingHostMessages
765
+ pendingHostMessages = []
766
+ pending.forEach(handleHostMessage)
767
+ }
768
+
769
+ function mountCapture() {
770
+ var active = state.mode !== 'idle'
771
+ if (active && capture.parentNode !== root) root.insertBefore(capture, pinLayer)
772
+ if (!active && capture.parentNode === root) root.removeChild(capture)
773
+ if (active) document.documentElement.setAttribute('data-dsa-mode', state.mode)
774
+ else document.documentElement.removeAttribute('data-dsa-mode')
775
+ }
776
+
777
+ /** The inert overlay leaves the real app in the browser's hit-test tree. */
778
+ function elementAt(x, y) {
779
+ var el = document.elementFromPoint(x, y)
780
+ if (!el || el === root || root.contains(el)) return null
781
+ return el
782
+ }
783
+
784
+ // Measurements only live for one update. Shared clipping ancestors are read
785
+ // once per frame, and no cached rectangle survives a scroll or layout change.
786
+ var measurements = null
787
+ function withMeasurements(callback) {
788
+ var previous = measurements
789
+ measurements = previous || new WeakMap()
790
+ try { return callback() } finally { measurements = previous }
791
+ }
792
+
793
+ function measurement(el) {
794
+ if (!measurements) return {}
795
+ var value = measurements.get(el)
796
+ if (!value) { value = {}; measurements.set(el, value) }
797
+ return value
798
+ }
799
+
800
+ function rectOf(el) {
801
+ var value = measurement(el)
802
+ if (!value.rect) value.rect = el.getBoundingClientRect()
803
+ return value.rect
804
+ }
805
+
806
+ function setStyle(el, key, value) {
807
+ if (el.style[key] !== value) el.style[key] = value
808
+ }
809
+
810
+ function render() {
811
+ if (!mounted) return
812
+ var dark = isDark()
813
+ root.setAttribute('data-dark', dark ? '1' : '0')
814
+ mountCapture()
815
+ renderFrame()
816
+ renderPins()
817
+ }
818
+
819
+ function framePosition() {
820
+ var target = state.selected || state.hover
821
+ var visible = visibleRect(target)
822
+ if (!visible) return null
823
+ var rect = visible.rect
824
+ var component = componentOf(target)
825
+ var content =
826
+ '<b>' + esc(target.tagName.toLowerCase()) + '</b>' +
827
+ (target.getAttribute('class') ? '<span>.' + esc(clip(target.getAttribute('class'), 28).split(' ')[0]) + '</span>' : '') +
828
+ (component ? '<span>· ' + esc(component) + '</span>' : '') +
829
+ '<span>· ' + Math.round(rect.width) + '×' + Math.round(rect.height) + '</span>'
830
+ var top = rect.top - 26
831
+ // A pin is anchored to the element's top edge, so a readout directly above
832
+ // it would sit on the marker; lift it clear instead of stacking two labels.
833
+ var annotated = state.annotations.some(function (ann) {
834
+ var el = elementFor(ann)
835
+ if (!el || !el.isConnected) return false
836
+ var other = rectOf(el)
837
+ return Math.abs(other.left + other.width / 2 - (rect.left + rect.width / 2)) < 2 &&
838
+ Math.abs(other.top - rect.top) < 2
839
+ })
840
+ if (annotated) top -= 24
841
+ var left = Math.max(4, rect.left)
842
+ if (top < 4) {
843
+ // No room above: prefer the element's right side (usually open canvas),
844
+ // and only fall back to below when the right edge is too close too.
845
+ if (window.innerWidth - rect.right > 240) {
846
+ left = rect.right + 8
847
+ top = rect.top - 2
848
+ } else {
849
+ top = rect.bottom + 6
850
+ }
851
+ }
852
+ return { rect: rect, content: content, left: left, top: top, selected: !!state.selected }
853
+ }
854
+
855
+ function renderFrame(position) {
856
+ if (arguments.length === 0) position = withMeasurements(framePosition)
857
+ if (!position) {
858
+ setStyle(frame, 'display', 'none')
859
+ setStyle(readout, 'display', 'none')
860
+ return
861
+ }
862
+ var rect = position.rect
863
+ var nextState = position.selected ? 'selected' : 'hover'
864
+ if (frame.getAttribute('data-state') !== nextState) frame.setAttribute('data-state', nextState)
865
+ setStyle(frame, 'display', 'block')
866
+ setStyle(frame, 'left', rect.left + 'px')
867
+ setStyle(frame, 'top', rect.top + 'px')
868
+ setStyle(frame, 'width', rect.width + 'px')
869
+ setStyle(frame, 'height', rect.height + 'px')
870
+ setStyle(readout, 'display', state.mode === 'writing' || state.viewing ? 'none' : 'flex')
871
+ if (readout.innerHTML !== position.content) readout.innerHTML = position.content
872
+ setStyle(readout, 'left', position.left + 'px')
873
+ setStyle(readout, 'top', position.top + 'px')
874
+ }
875
+
876
+ function overlapArea(a, b) {
877
+ var w = Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left)
878
+ var h = Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top)
879
+ return w > 0 && h > 0 ? w * h : 0
880
+ }
881
+
882
+ function cardPosition() {
883
+ if (!card || !state.anchor || !state.anchor.isConnected) return null
884
+ var rect = rectOf(state.anchor)
885
+ var vw = window.innerWidth
886
+ var vh = window.innerHeight
887
+ // If the click landed on a small label inside a compact row (breadcrumbs,
888
+ // toolbar, list item), treat the row as the anchor. Otherwise the card
889
+ // docks above the label but still clips the row it belongs to.
890
+ var parent = state.anchor.parentElement
891
+ if (parent && parent !== document.body && parent !== document.documentElement) {
892
+ var pr = rectOf(parent)
893
+ if (pr.height >= rect.height && pr.height <= 96 && pr.width <= vw && pr.top <= rect.top + 0.5 && pr.bottom >= rect.bottom - 0.5) {
894
+ rect = {
895
+ left: Math.min(rect.left, pr.left),
896
+ top: Math.min(rect.top, pr.top),
897
+ right: Math.max(rect.right, pr.right),
898
+ bottom: Math.max(rect.bottom, pr.bottom),
899
+ width: Math.max(rect.right, pr.right) - Math.min(rect.left, pr.left),
900
+ height: Math.max(rect.bottom, pr.bottom) - Math.min(rect.top, pr.top),
901
+ }
902
+ }
903
+ }
904
+ var width = Math.min(card.offsetWidth || 304, window.innerWidth - 16)
905
+ // offsetHeight already includes an earlier cap; scrollHeight keeps the
906
+ // uncapped content height so a capped card does not oscillate between
907
+ // "fits" and "grows back over the element" on the next layout pass.
908
+ var height = Math.max(card.offsetHeight || 0, card.scrollHeight || 0) || 168
909
+ var pad = 8
910
+ var gap = 12
911
+ var clampLeft = function (value) { return Math.max(pad, Math.min(value, vw - width - pad)) }
912
+ var clampTop = function (value) { return Math.max(pad, Math.min(value, vh - height - pad)) }
913
+ // Vertical room is bounded by the element, so the card can be capped and
914
+ // scroll internally instead of spilling onto the element's pixels.
915
+ var aboveRoom = Math.max(0, rect.top - gap - pad)
916
+ var belowRoom = Math.max(0, vh - rect.bottom - gap - pad)
917
+ var belowHeight = Math.min(height, belowRoom)
918
+ var aboveHeight = Math.min(height, aboveRoom)
919
+ // Never cover the element being annotated. Try right, left, below, above —
920
+ // the first side with real room wins. Wide elements (a full-width header,
921
+ // for example) have no side room, so they must dock above/below instead of
922
+ // falling back to the anchor's own top-left corner, which covered it.
923
+ var candidates = [
924
+ { left: rect.right + gap, top: clampTop(rect.top), height: height, maxHeight: 0 },
925
+ { left: rect.left - width - gap, top: clampTop(rect.top), height: height, maxHeight: 0 },
926
+ { left: clampLeft(rect.left + rect.width / 2 - width / 2), top: rect.bottom + gap, height: belowHeight, maxHeight: belowHeight < height ? belowHeight : 0 },
927
+ { left: clampLeft(rect.left + rect.width / 2 - width / 2), top: Math.max(pad, rect.top - aboveHeight - gap), height: aboveHeight, maxHeight: aboveHeight < height ? aboveHeight : 0 },
928
+ ]
929
+ for (var i = 0; i < candidates.length; i++) {
930
+ var fit = candidates[i]
931
+ if (fit.height < 80) continue
932
+ if (fit.left >= pad - 0.5 && fit.left + width <= vw - pad + 0.5 &&
933
+ fit.top >= pad - 0.5 && fit.top + fit.height <= vh - pad + 0.5 &&
934
+ overlapArea({ left: fit.left, top: fit.top, width: width, height: fit.height }, rect) === 0) {
935
+ return { left: fit.left, top: fit.top, maxHeight: fit.maxHeight }
936
+ }
937
+ }
938
+ // The element leaves no completely free side. Pick the placement with the
939
+ // least overlap (usually a sliver at a viewport edge) so the card never
940
+ // sits squarely on top of what the user just selected.
941
+ var best = null
942
+ var bestOverlap = Infinity
943
+ candidates.forEach(function (candidate) {
944
+ var left = clampLeft(candidate.left)
945
+ var top = clampTop(candidate.top)
946
+ var overlap = overlapArea({ left: left, top: top, width: width, height: candidate.height }, rect)
947
+ if (overlap < bestOverlap - 0.5) {
948
+ bestOverlap = overlap
949
+ best = { left: left, top: top, maxHeight: candidate.maxHeight }
950
+ }
951
+ })
952
+ return best || { left: pad, top: pad, maxHeight: 0 }
953
+ }
954
+
955
+ function anchorCard(position) {
956
+ if (arguments.length === 0) position = withMeasurements(cardPosition)
957
+ if (!card || !position) return
958
+ setStyle(card, 'left', position.left + 'px')
959
+ setStyle(card, 'top', position.top + 'px')
960
+ setStyle(card, 'max-height', position.maxHeight ? position.maxHeight + 'px' : '')
961
+ }
962
+
963
+ /** Re-place the card after its content settles (textarea growth, wrapping,
964
+ * details expansion). The first measurement happens before the card reaches
965
+ * its final height, so without this the card can grow back over the selected
966
+ * element by the difference. */
967
+ function watchCard() {
968
+ if (cardObserver) { cardObserver.disconnect(); cardObserver = null }
969
+ if (!card || typeof ResizeObserver !== 'function') return
970
+ cardObserver = new ResizeObserver(function () {
971
+ if (cardObserving) return
972
+ cardObserving = true
973
+ requestAnimationFrame(function () {
974
+ cardObserving = false
975
+ if (card) anchorCard()
976
+ })
977
+ })
978
+ cardObserver.observe(card)
979
+ }
980
+
981
+ function unwatchCard() {
982
+ if (cardObserver) { cardObserver.disconnect(); cardObserver = null }
983
+ }
984
+
985
+ /** A card's height is only final after the browser lays out the textarea and
986
+ * wraps the text; re-place it a couple of times to catch those late changes. */
987
+ function laterAnchor() {
988
+ setTimeout(function () { if (card) anchorCard() }, 80)
989
+ setTimeout(function () { if (card) anchorCard() }, 320)
990
+ }
991
+
992
+ /** Where a pin belongs right now, in viewport coordinates: the element's live
993
+ * position, so it travels with the page whether the window or an inner
994
+ * container scrolls. Falls back to the recorded document position. */
995
+ function elementFor(ann) {
996
+ var cached = liveElements.get(ann.id)
997
+ if (cached && cached.isConnected) return cached
998
+ var el = query(ann.selector)
999
+ // Never attach to an arbitrary lookalike after a component disappears: the
1000
+ // match has to be the same kind of element, not just the same selector.
1001
+ if (!el) return null
1002
+ if (ann.tag && el.tagName.toLowerCase() !== String(ann.tag).toLowerCase()) return null
1003
+ liveElements.set(ann.id, el)
1004
+ return el
1005
+ }
1006
+
1007
+ function clippingBounds(node) {
1008
+ if (!node || node === document.documentElement) return { left: 0, top: 0, right: innerWidth, bottom: innerHeight }
1009
+ var value = measurement(node)
1010
+ if (!value.bounds) {
1011
+ var bounds = Object.assign({}, clippingBounds(node.parentElement))
1012
+ var style = getComputedStyle(node)
1013
+ var clipsX = /(auto|scroll|hidden|clip)/.test(style.overflowX)
1014
+ var clipsY = /(auto|scroll|hidden|clip)/.test(style.overflowY)
1015
+ var box = clipsX || clipsY ? rectOf(node) : null
1016
+ if (clipsX) {
1017
+ bounds.left = Math.max(bounds.left, box.left)
1018
+ bounds.right = Math.min(bounds.right, box.right)
1019
+ }
1020
+ if (clipsY) {
1021
+ bounds.top = Math.max(bounds.top, box.top)
1022
+ bounds.bottom = Math.min(bounds.bottom, box.bottom)
1023
+ }
1024
+ value.bounds = bounds
1025
+ }
1026
+ return value.bounds
1027
+ }
1028
+
1029
+ function visibleRect(el) {
1030
+ if (!el || !el.isConnected) return null
1031
+ var rect = rectOf(el)
1032
+ if (rect.width <= 0 || rect.height <= 0 || rect.bottom <= 0 || rect.top >= innerHeight ||
1033
+ rect.right <= 0 || rect.left >= innerWidth) return null
1034
+ var bounds = clippingBounds(el.parentElement)
1035
+ if (rect.bottom <= bounds.top || rect.top >= bounds.bottom ||
1036
+ rect.right <= bounds.left || rect.left >= bounds.right) return null
1037
+ return { rect: rect, bounds: bounds }
1038
+ }
1039
+
1040
+ function pinAnchor(ann) {
1041
+ var visible = visibleRect(elementFor(ann))
1042
+ if (!visible) return null
1043
+ var rect = visible.rect, bounds = visible.bounds
1044
+ // Hide the flag when its edge is clipped; never leave a floating flag on
1045
+ // another component, and never fall back to stale absolute coordinates.
1046
+ if (rect.top < bounds.top || rect.top >= bounds.bottom) return null
1047
+ return { x: Math.max(bounds.left + 10, Math.min(bounds.right - 10, rect.left + rect.width / 2)), y: rect.top }
1048
+ }
1049
+
1050
+ /** Scroll/resize path: move the existing pins, don't rebuild them. */
1051
+ function positionPins(anchors) {
1052
+ state.annotations.forEach(function (ann, index) {
1053
+ var pin = pinLayer.children[index]
1054
+ if (!pin) return
1055
+ var anchor = anchors[index]
1056
+ if (pin.hidden !== !anchor) pin.hidden = !anchor
1057
+ if (anchor) {
1058
+ setStyle(pin, 'left', anchor.x + 'px')
1059
+ setStyle(pin, 'top', anchor.y + 'px')
1060
+ }
1061
+ })
1062
+ }
1063
+
1064
+ function updatePositions() {
1065
+ withMeasurements(function () {
1066
+ // Read all geometry before changing any overlay styles or markup.
1067
+ var anchors = state.annotations.map(pinAnchor)
1068
+ var nextFrame = framePosition()
1069
+ var nextCard = cardPosition()
1070
+ positionPins(anchors)
1071
+ renderFrame(nextFrame)
1072
+ anchorCard(nextCard)
1073
+ })
1074
+ }
1075
+
1076
+ function renderPins() {
1077
+ pinLayer.innerHTML = ''
1078
+ state.annotations.forEach(function (ann, index) {
1079
+ var pin = document.createElement('button')
1080
+ pin.type = 'button'
1081
+ pin.setAttribute('aria-label', t('overlay.viewPin', { n: index + 1, comment: ann.comment }))
1082
+ pin.className = 'dsa-pin'
1083
+ pin.dataset.id = ann.id
1084
+ pin.textContent = String(index + 1)
1085
+ pin.title = ann.comment
1086
+ var anchor = pinAnchor(ann)
1087
+ pin.hidden = !anchor
1088
+ if (anchor) {
1089
+ pin.style.left = anchor.x + 'px'
1090
+ pin.style.top = anchor.y + 'px'
1091
+ }
1092
+ pin.setAttribute('data-open', state.viewing === ann.id ? 'true' : 'false')
1093
+ pin.addEventListener('click', function (event) {
1094
+ event.stopPropagation()
1095
+ if (state.viewing === ann.id) { closeCard(); return }
1096
+ var el = elementFor(ann)
1097
+ if (!el) {
1098
+ post('missing', { id: ann.id })
1099
+ return
1100
+ }
1101
+ showComment(ann, el)
1102
+ post('focus', { id: ann.id })
1103
+ })
1104
+ pinLayer.appendChild(pin)
1105
+ })
1106
+ anchorCard()
1107
+ }
1108
+
1109
+ function query(selector) {
1110
+ try {
1111
+ var matches = document.querySelectorAll(selector)
1112
+ return matches.length === 1 ? matches[0] : null
1113
+ } catch (e) {
1114
+ return null
1115
+ }
1116
+ }
1117
+
1118
+ // ------------------------------------------------------------------ card UI
1119
+
1120
+ function draftIsDirty(draft, text) {
1121
+ var original = draft.existing ? String(draft.initialComment || '') : ''
1122
+ return draft.existing ? text !== original : !!text.trim()
1123
+ }
1124
+
1125
+ function publishDraft(open) {
1126
+ if (!card || !state.drafting) return
1127
+ var area = card.querySelector('textarea')
1128
+ if (!area) return
1129
+ var draft = state.drafting
1130
+ if (draftIsDirty(draft, area.value)) {
1131
+ state.savedDraft = Object.assign({}, draft, { comment: area.value, open: open })
1132
+ } else if (state.savedDraft && state.savedDraft.id === draft.id) {
1133
+ state.savedDraft = null
1134
+ }
1135
+ post('draft', { draft: state.savedDraft })
1136
+ }
1137
+
1138
+ function focusPin(id) {
1139
+ if (!id) return
1140
+ var pin = Array.prototype.find.call(pinLayer.querySelectorAll('.dsa-pin'), function (node) { return node.dataset.id === id })
1141
+ if (pin && !pin.hidden) pin.focus({ preventScroll: true })
1142
+ }
1143
+
1144
+ function closeCard(preserve) {
1145
+ if (card && state.drafting && preserve !== 'silent') {
1146
+ if (preserve !== false) publishDraft(false)
1147
+ else if (state.savedDraft && state.savedDraft.id === state.drafting.id) {
1148
+ state.savedDraft = null
1149
+ post('draft', { draft: null })
1150
+ }
1151
+ }
1152
+ unwatchCard()
1153
+ if (card && card.parentNode) card.parentNode.removeChild(card)
1154
+ card = null
1155
+ state.drafting = null
1156
+ state.viewing = null
1157
+ state.anchor = null
1158
+ if (state.mode === 'writing') state.mode = 'idle'
1159
+ state.selected = null
1160
+ render()
1161
+ post('mode', { mode: state.mode, count: state.annotations.length })
1162
+ }
1163
+
1164
+ function targetLabel(detail) {
1165
+ return clip(String(detail.ariaLabel || detail.text || detail.component || detail.tag || '').replace(/\s+/g, ' ').trim(), 60)
1166
+ }
1167
+
1168
+ function cardHeader(detail, number) {
1169
+ return '<header>' +
1170
+ '<button type="button" class="dsa-target" data-act="details" aria-expanded="false" title="' + esc(t('overlay.details')) + '">' +
1171
+ (number ? '<span class="dsa-number">' + esc(number) + '</span>' : '') +
1172
+ '<span class="dsa-clip">' + esc(targetLabel(detail)) + '</span></button>' +
1173
+ '<button type="button" data-act="close" aria-label="' + esc(t('overlay.close')) + '">✕</button></header>' +
1174
+ '<div class="dsa-details" hidden>' + esc(detail.selector) + '</div>'
1175
+ }
1176
+
1177
+ function bindCardDetails() {
1178
+ card.querySelector('[data-act="details"]').addEventListener('click', function (event) {
1179
+ var details = card.querySelector('.dsa-details')
1180
+ details.hidden = !details.hidden
1181
+ event.currentTarget.setAttribute('aria-expanded', String(!details.hidden))
1182
+ anchorCard()
1183
+ })
1184
+ }
1185
+
1186
+ function editComment(ann, el) {
1187
+ var draft = state.savedDraft && state.savedDraft.id === ann.id ? state.savedDraft : {
1188
+ id: ann.id, detail: ann, comment: ann.comment, initialComment: ann.comment, existing: true,
1189
+ }
1190
+ openCard(draft, el)
1191
+ }
1192
+
1193
+ function showComment(ann, el) {
1194
+ setMode('idle')
1195
+ state.viewing = ann.id
1196
+ state.anchor = el
1197
+ card = document.createElement('div')
1198
+ card.className = 'dsa-card dsa-comment-card'
1199
+ card.setAttribute('role', 'region')
1200
+ card.setAttribute('aria-label', t('overlay.viewTitle'))
1201
+ card.tabIndex = -1
1202
+ card.innerHTML = cardHeader(ann, String(state.annotations.indexOf(ann) + 1)) +
1203
+ '<textarea class="dsa-comment-text" readonly aria-label="' + esc(t('overlay.commentLabel')) + '" title="' + esc(t('overlay.editHint')) + '"></textarea>'
1204
+ var area = card.querySelector('textarea')
1205
+ area.value = ann.comment
1206
+ card.querySelector('[data-act="close"]').addEventListener('click', function () { closeCard() })
1207
+ area.addEventListener('focus', function () {
1208
+ if (state.viewing === ann.id) editComment(ann, el)
1209
+ })
1210
+ bindCardDetails()
1211
+ root.appendChild(card)
1212
+ area.style.height = Math.min(180, Math.max(58, area.scrollHeight)) + 'px'
1213
+ renderPins()
1214
+ anchorCard()
1215
+ watchCard()
1216
+ laterAnchor()
1217
+ // Keep the text unfocused until the user clicks it or tabs into it.
1218
+ card.focus({ preventScroll: true })
1219
+ }
1220
+
1221
+ function openCard(draft, el, sendOnCommit) {
1222
+ if (state.savedDraft && state.savedDraft.id !== draft.id) {
1223
+ post('warning', { message: t('overlay.finishDraft') })
1224
+ return
1225
+ }
1226
+ // Reuse the read-only field so the browser keeps the clicked caret position.
1227
+ var viewedCard = state.viewing === draft.id ? card : null
1228
+ if (!viewedCard) closeCard()
1229
+ state.viewing = null
1230
+ if (state.savedDraft && state.savedDraft.id === draft.id) draft = state.savedDraft
1231
+ var original = draft.existing ? state.annotations.find(function (ann) { return ann.id === draft.id }) : null
1232
+ draft = Object.assign({}, draft, { initialComment: draft.initialComment === undefined ? (original ? original.comment : '') : draft.initialComment })
1233
+ state.drafting = draft
1234
+ state.sendOnCommit = !!sendOnCommit
1235
+ state.mode = 'writing'
1236
+ state.anchor = el
1237
+ state.selected = el
1238
+ mountCapture()
1239
+ post('mode', { mode: state.mode })
1240
+ card = viewedCard || document.createElement('div')
1241
+ card.className = 'dsa-card'
1242
+ card.setAttribute('role', 'region')
1243
+ card.setAttribute('aria-label', t('overlay.editTitle'))
1244
+ if (!viewedCard) card.innerHTML = cardHeader(draft.detail) +
1245
+ '<textarea aria-label="' + esc(t('overlay.commentLabel')) + '" placeholder="' + esc(t('overlay.placeholder')) + '"></textarea>'
1246
+ card.insertAdjacentHTML('beforeend', '<footer><button type="button" class="dsa-btn" data-act="cancel">' + esc(t('overlay.cancel')) + '</button>' +
1247
+ '<span class="dsa-hint">' + esc(t('overlay.hint')) + '</span>' +
1248
+ '<button type="button" class="dsa-btn primary" data-act="save" aria-label="' + esc(t('overlay.save')) + '" title="' + esc(t('overlay.save')) + '">' +
1249
+ '<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M12 20V4m-6 6 6-6 6 6"/></svg></button></footer>')
1250
+ var area = card.querySelector('textarea')
1251
+ if (area.value !== (draft.comment || '')) area.value = draft.comment || ''
1252
+ area.readOnly = false
1253
+ area.removeAttribute('title')
1254
+ var saveButton = card.querySelector('[data-act="save"]')
1255
+ saveButton.disabled = !area.value.trim()
1256
+ area.addEventListener('input', function () {
1257
+ saveButton.disabled = !area.value.trim()
1258
+ area.style.height = 'auto'
1259
+ area.style.height = Math.min(180, Math.max(58, area.scrollHeight)) + 'px'
1260
+ publishDraft(true)
1261
+ anchorCard()
1262
+ })
1263
+ if (!viewedCard) card.querySelector('[data-act="close"]').addEventListener('click', function () { closeCard() })
1264
+ card.querySelector('[data-act="cancel"]').addEventListener('click', function () { closeCard(false) })
1265
+ saveButton.addEventListener('click', commit)
1266
+ if (!viewedCard) bindCardDetails()
1267
+ area.addEventListener('keydown', function (event) {
1268
+ if (event.isComposing || event.keyCode === 229) return
1269
+ if (event.key === 'Enter' && !event.shiftKey) {
1270
+ event.preventDefault()
1271
+ commit()
1272
+ } else if (event.key === 'Escape') {
1273
+ event.preventDefault()
1274
+ event.stopPropagation()
1275
+ var id = state.drafting && state.drafting.id
1276
+ setMode('idle')
1277
+ focusPin(id)
1278
+ }
1279
+ })
1280
+ if (!viewedCard) root.appendChild(card)
1281
+ area.style.height = Math.min(180, Math.max(58, area.scrollHeight)) + 'px'
1282
+ anchorCard()
1283
+ watchCard()
1284
+ laterAnchor()
1285
+ area.focus({ preventScroll: true })
1286
+ post('drafting', { id: draft.id, selector: draft.detail.selector })
1287
+ publishDraft(true)
1288
+ }
1289
+
1290
+ /** Follow the panel's language and re-render. A card that is already open is
1291
+ * rebuilt from the same draft, so nothing typed is lost. */
1292
+ function setLang(next) {
1293
+ if (!next || i18n.set(next) !== next) return
1294
+ var viewed = state.viewing && state.annotations.find(function (ann) { return ann.id === state.viewing })
1295
+ var viewedAnchor = state.anchor
1296
+ renderPins()
1297
+ render()
1298
+ if (card && state.drafting && state.anchor) {
1299
+ var draft = Object.assign({}, state.drafting, { comment: card.querySelector('textarea').value })
1300
+ openCard(draft, state.anchor)
1301
+ }
1302
+ if (viewed && viewedAnchor) showComment(viewed, viewedAnchor)
1303
+ }
1304
+
1305
+ function commit() {
1306
+ if (!card || !state.drafting || !state.anchor) return
1307
+ var text = card.querySelector('textarea').value.trim()
1308
+ if (!text) {
1309
+ return
1310
+ }
1311
+ var draft = state.drafting
1312
+ var detail = detailOf(state.anchor)
1313
+ if (draft.existing) {
1314
+ state.annotations = state.annotations.map(function (ann) {
1315
+ return ann.id === draft.id
1316
+ ? Object.assign({}, ann, detail, { comment: text })
1317
+ : ann
1318
+ })
1319
+ } else {
1320
+ state.annotations = state.annotations.concat([
1321
+ Object.assign({ id: draft.id, comment: text, createdAt: Date.now() }, detail),
1322
+ ])
1323
+ }
1324
+ liveElements.set(draft.id, state.anchor)
1325
+ save()
1326
+ if (state.savedDraft && state.savedDraft.id === draft.id) state.savedDraft = null
1327
+ post('draft', { draft: state.savedDraft })
1328
+ state.drafting = null
1329
+ var ship = state.sendOnCommit
1330
+ state.sendOnCommit = false
1331
+ setMode(ship ? 'idle' : 'picking')
1332
+ renderPins()
1333
+ post('changed', { annotations: state.annotations })
1334
+ if (ship) post('send', { annotations: state.annotations })
1335
+ }
1336
+
1337
+ // ------------------------------------------------------------------ picking
1338
+
1339
+ function pick(event) {
1340
+ if (state.mode === 'writing') {
1341
+ event.preventDefault()
1342
+ event.stopImmediatePropagation()
1343
+ closeCard()
1344
+ return
1345
+ }
1346
+ if (state.mode !== 'picking') return
1347
+ if (state.busy) return
1348
+ var el = elementAt(event.clientX, event.clientY)
1349
+ if (!el) {
1350
+ return
1351
+ }
1352
+ event.preventDefault()
1353
+ event.stopImmediatePropagation()
1354
+ state.selected = el
1355
+ state.hover = null
1356
+ state.mode = 'writing'
1357
+ post('mode', { mode: state.mode, count: state.annotations.length })
1358
+ // Codex parity: ⌘/Ctrl-click means "write it and ship it".
1359
+ render()
1360
+ var detail = detailOf(el)
1361
+ var draft = state.savedDraft && state.savedDraft.detail.selector === detail.selector ? state.savedDraft : { id: 'a' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), detail: detail, comment: '' }
1362
+ openCard(draft, el, event.metaKey || event.ctrlKey)
1363
+ }
1364
+
1365
+ var pointer = null
1366
+ function onMove(event) {
1367
+ if (state.mode !== 'picking') return
1368
+ pointer = { x: event.clientX, y: event.clientY }
1369
+ var el = elementAt(event.clientX, event.clientY)
1370
+ if (el === state.hover) return
1371
+ state.hover = el
1372
+ onViewportChange()
1373
+ }
1374
+
1375
+ function setMode(mode) {
1376
+ state.mode = mode
1377
+ if (mode !== 'writing') {
1378
+ state.selected = null
1379
+ state.hover = null
1380
+ pointer = null
1381
+ closeCard()
1382
+ }
1383
+ render()
1384
+ post('mode', { mode: state.mode, count: state.annotations.length })
1385
+ }
1386
+
1387
+ function post(type, payload) {
1388
+ if (type === 'ready' && !mounted) return
1389
+ var target = window.__DSH_ANNO__ && window.__DSH_ANNO__.parentOrigin
1390
+ if (!target) return
1391
+ try {
1392
+ parent.postMessage(
1393
+ Object.assign(
1394
+ { source: CHANNEL, type: type, url: window.__dshAnnoState ? window.__dshAnnoState().url : location.href, viewport: { w: window.innerWidth, h: window.innerHeight } },
1395
+ payload || {}
1396
+ ),
1397
+ target
1398
+ )
1399
+ } catch (e) {
1400
+ /* the panel is gone */
1401
+ }
1402
+ }
1403
+
1404
+ window.addEventListener('message', function (event) {
1405
+ // Source alone is not enough: any window that can reach this frame could
1406
+ // claim it. The message must also come from the harness origin.
1407
+ if (event.source !== parent || event.origin !== (window.__DSH_ANNO__ && window.__DSH_ANNO__.parentOrigin)) return
1408
+ var data = event.data
1409
+ if (!data || data.source !== HOST) return
1410
+ // Head-injected previews can receive mode and draft restoration before the
1411
+ // body is parsed. Apply those messages only after the layer has its children.
1412
+ if (!mounted) { pendingHostMessages.push(data); return }
1413
+ handleHostMessage(data)
1414
+ }, false)
1415
+
1416
+ function handleHostMessage(data) {
1417
+ if (data.type === 'busy') { state.busy = data.value; return }
1418
+ if (data.type === 'lang') { setLang(data.lang); return }
1419
+ if (data.type === 'restore') {
1420
+ state.annotations = Array.isArray(data.annotations) ? data.annotations : []
1421
+ liveElements.clear()
1422
+ save(); renderPins()
1423
+ state.savedDraft = data.draft && data.draft.detail && typeof data.draft.comment === 'string' ? data.draft : null
1424
+ if (state.savedDraft && state.savedDraft.existing && state.savedDraft.initialComment === undefined) {
1425
+ var original = state.annotations.find(function (ann) { return ann.id === state.savedDraft.id })
1426
+ state.savedDraft.initialComment = original ? original.comment : ''
1427
+ }
1428
+ if (state.savedDraft && !draftIsDirty(state.savedDraft, state.savedDraft.comment)) {
1429
+ state.savedDraft = null
1430
+ post('draft', { draft: null })
1431
+ }
1432
+ if (state.savedDraft) {
1433
+ var target = query(state.savedDraft.detail.selector)
1434
+ if (target && state.savedDraft.open !== false) openCard(state.savedDraft, target)
1435
+ }
1436
+ return
1437
+ }
1438
+ if (data.type === 'navigate') { history.go(data.delta); return }
1439
+ if (data.type === 'reload') { location.reload(); return }
1440
+ if (data.type === 'set-mode') setMode(data.mode)
1441
+ // The panel cannot always know whether a card is open; let the overlay —
1442
+ // which owns the mode — decide what "toggle" means right now.
1443
+ if (data.type === 'toggle-mode') setMode(state.mode === 'idle' ? 'picking' : 'idle')
1444
+ else if (data.type === 'resume-draft') {
1445
+ if (state.savedDraft) {
1446
+ var target = query(state.savedDraft.detail.selector)
1447
+ if (target) { target.scrollIntoView({ block: 'center', behavior: 'smooth' }); openCard(state.savedDraft, target) }
1448
+ else post('missing', { id: state.savedDraft.id })
1449
+ }
1450
+ } else if (data.type === 'discard-draft') {
1451
+ if (state.drafting && state.savedDraft && state.drafting.id === state.savedDraft.id) closeCard(false)
1452
+ state.savedDraft = null
1453
+ post('draft', { draft: null })
1454
+ } else if (data.type === 'focus' || data.type === 'view' || data.type === 'edit') {
1455
+ var ann = state.annotations.filter(function (a) {
1456
+ return a.id === data.id
1457
+ })[0]
1458
+ var el = ann ? elementFor(ann) : null
1459
+ if (!el) post('missing', { id: data.id })
1460
+ if (el) {
1461
+ el.scrollIntoView({ block: 'center', behavior: 'smooth' })
1462
+ if (data.type === 'view') showComment(ann, el)
1463
+ else if (data.type === 'edit') editComment(ann, el)
1464
+ else { state.selected = el; renderFrame() }
1465
+ }
1466
+ } else if (data.type === 'undo') {
1467
+ if (undo) { state.annotations.push(undo); undo = null; if (undoDraft) { state.savedDraft = undoDraft; undoDraft = null; post('draft', { draft: state.savedDraft }) } save(); renderPins(); post('changed', { annotations: state.annotations }) }
1468
+ } else if (data.type === 'remove') {
1469
+ undo = state.annotations.find(function (a) { return a.id === data.id }) || null
1470
+ if (state.viewing === data.id || (state.drafting && state.drafting.id === data.id)) closeCard()
1471
+ undoDraft = state.savedDraft && state.savedDraft.id === data.id ? state.savedDraft : null
1472
+ if (undoDraft) { state.savedDraft = null; post('draft', { draft: null }) }
1473
+ state.annotations = state.annotations.filter(function (a) {
1474
+ return a.id !== data.id
1475
+ })
1476
+ save()
1477
+ renderPins()
1478
+ post('changed', { annotations: state.annotations })
1479
+ } else if (data.type === 'clear') {
1480
+ setMode('idle')
1481
+ var removed = new Set(data.ids || state.annotations.map(function (a) { return a.id }))
1482
+ state.annotations = state.annotations.filter(function (a) { return !removed.has(a.id) })
1483
+ save()
1484
+ renderPins()
1485
+ post('changed', { annotations: state.annotations })
1486
+ } else if (data.type === 'ping') {
1487
+ post('ready', { annotations: state.annotations, path: location.pathname })
1488
+ }
1489
+ }
1490
+
1491
+ function isAppEvent(event) {
1492
+ return state.mode !== 'idle' && !root.contains(event.target)
1493
+ }
1494
+ window.addEventListener('mousemove', onMove, { capture: true, passive: true })
1495
+ window.addEventListener('click', function (event) {
1496
+ if (isAppEvent(event)) pick(event)
1497
+ }, true)
1498
+ // Keep app press handlers, links, focus and text selection from firing while
1499
+ // picking. Pointer defaults remain available for native touch scrolling.
1500
+ ;['pointerdown', 'pointerup'].forEach(function (type) {
1501
+ window.addEventListener(type, function (event) {
1502
+ if (type === 'pointerdown' && !root.contains(event.target)) post('interact')
1503
+ if (isAppEvent(event)) event.stopImmediatePropagation()
1504
+ }, true)
1505
+ })
1506
+ ;['mousedown', 'mouseup', 'dblclick', 'auxclick'].forEach(function (type) {
1507
+ window.addEventListener(type, function (event) {
1508
+ if (!isAppEvent(event)) return
1509
+ event.preventDefault()
1510
+ event.stopImmediatePropagation()
1511
+ }, true)
1512
+ })
1513
+ window.addEventListener('contextmenu', function (event) {
1514
+ if (!isAppEvent(event)) return
1515
+ event.preventDefault()
1516
+ event.stopImmediatePropagation()
1517
+ setMode('idle')
1518
+ }, true)
1519
+ window.addEventListener('click', function (event) {
1520
+ if (state.viewing && card && !card.contains(event.target) && !pinLayer.contains(event.target)) closeCard()
1521
+ }, true)
1522
+ window.addEventListener('keydown', function (event) {
1523
+ if (event.key === 'Escape' && state.viewing) { var id = state.viewing; closeCard(); focusPin(id); return }
1524
+ if (event.key === 'Escape' && !card) setMode('idle')
1525
+ }, true)
1526
+ /** Re-anchor stored annotations to their live elements: layout can shift
1527
+ * under a pin (content growing above it, a route change, a resize). */
1528
+ function resyncAnchors() {
1529
+ var changed = false
1530
+ state.annotations = state.annotations.map(function (ann) {
1531
+ var el = elementFor(ann)
1532
+ if (!el || !el.isConnected) return ann
1533
+ var rect = el.getBoundingClientRect()
1534
+ var doc = {
1535
+ x: Math.round(rect.x + window.scrollX),
1536
+ y: Math.round(rect.y + window.scrollY),
1537
+ w: Math.round(rect.width),
1538
+ h: Math.round(rect.height),
1539
+ }
1540
+ if (ann.doc && Math.abs(ann.doc.x - doc.x) < 1 && Math.abs(ann.doc.y - doc.y) < 1) return ann
1541
+ changed = true
1542
+ return Object.assign({}, ann, { doc: doc })
1543
+ })
1544
+ if (changed) save()
1545
+ }
1546
+
1547
+ // Capture phase: scroll events from inner containers do not bubble, but they
1548
+ // are delivered to window listeners registered for capture.
1549
+ var viewportChanged = false
1550
+ function onViewportChange() {
1551
+ viewportChanged = true
1552
+ }
1553
+ window.addEventListener('scroll', onViewportChange, { capture: true, passive: true })
1554
+ window.addEventListener('resize', function () {
1555
+ resyncAnchors()
1556
+ renderFrame()
1557
+ renderPins()
1558
+ })
1559
+
1560
+ function changePage() {
1561
+ var next = location.pathname + location.search + location.hash
1562
+ if (next === currentPage) return
1563
+ save()
1564
+ closeCard('silent')
1565
+ state.savedDraft = null
1566
+ currentPage = next
1567
+ state.annotations = load()
1568
+ state.hover = null
1569
+ state.selected = null
1570
+ liveElements.clear()
1571
+ undo = null
1572
+ setMode('idle')
1573
+ post('ready', { annotations: state.annotations })
1574
+ }
1575
+ ;['pushState', 'replaceState'].forEach(function (method) {
1576
+ var original = history[method]
1577
+ history[method] = function () {
1578
+ var result = original.apply(this, arguments)
1579
+ changePage()
1580
+ return result
1581
+ }
1582
+ })
1583
+ window.addEventListener('popstate', changePage)
1584
+ window.addEventListener('hashchange', changePage)
1585
+
1586
+ // Layout/transform animations do not necessarily emit scroll or resize.
1587
+ // Use one geometry pass for scrolling and animation; unchanged markup and
1588
+ // styles are left alone. Browsers pause rAF while the preview is backgrounded.
1589
+ function trackAnchors() {
1590
+ if (viewportChanged && state.mode === 'picking' && pointer) state.hover = elementAt(pointer.x, pointer.y)
1591
+ if (viewportChanged || state.hover || state.selected || state.annotations.length || card) updatePositions()
1592
+ viewportChanged = false
1593
+ requestAnimationFrame(trackAnchors)
1594
+ }
1595
+ requestAnimationFrame(trackAnchors)
1596
+ state.annotations = load()
1597
+ if (document.body) mount()
1598
+ else document.addEventListener('DOMContentLoaded', mount)
1599
+ })()
1600
+
1601
+ })()