dsh-selection-annotations 0.0.0-stage → 2.1.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +21 -0
  3. package/README.md +161 -3
  4. package/README.zh-CN.md +161 -0
  5. package/client.js +11136 -0
  6. package/cordis.patch.yml +3 -0
  7. package/icon.svg +7 -0
  8. package/lib/annotations-db.js +1157 -0
  9. package/lib/index.js +1304 -0
  10. package/package.json +74 -6
  11. package/scripts/build.mjs +37 -0
  12. package/scripts/check-build.mjs +10 -0
  13. package/src/core/annotation-clipboard.js +93 -0
  14. package/src/core/annotation-utils.js +27 -0
  15. package/src/core/cards.js +502 -0
  16. package/src/core/config.js +91 -0
  17. package/src/core/constants.js +34 -0
  18. package/src/core/draft-codec.js +77 -0
  19. package/src/core/draft-store.js +85 -0
  20. package/src/core/hidden-payload.js +73 -0
  21. package/src/core/image-codec.js +111 -0
  22. package/src/core/jump-icon.js +25 -0
  23. package/src/core/locale.js +59 -0
  24. package/src/core/log.js +19 -0
  25. package/src/core/markdown.js +80 -0
  26. package/src/core/messages.js +311 -0
  27. package/src/core/note-tone.js +77 -0
  28. package/src/core/panel-render.js +315 -0
  29. package/src/core/payload.js +191 -0
  30. package/src/core/preview-bridge.js +216 -0
  31. package/src/core/remote-sync.js +206 -0
  32. package/src/core/scroll-trace.js +177 -0
  33. package/src/core/sent-store.js +148 -0
  34. package/src/core/session.js +60 -0
  35. package/src/core/settings.js +168 -0
  36. package/src/core/side-tab-state.js +30 -0
  37. package/src/core/source-capture.js +530 -0
  38. package/src/core/source-locate.js +220 -0
  39. package/src/core/source-resolve.js +89 -0
  40. package/src/core/styles.js +590 -0
  41. package/src/core/turn-anchor.js +54 -0
  42. package/src/core/util.js +55 -0
  43. package/src/core/uuid.js +23 -0
  44. package/src/core/web-picker.js +426 -0
  45. package/src/entry.js +22 -0
  46. package/src/plugin.js +8706 -0
