dsh-selection-annotations 0.0.0-stage → 2.1.1

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 (48) hide show
  1. package/CHANGELOG.md +171 -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/locale/en.json +6 -0
  11. package/locale/zh.json +6 -0
  12. package/package.json +76 -6
  13. package/scripts/build.mjs +37 -0
  14. package/scripts/check-build.mjs +10 -0
  15. package/src/core/annotation-clipboard.js +93 -0
  16. package/src/core/annotation-utils.js +27 -0
  17. package/src/core/cards.js +502 -0
  18. package/src/core/config.js +91 -0
  19. package/src/core/constants.js +34 -0
  20. package/src/core/draft-codec.js +77 -0
  21. package/src/core/draft-store.js +85 -0
  22. package/src/core/hidden-payload.js +73 -0
  23. package/src/core/image-codec.js +111 -0
  24. package/src/core/jump-icon.js +25 -0
  25. package/src/core/locale.js +59 -0
  26. package/src/core/log.js +19 -0
  27. package/src/core/markdown.js +80 -0
  28. package/src/core/messages.js +311 -0
  29. package/src/core/note-tone.js +77 -0
  30. package/src/core/panel-render.js +315 -0
  31. package/src/core/payload.js +191 -0
  32. package/src/core/preview-bridge.js +216 -0
  33. package/src/core/remote-sync.js +206 -0
  34. package/src/core/scroll-trace.js +177 -0
  35. package/src/core/sent-store.js +148 -0
  36. package/src/core/session.js +60 -0
  37. package/src/core/settings.js +168 -0
  38. package/src/core/side-tab-state.js +30 -0
  39. package/src/core/source-capture.js +530 -0
  40. package/src/core/source-locate.js +220 -0
  41. package/src/core/source-resolve.js +89 -0
  42. package/src/core/styles.js +590 -0
  43. package/src/core/turn-anchor.js +54 -0
  44. package/src/core/util.js +55 -0
  45. package/src/core/uuid.js +23 -0
  46. package/src/core/web-picker.js +426 -0
  47. package/src/entry.js +22 -0
  48. package/src/plugin.js +8706 -0
@@ -0,0 +1,315 @@
1
+ import { el, button } from './util.js'
2
+ import { PLUGIN_BUILD } from './config.js'
3
+ import { paintNote } from './note-tone.js'
4
+
5
+ /**
6
+ * 批注总览面板:固定头(标题、说明、条数、清空)、可在其中拖拽排序的列表、
7
+ * 图片与指令设置区、末尾一行的构建号。所有批注数据通过 getAnnotations() 读取,不持有引用。
8
+ */
9
+ export function createPanelRenderer({
10
+ t,
11
+ getAnnotations,
12
+ clearAnnotations,
13
+ copyAll = () => {},
14
+ pasteAnnotations = () => {},
15
+ copyItem = () => {},
16
+ moveAnnotation,
17
+ openEditPopover,
18
+ jumpToQuote = () => {},
19
+ removeAnnotation,
20
+ sourceSummary,
21
+ openImageViewer,
22
+ imageSettingsRow,
23
+ instructionSettingsRow,
24
+ fallbackSettingsRow,
25
+ closePanel = () => {},
26
+ openSideTab = () => {},
27
+ isSideTabOpen = () => false, // true 时按钮变成「关闭」,图标与提示同步切换
28
+ noteView = () => null,
29
+ getHintText = () => '',
30
+ }) {
31
+ function render(panelEl) {
32
+ // 重绘会重建列表;保留滚动位置,拖拽补间时才不会因为整列表回顶而错位。
33
+ const body = panelEl.querySelector('.sa-panel-body')
34
+ const scrollTop = body === null ? 0 : body.scrollTop
35
+ paint(panelEl, { surface: 'panel' })
36
+ const nextBody = panelEl.querySelector('.sa-panel-body')
37
+ if (nextBody !== null) nextBody.scrollTop = scrollTop
38
+ }
39
+
40
+ /**
41
+ * 右侧标签页的渲染:与总览面板共用同一套 DOM 与事件,只去掉浮层的关闭按钮与
42
+ * 「在侧栏打开」按钮(它自己就在侧栏里),宽度与高度交给侧栏容器。
43
+ * host 是 React 渲染的容器,不能再被 paint 覆盖 className,所以面板另建一层。
44
+ */
45
+ function renderSide(host) {
46
+ // 侧栏靠定时轮询重绘,复用同一块面板节点:拖动结束后的重绘不会换掉闭包里的 panelEl。
47
+ let panel = host.firstElementChild
48
+ if (!(panel instanceof HTMLElement) || !panel.classList.contains('sa-panel')) {
49
+ host.textContent = ''
50
+ panel = document.createElement('div')
51
+ host.appendChild(panel)
52
+ }
53
+ const body = panel.querySelector('.sa-panel-body')
54
+ const scrollTop = body === null ? 0 : body.scrollTop
55
+ paint(panel, { surface: 'side' })
56
+ const nextBody = panel.querySelector('.sa-panel-body')
57
+ if (nextBody !== null) nextBody.scrollTop = scrollTop
58
+ }
59
+
60
+ /**
61
+ * 拖拽重排后的位移动画(FLIP):先按旧的屏幕位置把条目反向平移,再放开过渡让它回到新位置,
62
+ * 其余条目因此是滑过去而不是瞬间跳过去。动画结束后清掉内联样式,不留下过渡态。
63
+ */
64
+ function flipRows(panelEl, before) {
65
+ for (const row of panelEl.querySelectorAll('.sa-item')) {
66
+ const prev = before.get(row.dataset.id)
67
+ if (prev === undefined) continue
68
+ const next = row.getBoundingClientRect()
69
+ const dx = prev.left - next.left
70
+ const dy = prev.top - next.top
71
+ if (dx === 0 && dy === 0) continue
72
+ row.style.transition = 'none'
73
+ row.style.transform = `translate(${dx}px, ${dy}px)`
74
+ // 读一次布局,让反向平移先落地,再开始过渡。
75
+ void row.offsetWidth
76
+ const token = (row.__saFlipToken || 0) + 1
77
+ row.__saFlipToken = token
78
+ row.style.transition = 'transform 180ms cubic-bezier(.22,.61,.36,1)'
79
+ row.style.transform = ''
80
+ const finish = () => {
81
+ // 同一行再次参与拖动时 token 会变,旧动画的收尾不能清掉新动画。
82
+ if (row.__saFlipToken !== token) return
83
+ row.style.transition = ''
84
+ row.style.transform = ''
85
+ }
86
+ row.addEventListener('transitionend', finish, { once: true })
87
+ // 行被隐藏等情况下 transitionend 不触发,兜底清一次。
88
+ setTimeout(finish, 260)
89
+ }
90
+ }
91
+
92
+ function paint(panelEl, options) {
93
+ const side = options !== undefined && options.surface === 'side'
94
+ if (!side) panelEl.className = 'sa-panel'
95
+ else panelEl.className = 'sa-panel sa-panel-in-side'
96
+ const annotations = getAnnotations()
97
+ panelEl.textContent = ''
98
+
99
+ const panelHead = el('div', 'sa-panel-head')
100
+ panelHead.appendChild(el('span', 'sa-panel-title', t('panel.title')))
101
+ const meta = el('div', 'sa-panel-meta')
102
+ // 提示位始终带一个文本层:首次反馈也能播放淡入动画,重绘后当前反馈由状态回填。
103
+ const hintText = getHintText(side ? 'side' : 'panel') || t('panel.foot')
104
+ const hint = el('span', 'sa-panel-hint')
105
+ hint.appendChild(el('span', 'sa-hint-layer', hintText))
106
+ hint.title = hintText
107
+ meta.appendChild(hint)
108
+ meta.appendChild(el('span', 'sa-panel-count', t('panel.count', { n: annotations.length })))
109
+ if (annotations.length > 0) {
110
+ meta.appendChild(button('sa-foot-action', t('panel.copyAll'), () => copyAll(panelEl)))
111
+ }
112
+ meta.appendChild(button('sa-foot-action', t('panel.paste'), () => pasteAnnotations(panelEl)))
113
+ if (annotations.length > 0) {
114
+ meta.appendChild(button('sa-foot-action', t('panel.clear'), () => clearAnnotations()))
115
+ }
116
+ panelHead.appendChild(meta)
117
+ if (!side) {
118
+ const close = button('sa-panel-close', '×', () => closePanel())
119
+ close.setAttribute('aria-label', t('panel.close'))
120
+ close.title = t('panel.close')
121
+ panelHead.appendChild(close)
122
+ }
123
+ panelEl.appendChild(panelHead)
124
+ const panelBody = el('div', 'sa-panel-body')
125
+
126
+ if (annotations.length === 0) {
127
+ panelBody.appendChild(el('div', 'sa-panel-empty', t('panel.empty')))
128
+ }
129
+
130
+ let draggingId = null
131
+ for (const item of annotations) {
132
+ const row = el('div', 'sa-item')
133
+ row.draggable = true
134
+ row.dataset.id = item.id
135
+ row.addEventListener('dragstart', (event) => {
136
+ draggingId = item.id
137
+ event.dataTransfer.setData('text/plain', item.id)
138
+ event.dataTransfer.effectAllowed = 'move'
139
+ row.classList.add('sa-dragging')
140
+ })
141
+ row.addEventListener('dragend', () => {
142
+ draggingId = null
143
+ // 只摘掉拖拽态,别的 class 一律保留,避免重绘或动画期间把行样式整个覆盖掉。
144
+ for (const node of panelEl.querySelectorAll('.sa-item')) {
145
+ node.classList.remove('sa-dragging', 'sa-drop-before')
146
+ }
147
+ })
148
+ row.addEventListener('dragover', (event) => {
149
+ event.preventDefault()
150
+ event.dataTransfer.dropEffect = 'move'
151
+ // 拖动源自己身上不画插入线。
152
+ if (item.id === draggingId) return
153
+ // 快速划过时上一行可能来不及收到 dragleave,这里统一只保留当前插入线。
154
+ for (const node of panelEl.querySelectorAll('.sa-item')) {
155
+ if (node !== row) node.classList.remove('sa-drop-before')
156
+ }
157
+ row.classList.add('sa-drop-before')
158
+ })
159
+ row.addEventListener('dragleave', (event) => {
160
+ // 指针在行内子元素之间移动也会触发 dragleave,此时插入线应当保留。
161
+ if (event.relatedTarget instanceof Node && row.contains(event.relatedTarget)) return
162
+ row.classList.remove('sa-drop-before')
163
+ })
164
+ row.addEventListener('drop', (event) => {
165
+ event.preventDefault()
166
+ event.stopPropagation()
167
+ const draggedId = event.dataTransfer.getData('text/plain')
168
+ if (draggedId === '' || draggedId === item.id) return
169
+ // 先记下每行此刻的屏幕位置,重排后再按新位置做 FLIP 补间。
170
+ const before = new Map()
171
+ for (const node of panelEl.querySelectorAll('.sa-item')) {
172
+ before.set(node.dataset.id, node.getBoundingClientRect())
173
+ }
174
+ moveAnnotation(draggedId, item.id)
175
+ flipRows(panelEl, before)
176
+ })
177
+ const head = el('div', 'sa-item-head')
178
+ const grip = el('span', 'sa-drag-handle', '⠿')
179
+ grip.title = t('panel.drag')
180
+ grip.setAttribute('aria-label', t('panel.drag'))
181
+ head.appendChild(grip)
182
+ head.appendChild(el('span', 'sa-item-num', String(item.number)))
183
+ const summary = el('span', 'sa-item-src', sourceSummary(item))
184
+ summary.title = summary.textContent
185
+ head.appendChild(summary)
186
+ const actions = el('div', 'sa-item-actions')
187
+ actions.appendChild(button('sa-item-action', t('panel.copy'), () => copyItem(item, panelEl)))
188
+ actions.appendChild(button('sa-item-action', t('panel.edit'), () => openEditPopover(item.id, head)))
189
+ actions.appendChild(button('sa-item-action sa-danger', t('panel.delete'), () => removeAnnotation(item.id)))
190
+ head.appendChild(actions)
191
+ row.appendChild(head)
192
+ if (item.quote !== '') {
193
+ const q = el('div', 'sa-item-q')
194
+ const qHead = el('div', 'sa-item-q-head')
195
+ qHead.appendChild(el('div', 'sa-item-label', t('panel.quote')))
196
+ // 与拷贝/编辑/删除同一套按钮样式,同样随条目悬停才出现(规则在 .sa-item-jump)。
197
+ const jump = button('sa-item-action sa-item-jump', t('jump.label'), (event) => {
198
+ event.preventDefault()
199
+ event.stopPropagation()
200
+ jumpToQuote(item, jump)
201
+ })
202
+ jump.title = t('jump.hint')
203
+ if (item.source?.kind === 'file') jump.setAttribute('data-disabled', '1')
204
+ qHead.appendChild(jump)
205
+ q.appendChild(qHead)
206
+ const quote = el('div', 'sa-item-quote', item.quote)
207
+ quote.title = t('expand')
208
+ quote.addEventListener('click', () => {
209
+ quote.classList.toggle('sa-q-open')
210
+ })
211
+ q.appendChild(quote)
212
+ row.appendChild(q)
213
+ }
214
+ if (item.note !== '') {
215
+ const a = el('div', 'sa-item-a')
216
+ a.appendChild(el('div', 'sa-item-label', t('panel.note')))
217
+ const noteEl = el('div', 'sa-item-note')
218
+ paintNote(noteEl, item.note, noteView(item.note))
219
+ // 单击批注正文等同「编辑」按钮:打开同一条批注的编辑弹层。
220
+ noteEl.addEventListener('click', (event) => {
221
+ event.preventDefault()
222
+ event.stopPropagation()
223
+ openEditPopover(item.id, head)
224
+ })
225
+ a.appendChild(noteEl)
226
+ row.appendChild(a)
227
+ }
228
+ if (Array.isArray(item.images) && item.images.length > 0) {
229
+ const gallery = el('div', 'sa-item-images')
230
+ for (const image of item.images) {
231
+ const src =
232
+ typeof image?.url === 'string' && image.url !== ''
233
+ ? image.url
234
+ : typeof image?.preview === 'string' && image.preview !== ''
235
+ ? image.preview
236
+ : typeof image?.thumb === 'string' && image.thumb !== ''
237
+ ? image.thumb
238
+ : typeof image?.dataUrl === 'string' && image.dataUrl !== ''
239
+ ? image.dataUrl
240
+ : ''
241
+ if (src === '') continue
242
+ const thumb = document.createElement('img')
243
+ thumb.className = 'sa-item-thumb'
244
+ thumb.src = src
245
+ thumb.alt = typeof image.name === 'string' ? image.name : t('image.alt')
246
+ thumb.title = t('image.open')
247
+ thumb.style.cursor = 'zoom-in'
248
+ thumb.addEventListener('click', (event) => {
249
+ event.preventDefault()
250
+ event.stopPropagation()
251
+ openImageViewer(src, image.name)
252
+ })
253
+ gallery.appendChild(thumb)
254
+ }
255
+ if (gallery.childNodes.length > 0) row.appendChild(gallery)
256
+ }
257
+ if (typeof item.refineReason === 'string' && item.refineReason !== '') {
258
+ const why = el('div', 'sa-item-why', t('panel.refineFailed', { reason: item.refineReason }))
259
+ why.style.fontSize = '11px'
260
+ why.style.lineHeight = '1.5'
261
+ why.style.opacity = '0.8'
262
+ why.style.color = 'var(--dsw-alias-text-tertiary, GrayText)'
263
+ why.style.marginTop = '2px'
264
+ row.appendChild(why)
265
+ }
266
+ panelBody.appendChild(row)
267
+ }
268
+
269
+ panelBody.appendChild(imageSettingsRow())
270
+ panelBody.appendChild(instructionSettingsRow())
271
+ panelBody.appendChild(fallbackSettingsRow())
272
+ panelEl.appendChild(panelBody)
273
+
274
+ const panelFoot = el('div', 'sa-panel-foot')
275
+ const build = el('span', 'sa-build', `dsh-selection-annotations build.${PLUGIN_BUILD}`)
276
+ build.title = `dsh-selection-annotations build.${PLUGIN_BUILD}`
277
+ panelFoot.appendChild(build)
278
+ if (!side) {
279
+ // 同一个按钮两种动作:侧栏里已经有批注页签时是「关闭」,否则是「打开」。
280
+ const sideOpen = isSideTabOpen() === true
281
+ const sideAction = t(sideOpen ? 'panel.sideTabClose' : 'panel.sideTab')
282
+ const sideTab = button('sa-panel-side', '', openSideTab)
283
+ sideTab.title = sideAction
284
+ sideTab.setAttribute('aria-label', sideAction)
285
+ sideTab.setAttribute('aria-pressed', sideOpen ? 'true' : 'false')
286
+ const sideIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
287
+ sideIcon.setAttribute('viewBox', '0 0 16 16')
288
+ sideIcon.setAttribute('width', '14')
289
+ sideIcon.setAttribute('height', '14')
290
+ sideIcon.setAttribute('fill', 'none')
291
+ sideIcon.setAttribute('stroke', 'currentColor')
292
+ sideIcon.setAttribute('stroke-width', '1.2')
293
+ // 开合都用侧栏图标:右上角已有收起面板的叉号,这里再画叉号会重复;
294
+ // 是否已打开由 title、aria-label 与 aria-pressed 表达。
295
+ const sideIconPaths = ['M2.2 3.2h11.6v9.6H2.2z', 'M10.2 3.2v9.6']
296
+ for (const d of sideIconPaths) {
297
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
298
+ path.setAttribute('d', d)
299
+ sideIcon.appendChild(path)
300
+ }
301
+ sideTab.appendChild(sideIcon)
302
+ panelFoot.appendChild(sideTab)
303
+ }
304
+ panelEl.appendChild(panelFoot)
305
+ }
306
+
307
+ /** 拖到列表空白处(移到末尾)也走同一套位移动画:重排前先记下每一行的屏幕位置。 */
308
+ function snapshotRows(panelEl) {
309
+ const rects = new Map()
310
+ for (const row of panelEl.querySelectorAll('.sa-item')) rects.set(row.dataset.id, row.getBoundingClientRect())
311
+ return rects
312
+ }
313
+
314
+ return { render, renderSide, snapshotRows, animateRows: flipRows }
315
+ }
@@ -0,0 +1,191 @@
1
+ import { PAYLOAD_KIND } from './config.js'
2
+
3
+ /** 分段白名单:只抄这些字段,别让段上的临时缓存混进负载。*/
4
+ const MAX_PAYLOAD_SEGMENTS = 8
5
+
6
+ function finiteSpan(segment) {
7
+ if (segment === null || typeof segment !== 'object' || Array.isArray(segment)) return false
8
+ const { charStart, charEnd, quoteStart, quoteEnd } = segment
9
+ if (![charStart, charEnd, quoteStart, quoteEnd].every(Number.isFinite)) return false
10
+ if (charStart < 0 || charEnd <= charStart) return false
11
+ if (quoteStart < 0 || quoteEnd <= quoteStart) return false
12
+ return charEnd - charStart === quoteEnd - quoteStart
13
+ }
14
+
15
+ function payloadSegments(list) {
16
+ if (!Array.isArray(list)) return undefined
17
+ const out = []
18
+ for (const segment of list) {
19
+ if (out.length >= MAX_PAYLOAD_SEGMENTS) break
20
+ if (!finiteSpan(segment)) continue
21
+ const entry = {}
22
+ if (typeof segment.anchorKey === 'string') entry.anchorKey = segment.anchorKey
23
+ entry.textOrigin = segment.textOrigin === 'source' ? 'source' : 'rendered'
24
+ entry.charStart = segment.charStart
25
+ entry.charEnd = segment.charEnd
26
+ entry.quoteStart = segment.quoteStart
27
+ entry.quoteEnd = segment.quoteEnd
28
+ if (typeof segment.fingerprintBefore === 'string') entry.fingerprintBefore = segment.fingerprintBefore
29
+ if (typeof segment.fingerprintAfter === 'string') entry.fingerprintAfter = segment.fingerprintAfter
30
+ out.push(entry)
31
+ }
32
+ return out.length > 0 ? out : undefined
33
+ }
34
+
35
+ /**
36
+ * 批注负载与出处文案。
37
+ * 负载是一个自描述的 JSON 数据块:位置要能被程序化使用,所以用字段而不是自然语言描述。
38
+ */
39
+ export function createPayload({ t, instructionOf, uuidOfSent }) {
40
+ /** 已发送条目的 uuid 由调用方按台账解析;没解析到或解析出错都不写这个字段。 */
41
+ function sentUuidOf(source) {
42
+ if (typeof uuidOfSent !== 'function') return undefined
43
+ try {
44
+ const uuid = uuidOfSent(source)
45
+ return typeof uuid === 'string' && uuid !== '' ? uuid : undefined
46
+ } catch {
47
+ return undefined
48
+ }
49
+ }
50
+
51
+ function describeSource(source) {
52
+ if (source === null || source === undefined) return t('source.unknown')
53
+ if (source.kind === 'message') {
54
+ const role =
55
+ source.flowKind === 'user' || source.flowKind === 'steering' ? t('source.user') : t('source.assistant')
56
+ return t('source.message', { role, anchor: source.anchorKey || '-' })
57
+ }
58
+ if (source.kind === 'file') {
59
+ const path = source.path ?? t('source.pathUnknown')
60
+ let where = ''
61
+ if (Number.isFinite(source.lineStart)) {
62
+ where =
63
+ Number.isFinite(source.lineEnd) && source.lineEnd !== source.lineStart
64
+ ? t('source.lineRange', { a: source.lineStart, b: source.lineEnd })
65
+ : t('source.lineSingle', { n: source.lineStart })
66
+ }
67
+ return t('source.file', { path, where })
68
+ }
69
+ if (source.kind === 'web') {
70
+ return t('source.web', {
71
+ url: typeof source.path === 'string' && source.path !== '' ? source.path : t('source.pathUnknown'),
72
+ selector: typeof source.anchorKey === 'string' && source.anchorKey !== '' ? source.anchorKey : '-',
73
+ })
74
+ }
75
+ if (source.kind === 'reply') {
76
+ const fieldLabel =
77
+ { quote: t('label.quote'), note: t('label.note'), reason: t('label.reason'), next: t('label.next') }[
78
+ source.field
79
+ ] ?? t('source.replyField')
80
+ const anchor = `reply:${Number.isFinite(source.batchAt) ? source.batchAt : '-'}:${
81
+ Number.isFinite(source.index) ? source.index : '-'
82
+ }:${source.field || 'item'}`
83
+ const span =
84
+ Number.isFinite(source.charStart) && Number.isFinite(source.charEnd)
85
+ ? t('source.span', { a: source.charStart, b: source.charEnd })
86
+ : ''
87
+ return t('source.reply', {
88
+ index: Number.isFinite(source.index) ? source.index : '-',
89
+ field: fieldLabel,
90
+ anchor,
91
+ span,
92
+ })
93
+ }
94
+ if (source.kind === 'sent') {
95
+ const fieldLabel = { quote: t('label.quote'), note: t('label.note') }[source.field] ?? t('source.sentField')
96
+ const anchor = `sent:${source.anchorKey || '-'}:${Number.isFinite(source.index) ? source.index : '-'}:${
97
+ source.field || 'item'
98
+ }`
99
+ const span =
100
+ Number.isFinite(source.charStart) && Number.isFinite(source.charEnd)
101
+ ? t('source.span', { a: source.charStart, b: source.charEnd })
102
+ : ''
103
+ return t('source.sent', {
104
+ index: Number.isFinite(source.index) ? source.index : '-',
105
+ field: fieldLabel,
106
+ anchor,
107
+ span,
108
+ })
109
+ }
110
+ return t('source.selection')
111
+ }
112
+
113
+ function payloadSource(source) {
114
+ const out = { kind: source?.kind ?? 'dom' }
115
+ if (source?.kind === 'message') {
116
+ out.role = source.role ?? (source.flowKind === 'user' || source.flowKind === 'steering' ? 'user' : 'assistant')
117
+ if (typeof source.anchorKey === 'string' && source.anchorKey !== '') out.anchorKey = source.anchorKey
118
+ if (typeof source.flowKind === 'string' && source.flowKind !== '') out.flowKind = source.flowKind
119
+ // 轮次跟着条目走:宿主把那一轮卸下后,「跳到出处」还能拿它去点轮次导航。
120
+ if (Number.isFinite(source.turn)) out.turn = source.turn
121
+ } else if (source?.kind === 'file') {
122
+ if (typeof source.path === 'string' && source.path !== '') out.path = source.path
123
+ if (Number.isFinite(source.lineStart)) out.lineStart = source.lineStart
124
+ if (Number.isFinite(source.lineEnd)) out.lineEnd = source.lineEnd
125
+ } else if (source?.kind === 'reply') {
126
+ if (Number.isFinite(source.batchAt)) out.batchAt = source.batchAt
127
+ if (Number.isFinite(source.index)) out.index = source.index
128
+ if (typeof source.field === 'string' && source.field !== '') out.field = source.field
129
+ } else if (source?.kind === 'sent') {
130
+ if (typeof source.anchorKey === 'string' && source.anchorKey !== '') out.anchorKey = source.anchorKey
131
+ if (Number.isFinite(source.index)) out.index = source.index
132
+ if (typeof source.field === 'string' && source.field !== '') out.field = source.field
133
+ // 条目 uuid 只在知道时带上,让模型能定向答复那一条;不知道就不出现这个字段。
134
+ const uuid = typeof source.uuid === 'string' && source.uuid !== '' ? source.uuid : sentUuidOf(source)
135
+ if (typeof uuid === 'string' && uuid !== '') out.uuid = uuid
136
+ } else if (source?.kind === 'web') {
137
+ if (typeof source.anchorKey === 'string' && source.anchorKey !== '') out.anchorKey = source.anchorKey
138
+ if (typeof source.path === 'string' && source.path !== '') out.path = source.path
139
+ }
140
+ if (out.kind === 'file' || out.kind === 'message' || out.kind === 'reply' || out.kind === 'sent' || out.kind === 'web') {
141
+ out.textOrigin = source?.textOrigin === 'source' ? 'source' : 'rendered'
142
+ }
143
+ if (Number.isFinite(source?.charStart)) out.charStart = source.charStart
144
+ if (Number.isFinite(source?.charEnd)) out.charEnd = source.charEnd
145
+ // 分段是选中区间的按块切片:markConsumed 会把 payload 原样抄进台账,
146
+ // 白名单漏掉它,发送后这条批注就永久退回整段定位。
147
+ const segments = payloadSegments(source?.segments)
148
+ if (segments !== undefined) {
149
+ out.segments = segments
150
+ if (source?.segmentsTruncated === true) out.segmentsTruncated = true
151
+ }
152
+ return out
153
+ }
154
+
155
+ function buildPayload(items) {
156
+ let imageOrder = 0
157
+ const annotations = items.map((item) => {
158
+ const entry = {
159
+ index: item.number,
160
+ quote: item.quote,
161
+ note: item.note,
162
+ source: payloadSource(item.source),
163
+ }
164
+ // 条目 uuid 在捕获时生成,随批注一路带进数据块;旧数据没有就不写这个字段,
165
+ // 绝不输出 null 或空串。
166
+ const uuid = typeof item.uuid === 'string' && item.uuid !== '' ? item.uuid : undefined
167
+ if (uuid !== undefined) entry.uuid = uuid
168
+ const images = Array.isArray(item.images) ? item.images : []
169
+ if (images.length > 0) {
170
+ entry.images = images.map((image) => {
171
+ imageOrder += 1
172
+ return { order: imageOrder, name: image.name }
173
+ })
174
+ }
175
+ return entry
176
+ })
177
+ return JSON.stringify(
178
+ {
179
+ kind: PAYLOAD_KIND,
180
+ version: 1,
181
+ instruction: instructionOf(),
182
+ count: annotations.length,
183
+ annotations,
184
+ },
185
+ null,
186
+ 2,
187
+ )
188
+ }
189
+
190
+ return { describeSource, payloadSource, buildPayload }
191
+ }