@@ -0,0 +1,216 @@
1
+ /**
2
+ * 给 dsh-better-sidebar 的 HTML 预览补上批注拾取。
3
+ *
4
+ * 它的预览是一个带 sandbox 的 iframe,父页面读不到里面的 DOM;但它会把 HTML
5
+ * 读成文本、用 URL.createObjectURL 生成 blob 再挂到 iframe 上。我们在同页劫持
6
+ * 这一次调用,把拾取脚本追加进 HTML,等 iframe 挂上后再把地址换成注入过的 blob。
7
+ * 只替换文件名带 editorHtml 的那类预览,mermaid、变更预览等其它 iframe 不动。
8
+ *
9
+ * 这是对它的私有实现做兼容:类名或生成方式变了会失效,届时按它的新实现调整。
10
+ */
11
+
12
+ import { PICK_SCRIPT } from './web-picker.js'
13
+
14
+ const BRIDGE = String.raw`(function () {
15
+ try {
16
+ Object.defineProperty(window, '__saPicked', {
17
+ configurable: true,
18
+ get: function () { return null },
19
+ set: function (value) {
20
+ if (value && window.parent !== window) window.parent.postMessage({ __saPreviewPick: value }, '*')
21
+ },
22
+ })
23
+ } catch (error) {}
24
+ window.addEventListener('message', function (event) {
25
+ var data = event.data
26
+ if (!data || !Array.isArray(data.__saPreviewNotes)) return
27
+ window.__saWebNotes = data.__saPreviewNotes
28
+ try { window.__saWebRender && window.__saWebRender() } catch (error) {}
29
+ })
30
+ })();`
31
+
32
+ const INJECTED_MARK = 'data-sa-preview-picker'
33
+
34
+ function injectIntoHtml(html) {
35
+ if (typeof html !== 'string' || html.includes(INJECTED_MARK)) return undefined
36
+ const script = `<script ${INJECTED_MARK}="1">${BRIDGE}\n${PICK_SCRIPT}</script>`
37
+ // 追加到文档最末尾:页面里可能在脚本字符串或模板中出现 </body>,
38
+ // 按第一个 </body> 插入会把脚本塞进字符串里,永远不执行。
39
+ return `${html}${script}`
40
+ }
41
+
42
+ export function createPreviewBridge({ onPick, getNotes }) {
43
+ let installed = false
44
+ let swapTimer = 0
45
+ let syncTimer = 0
46
+ let observer = null
47
+ const pending = new Map()
48
+ const attempted = new Set()
49
+ const originalCreate = URL.createObjectURL.bind(URL)
50
+
51
+ function isEditorFrame(frame) {
52
+ const className = typeof frame.className === 'string' ? frame.className : ''
53
+ return className.toLowerCase().includes('editorhtml') || frame.closest('[class*="editorHtml" i]') !== null
54
+ }
55
+
56
+ /**
57
+ * 兜底:不依赖 createObjectURL 的调用时机,直接读 iframe 当前的文档内容。
58
+ * 预览可能是 blob(它自己生成的),也可能是同源的路由地址;两种都能 fetch 到
59
+ * 原文,注入后再换成新的 blob。blob 文档的相对资源本来由它内联好,直接沿用。
60
+ */
61
+ async function hydrateFrame(frame, src) {
62
+ try {
63
+ const response = await fetch(src)
64
+ if (!response.ok) return
65
+ const text = await response.text()
66
+ if (text.includes(INJECTED_MARK)) return
67
+ const injected = injectIntoHtml(text)
68
+ if (injected === undefined) return
69
+ if (!frame.isConnected || frame.getAttribute('src') !== src) return
70
+ frame.setAttribute('src', originalCreate(new Blob([injected], { type: 'text/html;charset=utf-8' })))
71
+ } catch {}
72
+ }
73
+
74
+ function swapPreviews() {
75
+ for (const frame of document.querySelectorAll('iframe')) {
76
+ if (!isEditorFrame(frame)) continue
77
+ const src = frame.getAttribute('src') ?? ''
78
+ if (src === '') continue
79
+ const next = pending.get(src)
80
+ if (next !== undefined) {
81
+ pending.delete(src)
82
+ attempted.add(src)
83
+ attempted.add(next)
84
+ frame.setAttribute('src', next)
85
+ continue
86
+ }
87
+ if (attempted.has(src)) continue
88
+ if (!src.startsWith('blob:')) {
89
+ try {
90
+ if (new URL(src, location.href).origin !== location.origin) continue
91
+ } catch {
92
+ continue
93
+ }
94
+ }
95
+ attempted.add(src)
96
+ hydrateFrame(frame, src)
97
+ }
98
+ }
99
+
100
+ function installCreateObjectUrl() {
101
+ if (installed) return
102
+ installed = true
103
+ URL.createObjectURL = function patchedCreateObjectURL(blob) {
104
+ const url = originalCreate(blob)
105
+ try {
106
+ const type = blob !== null && blob !== undefined && typeof blob.type === 'string' ? blob.type : ''
107
+ if (type.startsWith('text/html') && typeof blob.text === 'function') {
108
+ blob
109
+ .text()
110
+ .then((text) => {
111
+ const injected = injectIntoHtml(text)
112
+ if (injected === undefined) return
113
+ const next = originalCreate(new Blob([injected], { type: 'text/html;charset=utf-8' }))
114
+ attempted.add(url)
115
+ pending.set(url, next)
116
+ swapPreviews()
117
+ })
118
+ .catch(() => {})
119
+ }
120
+ } catch {}
121
+ return url
122
+ }
123
+ }
124
+
125
+ function onMessage(event) {
126
+ const data = event.data
127
+ if (data === null || typeof data !== 'object') return
128
+ const picked = data.__saPreviewPick
129
+ if (picked === null || picked === undefined) return
130
+ let frame = null
131
+ for (const candidate of document.querySelectorAll('iframe')) {
132
+ if (candidate.contentWindow === event.source) {
133
+ frame = candidate
134
+ break
135
+ }
136
+ }
137
+ if (frame === null) return
138
+ const className = typeof frame.className === 'string' ? frame.className : ''
139
+ const host = frame.closest('[class*="editorHtml" i]') !== null
140
+ if (!className.toLowerCase().includes('editorhtml') && !host) return
141
+ const base = frame.getBoundingClientRect()
142
+ const inner = picked.rect ?? {}
143
+ const rect = {
144
+ left: Number(inner.left ?? 0),
145
+ top: Number(inner.top ?? 0),
146
+ width: Number(inner.width ?? 0),
147
+ height: Number(inner.height ?? 0),
148
+ }
149
+ const anchor = {
150
+ getBoundingClientRect: () => ({
151
+ left: base.left + rect.left,
152
+ top: base.top + rect.top,
153
+ width: rect.width,
154
+ height: rect.height,
155
+ right: base.left + rect.left + rect.width,
156
+ bottom: base.top + rect.top + rect.height,
157
+ }),
158
+ }
159
+ try {
160
+ onPick({
161
+ action: picked.action,
162
+ id: picked.id,
163
+ quote: typeof picked.label === 'string' ? picked.label : '',
164
+ selector: typeof picked.selector === 'string' ? picked.selector : '',
165
+ text: typeof picked.text === 'string' ? picked.text : '',
166
+ url: frame.title !== '' ? frame.title : (typeof picked.url === 'string' ? picked.url : ''),
167
+ rect,
168
+ anchor,
169
+ fromPreview: true,
170
+ })
171
+ } catch {}
172
+ }
173
+
174
+ function syncNotes() {
175
+ const notes = typeof getNotes === 'function' ? getNotes() : []
176
+ for (const frame of document.querySelectorAll('iframe')) {
177
+ const className = typeof frame.className === 'string' ? frame.className : ''
178
+ const host = frame.closest('[class*="editorHtml" i]') !== null
179
+ if (!className.toLowerCase().includes('editorhtml') && !host) continue
180
+ const path = frame.title
181
+ const list = notes
182
+ .filter((note) => note.path === path)
183
+ .map((note) => ({ id: note.id, selector: note.selector, adopt: note.adopt }))
184
+ try {
185
+ frame.contentWindow?.postMessage({ __saPreviewNotes: list }, '*')
186
+ } catch {}
187
+ }
188
+ }
189
+
190
+ function start() {
191
+ installCreateObjectUrl()
192
+ window.addEventListener('message', onMessage)
193
+ observer = new MutationObserver(() => swapPreviews())
194
+ observer.observe(document.documentElement, {
195
+ childList: true,
196
+ subtree: true,
197
+ attributes: true,
198
+ attributeFilter: ['src', 'class'],
199
+ })
200
+ swapTimer = window.setInterval(swapPreviews, 500)
201
+ syncTimer = window.setInterval(syncNotes, 800)
202
+ }
203
+
204
+ function dispose() {
205
+ if (!installed) return
206
+ window.removeEventListener('message', onMessage)
207
+ if (observer !== null) observer.disconnect()
208
+ observer = null
209
+ if (swapTimer !== 0) window.clearInterval(swapTimer)
210
+ if (syncTimer !== 0) window.clearInterval(syncTimer)
211
+ swapTimer = 0
212
+ syncTimer = 0
213
+ }
214
+
215
+ return { start, dispose }
216
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * 会话落盘同步:把草稿与已提交台账 PUT 到宿主路由,再 GET 回来。
3
+ * 连不上(离线 / 旧宿主)时只调用一次即失败,不影响本地功能。
4
+ * 新宿主另有「一批一建」的 POST 与按条 PATCH/DELETE;旧宿主没有这些接口时安静退回整份快照。
5
+ */
6
+ export function createRemoteSync(getSnapshot) {
7
+ let state
8
+ const queue = new Set()
9
+ let timer = null
10
+
11
+ const storeUrl = (sessionId) => `/selection-annotations/session/${encodeURIComponent(sessionId)}`
12
+ const entryUrl = (uuid) => `/selection-annotations/entry/${encodeURIComponent(uuid)}`
13
+ const batchUrl = (batchUuid) => `/selection-annotations/batch/${encodeURIComponent(batchUuid)}`
14
+
15
+ // 新接口可用性:undefined=还没试过,false=确认是旧宿主(之后不再尝试),true=可用。
16
+ let batchSupported
17
+ // 同一会话的整份快照要等这批 POST 落库后再推:同锚点键先推快照、后建批会造出重复批次。
18
+ const batchInflight = new Map()
19
+
20
+ /** 读一个会话的落盘记录;连不上或格式不对都返回 undefined(调用方退回本地)。 */
21
+ async function pull(sessionId) {
22
+ if (typeof fetch !== 'function') {
23
+ state = false
24
+ return undefined
25
+ }
26
+ try {
27
+ const response = await fetch(storeUrl(sessionId), { method: 'GET', headers: { accept: 'application/json' } })
28
+ if (response.status === 204) {
29
+ state = true
30
+ return null
31
+ }
32
+ if (!response.ok) {
33
+ state = false
34
+ return undefined
35
+ }
36
+ const data = await response.json()
37
+ state = true
38
+ return data !== null && typeof data === 'object' && !Array.isArray(data) ? data : null
39
+ } catch {
40
+ state = false
41
+ return undefined
42
+ }
43
+ }
44
+
45
+ const pending = new Set()
46
+ const inflight = new Map()
47
+
48
+ async function pushOnce(sessionId) {
49
+ if (typeof fetch !== 'function') return
50
+ const hold = batchInflight.get(sessionId)
51
+ if (hold !== undefined) {
52
+ try {
53
+ await hold
54
+ } catch {
55
+ /* 新接口失败也照常推整份快照。 */
56
+ }
57
+ }
58
+ try {
59
+ const response = await fetch(storeUrl(sessionId), {
60
+ method: 'PUT',
61
+ headers: { 'content-type': 'application/json' },
62
+ body: JSON.stringify(getSnapshot(sessionId)),
63
+ })
64
+ state = response.ok
65
+ } catch {
66
+ state = false
67
+ }
68
+ }
69
+
70
+ /** 每个会话串行推送:同一时间只允许一个 PUT 在飞,期间的新快照合并成一次补发。 */
71
+ function enqueue(sessionId) {
72
+ if (typeof sessionId !== 'string' || sessionId === '') return
73
+ pending.add(sessionId)
74
+ if (inflight.has(sessionId)) return
75
+ const task = (async () => {
76
+ while (pending.has(sessionId)) {
77
+ pending.delete(sessionId)
78
+ await pushOnce(sessionId)
79
+ }
80
+ })()
81
+ inflight.set(sessionId, task)
82
+ void task.finally(() => {
83
+ inflight.delete(sessionId)
84
+ if (pending.has(sessionId)) enqueue(sessionId)
85
+ })
86
+ }
87
+
88
+ /** 合并 600ms 内的写入,避免每敲一个字就发一次请求。 */
89
+ function schedule(sessionId) {
90
+ if (typeof sessionId !== 'string' || sessionId === '') return
91
+ queue.add(sessionId)
92
+ if (timer !== null) return
93
+ timer = window.setTimeout(() => {
94
+ timer = null
95
+ const ids = [...queue]
96
+ queue.clear()
97
+ for (const id of ids) enqueue(id)
98
+ }, 600)
99
+ }
100
+
101
+ async function readObject(response) {
102
+ const data = await response.json()
103
+ return data !== null && typeof data === 'object' && !Array.isArray(data) ? data : undefined
104
+ }
105
+
106
+ /**
107
+ * 新建一批已提交批注。旧宿主(404/405)只判一次,之后直接走整份快照。
108
+ * 失败统一返回 `{ ok: false, status, reason }`,调用方据此决定是否标记未同步;
109
+ * 成功返回后端对象并补 `ok: true` 与真实 HTTP `status`,`batch_uuid` / `items` 等字段原样保留。
110
+ */
111
+ async function createBatch(sessionId, body) {
112
+ const failed = (status, reason) => ({ ok: false, status, reason })
113
+ if (typeof sessionId !== 'string' || sessionId === '') return failed(0, 'no-session')
114
+ if (batchSupported === false) return failed(0, 'unsupported')
115
+ if (typeof fetch !== 'function') {
116
+ batchSupported = false
117
+ return failed(0, 'no-fetch')
118
+ }
119
+ // 同会话的批次按发送顺序串行:既保证 batch_seq 与页面顺序一致,也让整份快照排在所有 POST 之后。
120
+ const previous = batchInflight.get(sessionId)
121
+ const task = (previous ?? Promise.resolve()).then(async () => {
122
+ try {
123
+ const response = await fetch(`${storeUrl(sessionId)}/batch`, {
124
+ method: 'POST',
125
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
126
+ body: JSON.stringify(body),
127
+ })
128
+ if (response.status === 404 || response.status === 405) {
129
+ batchSupported = false
130
+ return failed(response.status, 'unsupported')
131
+ }
132
+ if (!response.ok) return failed(response.status, 'http')
133
+ const data = await readObject(response)
134
+ if (data === undefined) return failed(response.status, 'empty')
135
+ batchSupported = true
136
+ return { ...data, ok: true, status: response.status }
137
+ } catch {
138
+ return failed(0, 'network')
139
+ }
140
+ })
141
+ batchInflight.set(sessionId, task)
142
+ void task.finally(() => {
143
+ if (batchInflight.get(sessionId) === task) batchInflight.delete(sessionId)
144
+ })
145
+ return task
146
+ }
147
+
148
+ /**
149
+ * 回填批次字段:消息真正入库后才知道 turn 与可信锚点。
150
+ * 宿主只补空值,重复调用结果一致;失败就保持现状,整份快照推送照旧兜底。
151
+ */
152
+ async function patchBatch(batchUuid, body) {
153
+ if (typeof batchUuid !== 'string' || batchUuid === '') return undefined
154
+ if (typeof fetch !== 'function') return undefined
155
+ try {
156
+ const response = await fetch(batchUrl(batchUuid), {
157
+ method: 'PATCH',
158
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
159
+ body: JSON.stringify(body),
160
+ })
161
+ if (!response.ok) return undefined
162
+ return await readObject(response)
163
+ } catch {
164
+ return undefined
165
+ }
166
+ }
167
+
168
+ /** 按条目 uuid 写一条答复;旧宿主没有该接口时返回 undefined。 */
169
+ async function patchEntry(uuid, reply) {
170
+ if (typeof uuid !== 'string' || uuid === '') return undefined
171
+ if (typeof fetch !== 'function') return undefined
172
+ try {
173
+ const response = await fetch(entryUrl(uuid), {
174
+ method: 'PATCH',
175
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
176
+ body: JSON.stringify(reply),
177
+ })
178
+ if (!response.ok) return undefined
179
+ return await readObject(response)
180
+ } catch {
181
+ return undefined
182
+ }
183
+ }
184
+
185
+ /**
186
+ * 删除一条已提交批注;成功返回宿主响应(`{ok,uuid}`),失败返回 undefined。
187
+ * 宿主只接受带 `x-sa-explicit-delete: true` 的单条删除(否则 400):
188
+ * 批量删除通道因为一次误判把整会话批注删光,已经撤掉,这条单条通道必须自带明确意图。
189
+ */
190
+ async function deleteEntry(uuid) {
191
+ if (typeof uuid !== 'string' || uuid === '') return undefined
192
+ if (typeof fetch !== 'function') return undefined
193
+ try {
194
+ const response = await fetch(entryUrl(uuid), {
195
+ method: 'DELETE',
196
+ headers: { accept: 'application/json', 'x-sa-explicit-delete': 'true' },
197
+ })
198
+ if (!response.ok) return undefined
199
+ return await readObject(response)
200
+ } catch {
201
+ return undefined
202
+ }
203
+ }
204
+
205
+ return { pull, push: pushOnce, schedule, storeUrl, createBatch, patchBatch, patchEntry, deleteEntry }
206
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * 滚动追踪:把「谁改了会话区的滚动位置、谁触发了重绘」写成一行行 JSON,
3
+ * 攒在内存队列里每 1000ms 批量送到宿主的调试路由,最终落在
4
+ * `$DSH_HOME/selection-annotations/scroll-trace.log`。
5
+ *
6
+ * 只记录时间、数字和来源标记,不碰任何正文与批注内容。
7
+ * 每条行还会带上 setContext 给出的上下文(当前会话 id 与构建号),flush 时统一合并。
8
+ * 默认开启,控制台可用 `window.__dshSelectionAnnotations.traceScroll(false)` 关掉。
9
+ */
10
+ export const SCROLL_TRACE_ROUTE = '/selection-annotations/debug/trace'
11
+
12
+ /** 批量推送间隔;页面隐藏或卸载时另外立即冲刷一次。 */
13
+ const FLUSH_MS = 1000
14
+ /** 内存队列上限,超出丢最旧的。 */
15
+ const MAX_QUEUE = 500
16
+ /** 插件写入的标记存活时间:scroll 事件是异步派发的,写完不能立刻清掉。 */
17
+ const WRITE_MARK_TTL_MS = 1000
18
+
19
+ export function createScrollTrace() {
20
+ let enabled = true
21
+ let queue = []
22
+ let timer = null
23
+ /** 每条行附带的上下文(会话 id、构建号);flush 时求值,合并进该批每一行。 */
24
+ let contextFn = null
25
+ /** 卸载后停用;同一个实例再次 watch 时重新挂上页面级监听。 */
26
+ let stopped = false
27
+ let bound = false
28
+ /** 容器 → {src, top, at}:插件刚把 scrollTop 写到哪里,等下一次 scroll 事件来认领。 */
29
+ const marks = new WeakMap()
30
+ const watched = new WeakSet()
31
+ const lastTops = new WeakMap()
32
+
33
+ function clearTimer() {
34
+ if (timer === null) return
35
+ try {
36
+ window.clearTimeout(timer)
37
+ } catch {
38
+ /* 忽略 */
39
+ }
40
+ timer = null
41
+ }
42
+
43
+ function push(entry) {
44
+ if (stopped || !enabled) return
45
+ queue.push(entry)
46
+ if (queue.length > MAX_QUEUE) queue.splice(0, queue.length - MAX_QUEUE)
47
+ if (timer === null) {
48
+ timer = window.setTimeout(() => {
49
+ timer = null
50
+ flush()
51
+ }, FLUSH_MS)
52
+ }
53
+ }
54
+
55
+ /** 把队列里攒下的行一次性发出去;失败就丢,不重试也不报错。 */
56
+ function flush() {
57
+ clearTimer()
58
+ if (stopped || !enabled || queue.length === 0) return
59
+ // 上下文在冲刷时求值:同一批行共用一个会话与构建号,不必逐行重复调用。
60
+ let context = {}
61
+ if (contextFn !== null) {
62
+ try {
63
+ const value = contextFn()
64
+ if (value !== null && typeof value === 'object') context = value
65
+ } catch {
66
+ /* 上下文取不到就照常发本行,追踪不能反过来影响功能 */
67
+ }
68
+ }
69
+ // 上下文放在前面、行内同名字段优先:批次行自带的 session 不会被当前会话覆盖。
70
+ const lines = queue.map((entry) => JSON.stringify({ ...context, ...entry }))
71
+ queue = []
72
+ if (typeof fetch !== 'function') return
73
+ try {
74
+ const task = fetch(SCROLL_TRACE_ROUTE, {
75
+ method: 'POST',
76
+ headers: { 'content-type': 'application/json' },
77
+ body: JSON.stringify({ lines }),
78
+ keepalive: true,
79
+ })
80
+ if (task !== undefined && task !== null && typeof task.catch === 'function') task.catch(() => {})
81
+ } catch {
82
+ /* 调试通道,失败不影响功能 */
83
+ }
84
+ }
85
+
86
+ /** 记一次重绘调度:触发源由调用点给出。 */
87
+ function repaint(source) {
88
+ push({ t: Date.now(), kind: 'repaint', src: String(source ?? 'timer') })
89
+ }
90
+
91
+ /** 插件自己写 scrollTop 之前调用:标记这次写入的目标位置与来源。 */
92
+ function markWrite(container, source, expectedTop) {
93
+ if (stopped || container === null || container === undefined) return
94
+ marks.set(container, {
95
+ src: String(source),
96
+ top: Math.round(Number(expectedTop) || 0),
97
+ at: Date.now(),
98
+ })
99
+ }
100
+
101
+ /** 给滚动容器挂 passive 监听;同一个容器只挂一次。 */
102
+ function watch(container) {
103
+ if (container === null || container === undefined) return
104
+ if (typeof container.addEventListener !== 'function') return
105
+ // 卸载后又重新挂载:恢复追踪并重新绑页面级监听。
106
+ stopped = false
107
+ bindPageListeners()
108
+ if (watched.has(container)) return
109
+ watched.add(container)
110
+ container.addEventListener(
111
+ 'scroll',
112
+ () => {
113
+ if (stopped || !enabled) return
114
+ const now = Date.now()
115
+ const top = Math.round(Number(container.scrollTop) || 0)
116
+ const previous = lastTops.get(container)
117
+ lastTops.set(container, top)
118
+ let src = 'other'
119
+ const mark = marks.get(container)
120
+ if (mark !== undefined) {
121
+ // 位置对得上才认作插件写的;对不上说明有别人也动了,标记作废。
122
+ if (now - mark.at <= WRITE_MARK_TTL_MS && Math.abs(top - mark.top) <= 2) src = mark.src
123
+ marks.delete(container)
124
+ }
125
+ push({ t: now, kind: 'scroll', top, d: previous === undefined ? 0 : top - previous, src })
126
+ },
127
+ { passive: true },
128
+ )
129
+ }
130
+
131
+ /** 设置随每条 trace 一起发出的上下文;返回对象里的字段会合并进每一行。 */
132
+ function setContext(fn) {
133
+ contextFn = typeof fn === 'function' ? fn : null
134
+ }
135
+
136
+ function setEnabled(on) {
137
+ enabled = Boolean(on)
138
+ if (!enabled) {
139
+ queue = []
140
+ clearTimer()
141
+ }
142
+ }
143
+
144
+ function dispose() {
145
+ stopped = true
146
+ queue = []
147
+ clearTimer()
148
+ try {
149
+ window.removeEventListener('visibilitychange', onVisibilityChange)
150
+ window.removeEventListener('pagehide', onPageHide)
151
+ } catch {
152
+ /* 忽略 */
153
+ }
154
+ bound = false
155
+ }
156
+
157
+ /** 页面级监听只挂一次;dispose 之后再次 watch 会重新挂上。 */
158
+ function bindPageListeners() {
159
+ if (bound) return
160
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return
161
+ window.addEventListener('visibilitychange', onVisibilityChange)
162
+ window.addEventListener('pagehide', onPageHide)
163
+ bound = true
164
+ }
165
+
166
+ function onVisibilityChange() {
167
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') flush()
168
+ }
169
+
170
+ function onPageHide() {
171
+ flush()
172
+ }
173
+
174
+ bindPageListeners()
175
+
176
+ return { setEnabled, setContext, flush, push, repaint, markWrite, watch, dispose }
177
+ }