dsh-knit 0.25.0 → 0.27.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.
@@ -0,0 +1,1004 @@
1
+ /**
2
+ * 媒体全屏查看器 · 图内评论(v0.26)
3
+ *
4
+ * 用户要的是 Codex 画布那条闭环:图上落 pin → 写一句 → 发送 → 会话里收到
5
+ * 「图像 1:<身份>」+「1.(x:62.5%,y:31.0%)文案」。
6
+ *
7
+ * 这份测试分三层:
8
+ * ① 纯函数(坐标 / 归一化 / §四 文本 / 身份)—— 能真断言,不碰 DOM;
9
+ * ② 组件接线(评论按钮 / 落 pin / 编辑 / 删除 / 切图 / 投递)—— 用 harness 真跑组件;
10
+ * ③ 源码守卫(坐标必须来自 contentRect / 颜色走 token / 不落盘 / 重算机制在)。
11
+ *
12
+ * ⚠️ 坐标是命门:绝大多数 bug 都在「拿 stage 框算百分比」这一个岔路上,
13
+ * 所以第 ③ 层对 `commentClickPct` 做**形状守卫**,并逐条做过突变证伪(见 docs/image-comments.md)。
14
+ */
15
+ import test from 'node:test'
16
+ import assert from 'node:assert/strict'
17
+ import { readFileSync } from 'node:fs'
18
+ import { fileURLToPath } from 'node:url'
19
+
20
+ import { loadClientModule, createHarness, byClass, byExactClass, textOf } from './harness.mjs'
21
+
22
+ const harness = createHarness()
23
+ const React = globalThis.__knitReact
24
+ const h = React.createElement
25
+ const SOURCE = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
26
+ const client = loadClientModule()
27
+ const testApi = client.exports.__test
28
+ const { KnitBody } = testApi
29
+
30
+ /* ── 测试夹具 ─────────────────────────────────────────── */
31
+
32
+ /** 装一个假 fetch;只认 `/api/recent` 那份载荷。 */
33
+ function installFetch(responder) {
34
+ globalThis.fetch = async (url) => ({ json: async () => responder(url) })
35
+ }
36
+
37
+ /** 两张图 + 一个视频的媒体载荷(时间倒序:a.png 更新)。 */
38
+ function mediaPayload(overrides = {}) {
39
+ const now = Date.now()
40
+ return {
41
+ ok: true, root: '/p', total: 3, mode: 'time', topic: '', kind: 'media',
42
+ docs: [
43
+ { path: '/p/a.png', rel: 'a.png', name: 'a.png', title: 'a', kind: 'image', summary: '', size: 1024, mtimeMs: now - 60000, score: null },
44
+ { path: '/p/b.png', rel: 'b.png', name: 'b.png', title: 'b', kind: 'image', summary: '', size: 2048, mtimeMs: now - 120000, score: null },
45
+ { path: '/p/demo.mp4', rel: 'demo.mp4', name: 'demo.mp4', title: 'demo', kind: 'video', summary: '', size: 99999, mtimeMs: now - 9e7, score: null },
46
+ ],
47
+ ...overrides,
48
+ }
49
+ }
50
+
51
+ /** 挂到媒体档、双击第 openIndex 张图打开查看器。 */
52
+ async function mountLightbox(payload = mediaPayload(), openIndex = 0) {
53
+ installFetch((url) => {
54
+ if (url.includes('/api/attachments')) return { ok: true, items: [] }
55
+ if (url.includes('/api/doc')) return { ok: true, rel: 'x', title: 'x', text: '', truncated: false }
56
+ return payload
57
+ })
58
+ const render = () => harness.render(h(KnitBody, { sessionId: 's1' }))
59
+ harness.reset()
60
+ harness.seed(['', 'time', 'media'])
61
+ let nodes = render()
62
+ await harness.flush()
63
+ nodes = render()
64
+ const cards = byClass(nodes, 'knit-media-card').filter((n) => String(n.props['data-knit-rel']).endsWith('.png'))
65
+ assert.ok(cards[openIndex], '前提:有图片卡片')
66
+ cards[openIndex].props.onDoubleClick()
67
+ return { nodes: render(), render }
68
+ }
69
+
70
+ /** 点评论模式开关;返回最新的渲染。 */
71
+ function toggleComment(nodes) {
72
+ const button = nodes.find((n) => n && n.props && n.props['data-knit-comment-toggle'] === '1')
73
+ assert.ok(button, '工具条里应有评论按钮')
74
+ button.props.onClick({ stopPropagation() {} })
75
+ }
76
+
77
+ /** 当前渲染里的评论按钮(取最新一次渲染)。 */
78
+ function commentButton(nodes) {
79
+ return nodes.find((n) => n && n.props && n.props['data-knit-comment-toggle'] === '1')
80
+ }
81
+
82
+ /**
83
+ * 在图片内容框的 (xPct, yPct) 处点一下。
84
+ *
85
+ * 夹具固定成:img 盒 400×300、自然尺寸 1000×1000 ⇒ contain 后绘制矩形 300×300 @ (50,0)。
86
+ * 这样「点击位置 ↔ 百分比」可以手算,断言不是自证。
87
+ */
88
+ function clickImage(nodes, xPct, yPct) {
89
+ const img = {
90
+ naturalWidth: 1000,
91
+ naturalHeight: 1000,
92
+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 400, height: 300 }),
93
+ }
94
+ const stage = {
95
+ querySelector: () => img,
96
+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600 }),
97
+ }
98
+ const content = { left: 50, top: 0, width: 300, height: 300 }
99
+ let stopped = 0
100
+ const event = {
101
+ clientX: content.left + (content.width * xPct) / 100,
102
+ clientY: content.top + (content.height * yPct) / 100,
103
+ currentTarget: stage,
104
+ stopPropagation() { stopped += 1 },
105
+ }
106
+ byExactClass(nodes, 'knit-lightbox-stage')[0].props.onClick(event)
107
+ return stopped
108
+ }
109
+
110
+ /** 在评论输入框里改文字并回车保存;返回保存后的渲染。 */
111
+ function typeAndEnter(nodes, text, render) {
112
+ const input = byExactClass(nodes, 'knit-lightbox-editor-input')[0]
113
+ assert.ok(input, '前提:编辑框开着')
114
+ input.props.onChange({ target: { value: text } })
115
+ const next = byExactClass(render(), 'knit-lightbox-editor-input')[0]
116
+ assert.ok(next, '前提:改完文字编辑框还在')
117
+ next.props.onKeyDown({ key: 'Enter', preventDefault() {}, stopPropagation() {} })
118
+ return render()
119
+ }
120
+
121
+ /** 在节点树里递归找一个满足条件的节点。 */
122
+ function findNode(node, predicate) {
123
+ if (!node || typeof node !== 'object') return null
124
+ if (predicate(node)) return node
125
+ for (const child of node.children || []) {
126
+ const hit = findNode(child, predicate)
127
+ if (hit) return hit
128
+ }
129
+ return null
130
+ }
131
+
132
+ /** 取 `.knit-lightbox` 根(className 可能带 docked)。 */
133
+ function lightboxRoot(nodes) {
134
+ return byClass(nodes, 'knit-lightbox')
135
+ .find((n) => String(n.props.className).split(/\s+/).includes('knit-lightbox'))
136
+ }
137
+
138
+ /** 一条评论在渲染结果里的 pin 文本。 */
139
+ function pinLabels(nodes) {
140
+ return byExactClass(nodes, 'knit-lightbox-pin').map((n) => textOf(n))
141
+ }
142
+
143
+ /* ── ① 纯函数:坐标 ───────────────────────────────────── */
144
+
145
+ test('纯:contentRect 返回 contain 之后**真正画出图**的矩形(letterbox 去掉)', () => {
146
+ const { contentRect } = testApi
147
+
148
+ // 方图塞进 400×300 的横盒子 ⇒ 300×300,左边各留 50
149
+ assert.deepEqual(
150
+ contentRect({ left: 0, top: 0, width: 400, height: 300 }, { width: 1000, height: 1000 }),
151
+ { left: 50, top: 0, width: 300, height: 300 },
152
+ )
153
+ // 横图(2:1)塞进 400×300 ⇒ 400×200,上下各留 50
154
+ assert.deepEqual(
155
+ contentRect({ left: 10, top: 20, width: 400, height: 300 }, { width: 2000, height: 1000 }),
156
+ { left: 10, top: 70, width: 400, height: 200 },
157
+ )
158
+ // 竖图(1:2)塞进 400×300 ⇒ 150×300,左右各留 125
159
+ assert.deepEqual(
160
+ contentRect({ left: 0, top: 0, width: 400, height: 300 }, { width: 500, height: 1000 }),
161
+ { left: 125, top: 0, width: 150, height: 300 },
162
+ )
163
+ // cover / fill 也支持(虽然查看器只用 contain;这里钉住语义不混)
164
+ assert.deepEqual(
165
+ contentRect({ left: 0, top: 0, width: 400, height: 300 }, { width: 1000, height: 1000 }, 'fill'),
166
+ { left: 0, top: 0, width: 400, height: 300 },
167
+ )
168
+ assert.deepEqual(
169
+ contentRect({ left: 0, top: 0, width: 400, height: 300 }, { width: 1000, height: 1000 }, 'cover'),
170
+ { left: 0, top: -50, width: 400, height: 400 },
171
+ )
172
+ // 畸形输入 ⇒ null(不许抛)
173
+ assert.equal(contentRect(null, { width: 1, height: 1 }), null)
174
+ assert.equal(contentRect({ left: 0, top: 0, width: 400, height: 300 }, { width: 0, height: 0 }), null)
175
+ assert.equal(contentRect({ left: 0, top: 0, width: 0, height: 0 }, { width: 10, height: 10 }), null)
176
+ })
177
+
178
+ test('纯:pctFromPoint / pointFromPct 互逆,坐标夹到 0–100', () => {
179
+ const { pctFromPoint, pointFromPct } = testApi
180
+ const rect = { left: 100, top: 50, width: 400, height: 200 }
181
+
182
+ assert.deepEqual(pctFromPoint({ x: 100, y: 50 }, rect), { xPct: 0, yPct: 0 })
183
+ assert.deepEqual(pctFromPoint({ x: 500, y: 250 }, rect), { xPct: 100, yPct: 100 })
184
+ assert.deepEqual(pctFromPoint({ x: 350, y: 150 }, rect), { xPct: 62.5, yPct: 50 })
185
+
186
+ // 出界一律夹到 0–100(落点不会跑到图外面)
187
+ assert.deepEqual(pctFromPoint({ x: -999, y: 9999 }, rect), { xPct: 0, yPct: 100 })
188
+
189
+ // 逆运算:同一个百分比回到同一个点
190
+ const back = pointFromPct({ xPct: 62.5, yPct: 31 }, rect)
191
+ assert.equal(back.x, 100 + 400 * 0.625)
192
+ assert.equal(back.y, 50 + 200 * 0.31)
193
+ assert.deepEqual(pctFromPoint(back, rect), { xPct: 62.5, yPct: 31 })
194
+
195
+ // 畸形 ⇒ null
196
+ assert.equal(pctFromPoint(null, rect), null)
197
+ assert.equal(pctFromPoint({ x: 1, y: 1 }, null), null)
198
+ assert.equal(pctFromPoint({ x: NaN, y: 1 }, rect), null)
199
+ assert.equal(pointFromPct({ xPct: NaN, yPct: 1 }, rect), null)
200
+ })
201
+
202
+ test('纯:同一个百分比在**不同窗口宽度 / 不同 DPR** 下落在同一视觉位置', () => {
203
+ const { contentRect, pointFromPct, pctFromPoint } = testApi
204
+
205
+ // 同一张方图,两个窗口宽度下 img 盒不同(面板 320 / 900 时 contain 后的盒子也不同)
206
+ const wide = contentRect({ left: 0, top: 0, width: 800, height: 600 }, { width: 1000, height: 1000 })
207
+ const narrow = contentRect({ left: 0, top: 0, width: 360, height: 640 }, { width: 1000, height: 1000 })
208
+ const pct = { xPct: 48.3, yPct: 29.5 }
209
+ const a = pointFromPct(pct, wide)
210
+ const b = pointFromPct(pct, narrow)
211
+
212
+ // 「同一视觉位置」= 相对内容框的比例相同(不是绝对像素相同)
213
+ const rel = (point, rect) => ({ x: (point.x - rect.left) / rect.width, y: (point.y - rect.top) / rect.height })
214
+ const relA = rel(a, wide)
215
+ const relB = rel(b, narrow)
216
+ assert.ok(Math.abs(relA.x - relB.x) < 1e-9 && Math.abs(relA.y - relB.y) < 1e-9,
217
+ '同一百分比在两种宽度下相对内容框的比例必须相同')
218
+ // 再把它换算回百分比,逐字相同(这就是跨 DPR 也一致的原因:几何只用 CSS px,不读 devicePixelRatio)
219
+ assert.deepEqual(pctFromPoint(a, wide), { xPct: 48.3, yPct: 29.5 })
220
+ assert.deepEqual(pctFromPoint(b, narrow), { xPct: 48.3, yPct: 29.5 })
221
+ // 窄视口里图片上下留白(360 宽、640 高 ⇒ 绘制矩形 360×360 居中)—— 百分比仍相对这 360×360
222
+ assert.equal(narrow.width, 360)
223
+ assert.equal(narrow.top, 140)
224
+ })
225
+
226
+ test('纯:评论气泡贴着 pin,近右/近下会翻边并夹进视口(不再停到图片边上)', () => {
227
+ const { commentPopoverBox } = testApi
228
+ const view = { width: 1440, height: 900 }
229
+ const size = { width: 280, height: 172 }
230
+
231
+ // 常规位置:pin 在左上 ⇒ 气泡在右下、紧挨着 pin(不是跑到画面边角)
232
+ const normal = commentPopoverBox({ x: 200, y: 200 }, size, view)
233
+ assert.equal(normal.placement, 'right')
234
+ assert.equal(normal.side, 'below')
235
+ assert.ok(normal.left >= 200 && normal.top >= 200, '默认长在 pin 的右下方')
236
+
237
+ // 靠右 ⇒ 翻到 pin 左侧(Infini 分享包同一套规则)
238
+ const nearRight = commentPopoverBox({ x: 1320, y: 200 }, size, view)
239
+ assert.equal(nearRight.placement, 'left')
240
+ assert.ok(nearRight.left + size.width <= 1320, '翻边后不压住 pin')
241
+ assert.ok(nearRight.left >= 12, '也不许出左边')
242
+
243
+ // 靠下 ⇒ 翻到 pin 上方
244
+ const nearBottom = commentPopoverBox({ x: 200, y: 840 }, size, view)
245
+ assert.equal(nearBottom.side, 'above')
246
+ assert.ok(nearBottom.top + size.height <= 840)
247
+
248
+ // 极端角落 / 超小视口:一律夹在视口内(气泡不许半截出屏)
249
+ const corner = commentPopoverBox({ x: 1435, y: 895 }, size, view)
250
+ assert.ok(corner.left >= 12 && corner.left + size.width <= view.width - 12)
251
+ assert.ok(corner.top >= 12 && corner.top + size.height <= view.height - 12)
252
+ const tiny = commentPopoverBox({ x: 10, y: 10 }, size, { width: 320, height: 240 })
253
+ assert.ok(tiny.left >= 0 && tiny.top >= 0)
254
+ assert.ok(tiny.left + size.width <= 320 && tiny.top + size.height <= 240)
255
+
256
+ // 量不到 pin(测试替身 / 尺寸未就绪)⇒ 视口中心附近,仍在屏内
257
+ const noAnchor = commentPopoverBox(null, size, view)
258
+ assert.ok(noAnchor.left >= 12 && noAnchor.left + size.width <= view.width - 12)
259
+ })
260
+
261
+ /* ── ① 纯函数:数据 ───────────────────────────────────── */
262
+
263
+ test('纯:normalizeComments 畸形回空 / 夹取 / 编号连续 / 条数上限 / 不改入参', () => {
264
+ const { normalizeComments, COMMENT_MAX } = testApi
265
+
266
+ assert.deepEqual(normalizeComments(null), [])
267
+ assert.deepEqual(normalizeComments('nope'), [])
268
+ assert.deepEqual(normalizeComments([null, 1, 'x', {}]), [], '没有正文的条目一律丢掉')
269
+
270
+ // 夹取 + 连续编号(输入里编号乱写:7、9、3)
271
+ const cleaned = normalizeComments([
272
+ { n: 7, xPct: -20, yPct: 120, text: 'a' },
273
+ { n: 9, xPct: 50, yPct: 50, text: 'b' },
274
+ { n: 3, xPct: 200, yPct: -1, text: 'c' },
275
+ ])
276
+ assert.deepEqual(cleaned.map((c) => c.n), [1, 2, 3])
277
+ assert.deepEqual(cleaned.map((c) => [c.xPct, c.yPct]), [[0, 100], [50, 50], [100, 0]])
278
+
279
+ // 空文本 / 纯空白不占位(「空文本不保存」的数据层兜底)
280
+ assert.deepEqual(normalizeComments([{ n: 1, xPct: 1, yPct: 1, text: ' ' }]), [])
281
+
282
+ // 条数上限
283
+ const many = Array.from({ length: COMMENT_MAX + 10 }, (_, i) => ({ n: i + 1, xPct: 1, yPct: 1, text: `t${i}` }))
284
+ assert.equal(normalizeComments(many).length, COMMENT_MAX)
285
+
286
+ // 不改入参
287
+ const input = [{ n: 5, xPct: 10, yPct: 20, text: 'x' }]
288
+ normalizeComments(input)
289
+ assert.deepEqual(input, [{ n: 5, xPct: 10, yPct: 20, text: 'x' }])
290
+ })
291
+
292
+ test('纯:nextNumber 空表从 1 起、连续递增', () => {
293
+ const { nextNumber } = testApi
294
+ assert.equal(nextNumber([]), 1)
295
+ assert.equal(nextNumber(null), 1)
296
+ assert.equal(nextNumber([{ n: 1 }]), 2)
297
+ assert.equal(nextNumber([{ n: 1 }, { n: 2 }, { n: 3 }]), 4)
298
+ // 畸形编号先被归一化,所以「下一条」仍连续
299
+ assert.equal(nextNumber([{ n: 9, xPct: 1, yPct: 1, text: 'a' }]), 2)
300
+ })
301
+
302
+ test('纯:commentLines 严格照 §四 的文本格式(1 位小数、不截断、带身份)', () => {
303
+ const { commentLines } = testApi
304
+ const list = [
305
+ { n: 1, xPct: 62.5, yPct: 31, text: '右腿两条腿粘在一起了,分界要出来' },
306
+ { n: 2, xPct: 41.25, yPct: 57.44, text: '陶盆和虎尾兰对不上' },
307
+ ]
308
+
309
+ assert.deepEqual(commentLines(list, { name: 'G3.png', sha: 'd33f4f2a1234567890abcdef' }), [
310
+ '图像 1:G3.png(sha256 d33f4f2a1234)',
311
+ '1.(x:62.5%,y:31.0%)右腿两条腿粘在一起了,分界要出来',
312
+ '2.(x:41.3%,y:57.4%)陶盆和虎尾兰对不上',
313
+ ])
314
+
315
+ // 工作区图同时有 name 和 rel 时**优先 rel**(比文件名唯一,agent 能直接定位)
316
+ assert.equal(commentLines(list.slice(0, 1), { name: 'G3.png', rel: 'sub/G3.png' })[0], '图像 1:sub/G3.png')
317
+
318
+ // 编号跟着输入框附件顺序走:第二张附件就是「图像 2」
319
+ assert.equal(commentLines(list.slice(0, 1), { rel: 'b.png', index: 2 })[0], '图像 2:b.png')
320
+ assert.equal(commentLines(list.slice(0, 1), { rel: 'c.png', index: 0 })[0], '图像 1:c.png', '非法序号回落 1')
321
+
322
+ // 没有 sha(工作区图)⇒ 不带那对括号,但身份(rel)必须在
323
+ assert.deepEqual(commentLines(list.slice(0, 1), { rel: 'sub/G3.png' }), [
324
+ '图像 1:sub/G3.png',
325
+ '1.(x:62.5%,y:31.0%)右腿两条腿粘在一起了,分界要出来',
326
+ ])
327
+
328
+ // 文案原样,不截断(200 字整条都在)
329
+ const long = '长'.repeat(200)
330
+ const [line] = commentLines([{ n: 1, xPct: 0, yPct: 0, text: long }], { rel: 'x.png' }).slice(1)
331
+ assert.ok(line.endsWith(long), '用户输入一个字都不许截')
332
+ })
333
+
334
+ test('纯:身份锚定 —— 工作区图用 rel,对话图用附件 sha256', () => {
335
+ const { anchorIdFor, shaOfDoc } = testApi
336
+ const sha = 'a'.repeat(64)
337
+
338
+ assert.equal(anchorIdFor({ rel: 'sub/a.png' }), 'sub/a.png')
339
+ assert.equal(anchorIdFor({ rel: 'sha256:' + sha, attachmentId: 'sha256:' + sha }), 'sha256:' + sha)
340
+ assert.equal(anchorIdFor({ rel: 'sha256:' + sha }), 'sha256:' + sha, '伪文档只有 id 没有 attachmentId 时也要认')
341
+ assert.equal(anchorIdFor(null), '')
342
+
343
+ assert.equal(shaOfDoc({ attachmentId: 'sha256:' + sha }), sha)
344
+ assert.equal(shaOfDoc({ sha256: sha }), sha)
345
+ assert.equal(shaOfDoc({ rel: 'a.png' }), '', '工作区图没有哈希就空串,不瞎猜')
346
+ })
347
+
348
+ test('纯:commentsFor / withComments 按身份存、删空不留垃圾键、不改入参', () => {
349
+ const { commentsFor, withComments } = testApi
350
+
351
+ const empty = {}
352
+ const one = withComments(empty, 'a.png', [{ n: 1, xPct: 10, yPct: 20, text: 'x' }])
353
+ assert.deepEqual(empty, {}, '不许原地改 state')
354
+ assert.deepEqual(commentsFor(one, 'a.png'), [{ n: 1, xPct: 10, yPct: 20, text: 'x' }])
355
+ assert.deepEqual(commentsFor(one, 'b.png'), [])
356
+
357
+ const cleared = withComments(one, 'a.png', [])
358
+ assert.equal(Object.prototype.hasOwnProperty.call(cleared, 'a.png'), false, '删到空要删键')
359
+ assert.deepEqual(commentsFor(null, 'a.png'), [])
360
+ })
361
+
362
+ test('纯:composerState 数出输入框里已有几张附件、有没有正文', () => {
363
+ const { composerState } = testApi
364
+ const card = {
365
+ querySelectorAll: () => [
366
+ { src: 'blob:http://x/1' },
367
+ { src: 'https://x/y', parentElement: { className: 'abc_thumbnail' } },
368
+ { src: 'https://x/icon', parentElement: { className: 'icon' } },
369
+ ],
370
+ }
371
+ const input = {
372
+ textContent: '已有正文',
373
+ closest: (selector) => (selector === '[data-composer-card]' ? card : null),
374
+ }
375
+ const doc = { querySelector: (selector) => (selector === '[data-composer-input]' ? input : null) }
376
+ assert.deepEqual(composerState(doc), { count: 2, hasText: true })
377
+ assert.deepEqual(composerState({ querySelector: () => null }), { count: 0, hasText: false })
378
+ assert.deepEqual(composerState(null), { count: 0, hasText: false })
379
+ input.textContent = ' '
380
+ assert.deepEqual(composerState(doc), { count: 2, hasText: false }, '纯空白不算正文')
381
+ })
382
+
383
+ /* ── ① 纯函数:投递通道 ───────────────────────────────── */
384
+
385
+ test('投递:合成 paste 到 [data-composer-input],文本逐字进输入框', async () => {
386
+ const { deliverCommentText } = testApi
387
+ const events = []
388
+ const input = {
389
+ textContent: '',
390
+ focus() {},
391
+ dispatchEvent(event) {
392
+ events.push(event)
393
+ this.textContent = event.clipboardData.getData('text/plain')
394
+ return false // 宿主接住了(preventDefault)
395
+ },
396
+ }
397
+ const doc = {
398
+ querySelector: (selector) => (selector === '[data-composer-input]' ? input : null),
399
+ dispatchEvent: () => true,
400
+ }
401
+ const text = '图像 1:a.png\n1.(x:50.0%,y:50.0%)腿粘住了'
402
+ const result = await deliverCommentText(text, { document: doc, window: {} })
403
+
404
+ assert.deepEqual(result, { ok: true, via: 'paste', image: false })
405
+ assert.equal(input.textContent, text, '投进输入框的是 §四 的原文')
406
+ assert.equal(events.length, 1, '只投递一次(不自动发送、不重复粘贴)')
407
+ assert.equal(events[0].type, 'paste')
408
+ assert.equal(events[0].clipboardData.getData('text/plain'), text)
409
+ })
410
+
411
+ test('投递:评论要**把原图一起**作为附件 paste 进输入框(不只是文字)', async () => {
412
+ const { deliverCommentText } = testApi
413
+ const events = []
414
+ const input = {
415
+ textContent: '',
416
+ focus() {},
417
+ dispatchEvent(event) {
418
+ events.push(event)
419
+ this.textContent = event.clipboardData.getData('text/plain')
420
+ return false
421
+ },
422
+ }
423
+ const doc = { querySelector: () => input, dispatchEvent: () => true }
424
+ const made = []
425
+ class FakeFile {
426
+ constructor(parts, name, options) {
427
+ this.parts = parts
428
+ this.name = name
429
+ this.type = options.type
430
+ made.push(this)
431
+ }
432
+ }
433
+ const fakeFetch = async (url) => {
434
+ assert.match(url, /^\/knit\/api\/(raw|attachment)\?/, '只读同源图片地址')
435
+ return { ok: true, blob: async () => ({ size: 4, type: 'image/png' }) }
436
+ }
437
+ const text = '图像 1:sub/a.png\n1.(x:50.0%,y:50.0%)腿粘住了'
438
+ const result = await deliverCommentText(text, {
439
+ document: doc,
440
+ window: {},
441
+ fetch: fakeFetch,
442
+ File: FakeFile,
443
+ attachment: { src: '/knit/api/raw?sessionId=s1&rel=sub%2Fa.png', name: 'a.png' },
444
+ })
445
+ assert.deepEqual(result, { ok: true, via: 'paste', image: true })
446
+ assert.equal(made.length, 1, '读成 File')
447
+ assert.equal(made[0].name, 'a.png')
448
+ assert.equal(made[0].type, 'image/png')
449
+ assert.equal(events.length, 1, '图片与文本同一个 paste 事件')
450
+ assert.equal(events[0].clipboardData.items[0].kind, 'file')
451
+ assert.equal(events[0].clipboardData.items[0].getAsFile(), made[0], 'File 放进剪贴板 items')
452
+ assert.equal(events[0].clipboardData.getData('text/plain'), text)
453
+ assert.equal(input.textContent, text)
454
+ })
455
+
456
+ test('投递:输入框已有正文时,新评论以**独立段落**投递(前面空两行)', async () => {
457
+ const { deliverCommentText } = testApi
458
+ const events = []
459
+ const input = {
460
+ textContent: '上一段',
461
+ focus() {},
462
+ dispatchEvent(event) {
463
+ events.push(event)
464
+ this.textContent = `${this.textContent}${event.clipboardData.getData('text/plain')}`
465
+ return false
466
+ },
467
+ }
468
+ const doc = { querySelector: () => input, dispatchEvent: () => true }
469
+ const result = await deliverCommentText('图像 2:b.png', { document: doc, window: {} })
470
+ assert.deepEqual(result, { ok: true, via: 'paste', image: false })
471
+ assert.equal(events[0].clipboardData.getData('text/plain'), '\n\n图像 2:b.png', '前面空两行 = 新段落')
472
+ assert.equal(input.textContent, '上一段\n\n图像 2:b.png')
473
+ })
474
+
475
+ test('投递:图片读不到时仍投文本,并如实报告 image:false(不假装附件成功)', async () => {
476
+ const { deliverCommentText } = testApi
477
+ const input = { textContent: '', focus() {}, dispatchEvent() { this.textContent = 'x'; return false } }
478
+ const doc = { querySelector: () => input, dispatchEvent: () => true }
479
+ const result = await deliverCommentText('x', {
480
+ document: doc,
481
+ window: {},
482
+ fetch: async () => { throw new Error('boom') },
483
+ File: class {},
484
+ attachment: { src: '/knit/api/raw?rel=a.png', name: 'a.png' },
485
+ })
486
+ assert.deepEqual(result, { ok: true, via: 'paste', image: false })
487
+ })
488
+
489
+ test('投递:输入框没接住 ⇒ document drop;再不行 ⇒ clipboard', async () => {
490
+ const { deliverCommentText } = testApi
491
+
492
+ // paste 返回 true 且文本没变 ⇒ 视为没接住
493
+ const input = { textContent: '', focus() {}, dispatchEvent: () => true }
494
+ const dropEvents = []
495
+ const docDrop = {
496
+ querySelector: () => input,
497
+ dispatchEvent(event) { dropEvents.push(event); return false },
498
+ }
499
+ assert.deepEqual(await deliverCommentText('x', { document: docDrop, window: {} }), { ok: true, via: 'drop', image: false })
500
+ assert.equal(dropEvents[0].type, 'drop')
501
+ assert.equal(dropEvents[0].dataTransfer.getData('text/plain'), 'x')
502
+
503
+ // drop 也没人接 ⇒ clipboard
504
+ const written = []
505
+ const docClipboard = {
506
+ querySelector: () => input,
507
+ dispatchEvent: () => true,
508
+ }
509
+ const win = { navigator: { clipboard: { writeText: async (value) => { written.push(value) } } } }
510
+ assert.deepEqual(await deliverCommentText('y', { document: docClipboard, window: win }), { ok: true, via: 'clipboard', image: false })
511
+ assert.deepEqual(written, ['y'])
512
+ })
513
+
514
+ test('投递:全部通道都不可用 ⇒ 明确失败,不假装成功', async () => {
515
+ const { deliverCommentText } = testApi
516
+ assert.deepEqual(await deliverCommentText('', { document: null, window: null }), { ok: false, via: 'none', image: false })
517
+ const doc = { querySelector: () => null, dispatchEvent: () => true }
518
+ assert.deepEqual(await deliverCommentText('z', { document: doc, window: {} }), { ok: false, via: 'none', image: false })
519
+ })
520
+
521
+ /** 只挂媒体面板(不打开任何查看器),用于验证 hover → 面板画布这条入口。 */
522
+ async function mountMediaPanel(payload = mediaPayload()) {
523
+ installFetch((url) => {
524
+ if (url.includes('/api/attachments')) return { ok: true, items: [] }
525
+ if (url.includes('/api/doc')) return { ok: true, rel: 'x', title: 'x', text: '', truncated: false }
526
+ return payload
527
+ })
528
+ const { KnitBody } = testApi
529
+ harness.reset()
530
+ harness.seed(['', 'time', 'media'])
531
+ const render = () => harness.render(h(KnitBody, { sessionId: 's1' }))
532
+ let nodes = render()
533
+ await harness.flush()
534
+ nodes = render()
535
+ return { nodes, render }
536
+ }
537
+
538
+ /* ── ② 组件接线 ───────────────────────────────────────── */
539
+
540
+ test('评论:工具条二态入口 —— 进入后出现评论栏与落 pin 层,退出后一起消失', async () => {
541
+ const { nodes, render } = await mountLightbox()
542
+ let current = nodes
543
+ assert.equal(byExactClass(current, 'knit-lightbox-comments').length, 0, '默认不该有评论栏')
544
+
545
+ const button = commentButton(current)
546
+ assert.ok(button, '工具条里应有评论按钮')
547
+ assert.equal(textOf(button), '评论')
548
+ assert.equal(button.props['aria-pressed'], 'false')
549
+
550
+ toggleComment(current)
551
+ current = render()
552
+ assert.equal(byExactClass(current, 'knit-lightbox-comments').length, 1, '进入评论模式后底部浮出评论栏')
553
+ assert.equal(byExactClass(current, 'knit-lightbox-pins').length, 1, '图片上盖一层 pin 覆盖层')
554
+ assert.equal(textOf(commentButton(current)), '退出评论')
555
+ assert.equal(commentButton(current).props['aria-pressed'], 'true')
556
+
557
+ toggleComment(current)
558
+ current = render()
559
+ assert.equal(byExactClass(current, 'knit-lightbox-comments').length, 0)
560
+ assert.equal(byExactClass(current, 'knit-lightbox-pins').length, 0)
561
+ assert.equal(textOf(commentButton(current)), '评论')
562
+ })
563
+
564
+ test('评论:点图片落 pin(1..n)→ 就地输入 → Enter 保存;空文本不落;Esc 取消', async () => {
565
+ const { nodes, render } = await mountLightbox()
566
+ toggleComment(nodes)
567
+ let current = render()
568
+
569
+ // 第一次点:落一个 pin,并就地弹出输入框
570
+ const stopped = clickImage(current, 50, 50)
571
+ assert.equal(stopped, 1, '评论模式里点图必须 stopPropagation(否则查看器被点没了)')
572
+ current = render()
573
+ assert.equal(byExactClass(current, 'knit-lightbox-editor').length, 1, '落 pin 即就地弹输入框')
574
+ const drafts = byClass(current, 'knit-lightbox-pin')
575
+ .filter((n) => String(n.props.className).split(/\s+/).includes('knit-lightbox-pin'))
576
+ assert.equal(drafts.length, 1, '草稿 pin 要画在点下去的那一点上')
577
+ assert.match(String(drafts[0].props.className), /draft/, '它是草稿态,不是已保存的 pin')
578
+ assert.equal(textOf(drafts[0]), '1', '草稿 pin 的编号就是即将保存的 n')
579
+ assert.equal(byExactClass(current, 'knit-lightbox-comment-row').length, 0, '还没保存,评论栏里不出现')
580
+ const editorText = textOf(byExactClass(current, 'knit-lightbox-editor')[0])
581
+ assert.match(editorText, /新评论/, '气泡有标题(与 Infini 的「新标注」同一套语汇)')
582
+ assert.match(editorText, /x 50\.0% · y 50\.0%/, '气泡里直接写这条评论的坐标')
583
+ assert.match(editorText, /0\/200/, '气泡里带字数计数')
584
+
585
+ // 空文本回车 ⇒ 不保存
586
+ const emptyInput = byExactClass(current, 'knit-lightbox-editor-input')[0]
587
+ emptyInput.props.onKeyDown({ key: 'Enter', preventDefault() {}, stopPropagation() {} })
588
+ current = render()
589
+ assert.equal(byExactClass(current, 'knit-lightbox-editor').length, 0)
590
+ assert.equal(byClass(current, 'knit-lightbox-pin')
591
+ .filter((n) => String(n.props.className).split(/\s+/).includes('knit-lightbox-pin')).length, 0,
592
+ '空文本不落 pin(草稿也一起收掉)')
593
+
594
+ // 再点一次:写一句,回车
595
+ clickImage(current, 50, 50)
596
+ current = render()
597
+ current = typeAndEnter(current, '右腿两条腿粘在一起了,分界要出来', render)
598
+ assert.deepEqual(pinLabels(current), ['1'], '编号从 1 起')
599
+ assert.equal(byExactClass(current, 'knit-lightbox-comment-row').length, 1, '评论栏里多一行')
600
+ assert.match(textOf(current), /右腿两条腿粘在一起了/, '评论栏显示文字摘要')
601
+
602
+ // 第二次落点:编号 2
603
+ clickImage(current, 20, 30)
604
+ current = render()
605
+ current = typeAndEnter(current, '陶盆和虎尾兰对不上', render)
606
+ assert.deepEqual(pinLabels(current), ['1', '2'], '编号连续')
607
+
608
+ // Esc 取消一个新草稿:不落
609
+ clickImage(current, 80, 80)
610
+ current = render()
611
+ byExactClass(current, 'knit-lightbox-editor-input')[0].props.onKeyDown({ key: 'Escape', preventDefault() {}, stopPropagation() {} })
612
+ current = render()
613
+ assert.equal(byExactClass(current, 'knit-lightbox-editor').length, 0)
614
+ assert.deepEqual(pinLabels(current), ['1', '2'], 'Esc 取消不新增')
615
+
616
+ // pin 的编号/身份在 DOM 上;像素位置由 contentViewport(同一绘制矩形)算 ——
617
+ // 替身没有 DOM,几何本身由下面的 commentPopoverBox / contentRect 纯函数真断言。
618
+ const pins = byExactClass(current, 'knit-lightbox-pin')
619
+ assert.deepEqual(pins.map((pin) => pin.props['data-knit-comment-pin']), ['1', '2'])
620
+ })
621
+
622
+ test('评论:点已有 pin 重编辑;删除后编号仍然连续', async () => {
623
+ const { nodes, render } = await mountLightbox()
624
+ toggleComment(nodes)
625
+ let current = render()
626
+ for (const [x, y, text] of [[10, 10, '第一条'], [40, 40, '第二条'], [70, 70, '第三条']]) {
627
+ clickImage(current, x, y)
628
+ current = render()
629
+ current = typeAndEnter(current, text, render)
630
+ }
631
+ assert.deepEqual(pinLabels(current), ['1', '2', '3'])
632
+
633
+ // 点第 2 个 pin → 编辑框里是原文
634
+ const pin = byExactClass(current, 'knit-lightbox-pin')[1]
635
+ pin.props.onClick({ stopPropagation() {} })
636
+ current = render()
637
+ const input = byExactClass(current, 'knit-lightbox-editor-input')[0]
638
+ assert.equal(input.props.value, '第二条')
639
+ assert.match(textOf(byExactClass(current, 'knit-lightbox-editor')[0]), /评论 2/, '编辑已有评论时标题带编号')
640
+ input.props.onChange({ target: { value: '第二条(改)' } })
641
+ current = render()
642
+ byExactClass(current, 'knit-lightbox-editor-input')[0]
643
+ .props.onKeyDown({ key: 'Enter', preventDefault() {}, stopPropagation() {} })
644
+ current = render()
645
+ assert.match(textOf(current), /第二条(改)/)
646
+
647
+ // 删中间一条 → 剩下的重新从 1 连续编号(发送文本里不许出现 1. 3.)
648
+ const del = byExactClass(current, 'knit-lightbox-comment-del')[1]
649
+ del.props.onClick()
650
+ current = render()
651
+ assert.deepEqual(pinLabels(current), ['1', '2'])
652
+ const rows = byExactClass(current, 'knit-lightbox-comment-row')
653
+ assert.match(textOf(rows[1]), /第三条/, '删第 2 条后,原第 3 条补到第 2 位')
654
+
655
+ // 编辑框里的「删除」也真的能删
656
+ byExactClass(current, 'knit-lightbox-pin')[0].props.onClick({ stopPropagation() {} })
657
+ current = render()
658
+ const editor = byExactClass(current, 'knit-lightbox-editor')[0]
659
+ const deleteButton = findNode(editor, (node) => node && node.type === 'button' && /删除/.test(textOf(node)))
660
+ assert.ok(deleteButton, '编辑框里应有删除')
661
+ deleteButton.props.onClick()
662
+ current = render()
663
+ assert.deepEqual(pinLabels(current), ['1'])
664
+ })
665
+
666
+ test('评论:切图各自保留、编号各自从 1 起;退出查看器再进评论仍在(本会话内存)', async () => {
667
+ const { nodes, render } = await mountLightbox()
668
+ toggleComment(nodes)
669
+ let current = render()
670
+
671
+ clickImage(current, 50, 50)
672
+ current = render()
673
+ current = typeAndEnter(current, 'a 图的问题', render)
674
+ assert.deepEqual(pinLabels(current), ['1'])
675
+
676
+ // 切到第二张图:评论栏是空的(各图各自保留)
677
+ byClass(current, 'knit-lightbox-thumb')[1].props.onClick()
678
+ current = render()
679
+ assert.equal(byExactClass(current, 'knit-lightbox-comment-row').length, 0, 'b 图还没有评论')
680
+ assert.equal(byExactClass(current, 'knit-lightbox-comments-empty').length, 1)
681
+
682
+ clickImage(current, 30, 40)
683
+ current = render()
684
+ current = typeAndEnter(current, 'b 图的问题', render)
685
+ assert.deepEqual(pinLabels(current), ['1'], 'b 图自己的编号也从 1 起')
686
+
687
+ // 切回 a 图:它那条还在
688
+ byClass(current, 'knit-lightbox-thumb')[0].props.onClick()
689
+ current = render()
690
+ assert.deepEqual(pinLabels(current), ['1'])
691
+ assert.match(textOf(current), /a 图的问题/)
692
+
693
+ // Esc 关掉查看器,再双击打开:评论仍在(内存;硬刷新才丢)
694
+ const rootOf = (n) => byClass(n, 'knit-root')[0]
695
+ rootOf(current).props.onKeyDownCapture({ key: 'Escape', preventDefault() {}, stopPropagation() {} })
696
+ current = render()
697
+ assert.equal(byExactClass(current, 'knit-lightbox').length, 0, '已关闭')
698
+ await harness.flush()
699
+ current = render()
700
+
701
+ byClass(current, 'knit-media-card').filter((n) => String(n.props['data-knit-rel']).endsWith('.png'))[0].props.onDoubleClick()
702
+ current = render()
703
+ assert.equal(byExactClass(current, 'knit-lightbox').length, 1, '重新打开查看器')
704
+ toggleComment(current)
705
+ current = render()
706
+ assert.match(textOf(current), /a 图的问题/, '退出再进,评论仍在(P0 内存)')
707
+ assert.deepEqual(pinLabels(current), ['1'])
708
+ })
709
+
710
+ test('评论:发送只**投递** §四 文本到输入框,不自动发送', async () => {
711
+ const { nodes, render } = await mountLightbox()
712
+ toggleComment(nodes)
713
+ let current = render()
714
+ clickImage(current, 50, 50)
715
+ current = render()
716
+ current = typeAndEnter(current, '右腿两条腿粘在一起了,分界要出来', render)
717
+
718
+ const events = []
719
+ const composer = {
720
+ textContent: '',
721
+ focus() {},
722
+ dispatchEvent(event) {
723
+ events.push(event)
724
+ this.textContent = event.clipboardData.getData('text/plain')
725
+ return false
726
+ },
727
+ }
728
+ globalThis.document = {
729
+ // ensureStyle / KnitGlyph 在渲染期会问这两个;给个空壳免得把测试自己的假 document 弄崩
730
+ getElementById: () => ({ id: 'dsh-knit-style' }),
731
+ createElement: () => ({ style: {}, setAttribute() {} }),
732
+ head: { appendChild() {} },
733
+ querySelector: (selector) => (selector === '[data-composer-input]' ? composer : null),
734
+ dispatchEvent: () => true,
735
+ }
736
+ const made = []
737
+ class FakeFile {
738
+ constructor(parts, name, options) { this.parts = parts; this.name = name; this.type = options.type; made.push(this) }
739
+ }
740
+ const realFetch = globalThis.fetch
741
+ const realFile = globalThis.File
742
+ globalThis.fetch = async () => ({ ok: true, blob: async () => ({ size: 4, type: 'image/png' }) })
743
+ globalThis.File = FakeFile
744
+ try {
745
+ const send = current.find((n) => n && n.props && n.props['data-knit-comment-send'] === '1')
746
+ assert.ok(send, '评论栏里应有发送按钮')
747
+ await send.props.onClick()
748
+ current = render()
749
+ } finally {
750
+ delete globalThis.document
751
+ globalThis.fetch = realFetch
752
+ if (realFile === undefined) delete globalThis.File
753
+ else globalThis.File = realFile
754
+ }
755
+
756
+ assert.equal(composer.textContent, [
757
+ '图像 1:a.png',
758
+ '1.(x:50.0%,y:50.0%)右腿两条腿粘在一起了,分界要出来',
759
+ ].join('\n'), '输入框里逐字是 §四 的文本')
760
+ assert.equal(events.length, 1, '只 dispatch 了一次 paste —— 没有任何「自动发送」')
761
+ assert.equal(events[0].type, 'paste')
762
+ assert.equal(made.length, 1, '原图被读成 File 一起投递')
763
+ assert.equal(events[0].clipboardData.items[0].getAsFile(), made[0], '图片在同一个 paste 事件里')
764
+ assert.match(textOf(current), /已投进输入框/, '评论栏里如实说投递成功')
765
+ })
766
+
767
+ test('评论:输入框里的 Esc / 方向键归输入框,不许被查看器的捕获阶段抢走', async () => {
768
+ const { nodes, render } = await mountLightbox()
769
+ toggleComment(nodes)
770
+ let current = render()
771
+ clickImage(current, 50, 50)
772
+ current = render()
773
+ assert.equal(byExactClass(current, 'knit-lightbox-editor').length, 1, '前提:编辑框开着')
774
+
775
+ // 模拟「事件 target 落在编辑框里」:查看器根的捕获处理器必须直接放行
776
+ const calls = { prevented: 0, stopped: 0 }
777
+ const inEditor = {
778
+ isContentEditable: false,
779
+ closest: (selector) => (selector === '[data-knit-comment-editor]' ? { nodeType: 1 } : null),
780
+ }
781
+ byClass(current, 'knit-root')[0].props.onKeyDownCapture({
782
+ key: 'Escape',
783
+ target: inEditor,
784
+ preventDefault() { calls.prevented += 1 },
785
+ stopPropagation() { calls.stopped += 1 },
786
+ })
787
+ assert.deepEqual(calls, { prevented: 0, stopped: 0 }, '编辑框内的 Esc 不许被查看器拦')
788
+ assert.equal(byExactClass(render(), 'knit-lightbox').length, 1, '查看器没被关掉')
789
+ })
790
+
791
+ test('评论:非评论模式下的既有语义没变(点图不关、点图外关、Esc 关)', async () => {
792
+ const { nodes, render } = await mountLightbox()
793
+ const box = byExactClass(nodes, 'knit-lightbox')[0]
794
+ let stopped = 0
795
+ byExactClass(nodes, 'knit-lightbox-img')[0].props.onClick({ stopPropagation() { stopped += 1 } })
796
+ assert.equal(stopped, 1, '默认模式点图仍然 stopPropagation')
797
+ assert.equal(byExactClass(render(), 'knit-lightbox').length, 1)
798
+ box.props.onClick()
799
+ assert.equal(byExactClass(render(), 'knit-lightbox').length, 0, '点图片以外照旧关闭')
800
+ })
801
+
802
+ test('评论:悬停大图点一下 → 在 **Knit 面板里**打开画布(不盖会话),且评论模式已开', async () => {
803
+ const { nodes, render } = await mountMediaPanel()
804
+ const card = byClass(nodes, 'knit-media-card').find((n) => String(n.props['data-knit-rel']).endsWith('.png'))
805
+ card.props.onMouseEnter({ currentTarget: null })
806
+ harness.tick()
807
+ let current = render()
808
+ const shot = byExactClass(current, 'knit-shot')[0]
809
+ assert.ok(shot, '前提:悬停大图出来了')
810
+ assert.equal(shot.props['data-knit-hover-shot'], '1')
811
+ assert.match(textOf(shot), /评论/, '浮窗上写着「评论」——它现在是入口')
812
+
813
+ shot.props.onClick({ stopPropagation() {} })
814
+ current = render()
815
+ const box = lightboxRoot(current)
816
+ assert.ok(box, '打开的是画布')
817
+ assert.match(String(box.props.className), /docked/, '默认落在面板画布(docked),不是整屏')
818
+ assert.equal(box.props['aria-modal'], 'false', '面板画布不是模态:会话不被盖住')
819
+ assert.equal(byExactClass(current, 'knit-canvas').length, 1, '画布挂在 Knit 面板里')
820
+ assert.equal(byExactClass(current, 'knit-lightbox-rail').length, 0, '面板画布不需要左侧缩略图带')
821
+ assert.equal(byExactClass(current, 'knit-lightbox-comments').length, 1, '直接进评论模式:底部评论栏在')
822
+ assert.match(textOf(current), /点一下图片上的位置/, '空态要教用户怎么开始(不是只写「还没有评论」)')
823
+ assert.ok(current.find((n) => n && n.props && n.props['data-knit-canvas-next'] === '1'), '画布里有「下一张」')
824
+ assert.ok(current.find((n) => n && n.props && n.props['data-knit-canvas-prev'] === '1'), '画布里有「上一张」')
825
+ const imgSrc = () => byExactClass(current, 'knit-lightbox-img')[0].props.src
826
+ const first = imgSrc()
827
+ current.find((n) => n && n.props && n.props['data-knit-canvas-next'] === '1')
828
+ .props.onClick({ stopPropagation() {} })
829
+ current = render()
830
+ assert.notEqual(imgSrc(), first, '「下一张」能换图')
831
+ const second = imgSrc()
832
+ lightboxRoot(current).props.onWheel({ deltaY: 120, target: null })
833
+ current = render()
834
+ assert.notEqual(imgSrc(), second, '画布上滚轮也能换图(不用只能返回)')
835
+
836
+ // 面板画布里点图 → 落 pin → 写 → 保存(与整屏共用同一套逻辑)
837
+ clickImage(current, 40, 60)
838
+ current = render()
839
+ typeAndEnter(current, '面板画布里也能直接评', render)
840
+ current = render()
841
+ assert.deepEqual(pinLabels(current), ['1'])
842
+ assert.equal(byExactClass(current, 'knit-lightbox-comment-row').length, 1)
843
+ })
844
+
845
+ test('评论:画布 ↔ 全屏 切换不丢评论;返回回到媒体网格', async () => {
846
+ const { nodes, render } = await mountMediaPanel()
847
+ const card = byClass(nodes, 'knit-media-card').find((n) => String(n.props['data-knit-rel']).endsWith('.png'))
848
+ card.props.onMouseEnter({ currentTarget: null })
849
+ harness.tick()
850
+ let current = render()
851
+ byExactClass(current, 'knit-shot')[0].props.onClick({ stopPropagation() {} })
852
+ current = render()
853
+ clickImage(current, 30, 40)
854
+ current = render()
855
+ typeAndEnter(current, '切换不丢', render)
856
+ current = render()
857
+ assert.deepEqual(pinLabels(current), ['1'])
858
+
859
+ const full = current.find((n) => n && n.props && n.props['data-knit-canvas-fullscreen'] === '1')
860
+ assert.ok(full, '画布工具条里有「全屏」')
861
+ full.props.onClick({ stopPropagation() {} })
862
+ current = render()
863
+ assert.doesNotMatch(String(lightboxRoot(current).props.className), /docked/, '切到整屏')
864
+ assert.equal(lightboxRoot(current).props['aria-modal'], 'true')
865
+ assert.deepEqual(pinLabels(current), ['1'], '评论跟着走,不丢')
866
+
867
+ const dock = current.find((n) => n && n.props && n.props['data-knit-canvas-dock'] === '1')
868
+ assert.ok(dock, '整屏工具条里有「画布」')
869
+ dock.props.onClick({ stopPropagation() {} })
870
+ current = render()
871
+ assert.match(String(lightboxRoot(current).props.className), /docked/)
872
+ assert.deepEqual(pinLabels(current), ['1'], '切回来评论仍在')
873
+
874
+ const back = current.find((n) => n && n.props && n.props['data-knit-canvas-back'] === '1')
875
+ assert.ok(back, '画布工具条里有「返回」')
876
+ back.props.onClick({ stopPropagation() {} })
877
+ current = render()
878
+ assert.equal(byExactClass(current, 'knit-lightbox').length, 0, '返回关掉画布')
879
+ assert.ok(byClass(current, 'knit-media-card').length > 0, '回到媒体网格')
880
+ })
881
+
882
+ /* ── ③ 源码守卫 ───────────────────────────────────────── */
883
+
884
+ test('守卫:落点百分比只能从 contentRect 算 —— 不许出现拿 stage 宽度算的代码', () => {
885
+ const start = SOURCE.indexOf('function commentClickPct')
886
+ assert.ok(start > 0, 'commentClickPct 必须存在(它是落点唯一的入口)')
887
+ const end = SOURCE.indexOf('\n /**', start + 1)
888
+ const body = SOURCE.slice(start, end > start ? end : undefined)
889
+
890
+ assert.match(body, /contentRect\(/, '落点必须先算「实际绘制矩形」')
891
+ assert.match(body, /pctFromPoint\(/, '百分比必须由 pctFromPoint 从矩形算')
892
+ assert.ok(!/stage/i.test(body), 'commentClickPct 里根本不该出现 stage(拿 stage 算 = pin 整体偏移)')
893
+ assert.ok(!/devicePixelRatio/.test(body), '几何只用 CSS px,不读 DPR')
894
+
895
+ // 渲染层:pin 的像素位置 = 同一个绘制矩形(commentBox)上的百分比,不另算一套
896
+ assert.match(SOURCE, /commentBox\.left \+ \(commentBox\.width \* item\.xPct\) \/ 100/,
897
+ 'pin 必须用 commentBox(与落点同一个绘制矩形)算像素位置')
898
+ assert.match(SOURCE, /commentBox\.top \+ \(commentBox\.height \* item\.yPct\) \/ 100/,
899
+ '纵坐标同理')
900
+ })
901
+
902
+ test('守卫:pin 与编辑气泡共用绘制矩形,且缩放/滚动会重算', () => {
903
+ assert.match(SOURCE, /const rect = contentViewportOf\(img\)/,
904
+ '几何必须来自 contentViewportOf(图片实际绘制矩形)')
905
+ assert.match(SOURCE, /srect = surface\.getBoundingClientRect\(\)/,
906
+ '整屏 / 面板画布共用同一套「表面坐标」,不能各算各的')
907
+ assert.match(SOURCE, /typeof ResizeObserver !== 'undefined'/, '必须用 ResizeObserver 跟踪尺寸变化')
908
+ assert.match(SOURCE, /addEventListener\('resize', measureCommentBox\)/, '窗口缩放要重算')
909
+ assert.match(SOURCE, /addEventListener\('scroll', measureCommentBox, true\)/, '滚动也要重算')
910
+ })
911
+
912
+ test('守卫:评论 UI 的颜色一律走语义 token,零硬编码色值', () => {
913
+ const start = SOURCE.indexOf('const CSS = `') + 'const CSS = `'.length
914
+ const css = SOURCE.slice(start, SOURCE.indexOf('`', start))
915
+ const from = css.indexOf('.knit-lightbox-pins{')
916
+ const to = css.indexOf('.knit-preview{', from)
917
+ assert.ok(from > 0 && to > from, '评论那段 CSS 必须找得到')
918
+ // 注释里提到色值不算(比如「别写 #fff」这种说明),只看真实声明
919
+ const block = css.slice(from, to).replace(/\/\*[\s\S]*?\*\//g, '')
920
+
921
+ assert.ok(!/#[0-9a-fA-F]{3,8}\b/.test(block), '评论样式里不许出现 hex 色值')
922
+ assert.ok(!/\brgba?\(/.test(block), '评论样式里不许出现 rgb / rgba')
923
+ assert.ok(!/\bhsla?\(/.test(block), '评论样式里不许出现 hsl / hsla')
924
+ assert.match(block, /var\(--dsw-alias-brand-primary-new-colorprimary-new-color\)/,
925
+ 'pin 用品牌强调色 token')
926
+ })
927
+
928
+ test('守卫:工具条 / 关闭 / 缩略图带 / 评论栏必须压在 stage 之上(真机踩过)', () => {
929
+ const start = SOURCE.indexOf('const CSS = `') + 'const CSS = `'.length
930
+ const css = SOURCE.slice(start, SOURCE.indexOf('`', start))
931
+ const rule = (selector) => {
932
+ const match = css.match(new RegExp(selector + '\\{([^}]*)\\}'))
933
+ assert.ok(match, `应有 ${selector} 的样式`)
934
+ return match[1]
935
+ }
936
+ // stage 为了摆 pin 覆盖层必须是 positioned;一旦它 positioned,DOM 里排在它前面的
937
+ // 工具条就会被 stage 盖住(真机上「评论」按钮点不到,点了是点图 = 关查看器)。
938
+ assert.match(rule('\\.knit-lightbox-stage'), /position:relative/)
939
+ for (const selector of ['\\.knit-lightbox-tools', '\\.knit-lightbox-close', '\\.knit-lightbox-rail', '\\.knit-lightbox-comments']) {
940
+ assert.match(rule(selector), /z-index:\s*\d+/, `${selector} 必须显式抬到 stage 之上`)
941
+ }
942
+ })
943
+
944
+ test('守卫:客户端热换(HMR)后样式表必须跟着更新 —— 不能「有 style 元素就跳过」', () => {
945
+ const start = SOURCE.indexOf('function ensureStyle')
946
+ assert.ok(start > 0, 'ensureStyle 必须存在')
947
+ const end = SOURCE.indexOf('\n /**', start + 1)
948
+ const body = SOURCE.slice(start, end > start ? end : undefined)
949
+ // 旧版只有 `if (document.getElementById(STYLE_ID)) return`:HMR 只换 JS 不换页面时,
950
+ // 新加的 CSS 一条都不生效(真机表现:评论气泡/评论栏被当成 flex 子项挤到图片右侧)。
951
+ assert.match(body, /existing\.textContent !== CSS/, '样式内容变了必须比对出来')
952
+ assert.match(body, /existing\.textContent = CSS/, '变了就整段替换,下一次渲染追上代码')
953
+ })
954
+
955
+ test('守卫:面板画布与整屏查看器共用同一份 DOM(docked 只换定位,评论逻辑不分叉)', () => {
956
+ assert.ok(SOURCE.includes('const lightboxContent = lightboxDoc'),
957
+ '画布内容必须只构造一次')
958
+ assert.ok(SOURCE.includes("className: `knit-lightbox${lightboxDock ? ' docked' : ''}`"),
959
+ 'docked 只是同一个根上的一个 class')
960
+ assert.ok(SOURCE.includes('mountLightbox(lightboxContent)'),
961
+ '整屏挂载的是同一份内容')
962
+ assert.ok(SOURCE.includes("h('div', { className: 'knit-canvas' }, lightboxContent)"),
963
+ '面板画布挂载的也是同一份内容')
964
+ const start = SOURCE.indexOf('const CSS = `') + 'const CSS = `'.length
965
+ const css = SOURCE.slice(start, SOURCE.indexOf('`', start))
966
+ assert.match(css, /\.knit-canvas\{/, '要有面板画布的容器')
967
+ assert.match(css, /\.knit-lightbox\.docked\{/, '要有 docked 的定位覆盖')
968
+ // 评论栏要与画布有明确分界(用户反馈「红框区别太低」)
969
+ assert.match(css, /\.knit-lightbox-comments\{[^}]*border:\.5px solid var\(--dsw-alias-border-l4\)/,
970
+ '评论栏必须有可见描边')
971
+ assert.match(css, /\.knit-lightbox-comments-send\{[^}]*background:var\(--dsw-alias-brand-primary-new-colorprimary-new-color\)/,
972
+ '发送必须是主操作(品牌色按钮),不是灰字')
973
+ assert.match(css, /\.knit-lightbox-comments-emptyHint\{/, '空态要有下一步提示')
974
+ })
975
+
976
+ test('守卫:发送必须带原图附件(只发文字会被 agent 当成「不知道是哪张图」)', () => {
977
+ assert.match(SOURCE, /attachment: \{\s*src: srcFor\(lightboxDoc\)/,
978
+ 'sendComments 必须把图片地址交给投递层')
979
+ assert.match(SOURCE, /buildPasteEvent\(body, win, file\)/,
980
+ 'paste 事件必须同时带文本与 File')
981
+ assert.match(SOURCE, /async function imageFileFrom\(/, '图片要读成 File')
982
+ assert.match(SOURCE, /credentials: 'same-origin'/, '只读同源图片,不碰外网')
983
+ })
984
+
985
+ test('守卫:多张图的编号跟附件顺序一致,且每次投递是独立段落', () => {
986
+ assert.match(SOURCE, /composerState\(typeof document === 'undefined' \? null : document\)/,
987
+ '发送前必须读输入框的附件数')
988
+ assert.match(SOURCE, /index: composer\.count \+ 1/,
989
+ '新图编号 = 已有附件数 + 1(附件一 = 图像一)')
990
+ assert.match(SOURCE, /图像 \$\{index\}:/,
991
+ '头行的编号是变量,不是写死 1')
992
+ assert.match(SOURCE, /existing \? `\\n\\n\$\{payload\}` : payload/,
993
+ '已有正文时前面空两行,形成独立段落')
994
+ })
995
+
996
+ test('守卫:评论 P0 不落盘 —— 不新增 localStorage 键,也不碰 dsh-knit:pack', () => {
997
+ const start = SOURCE.indexOf('const [commentOn, setCommentOn]')
998
+ const end = SOURCE.indexOf('return h(\'div\', {', start)
999
+ const block = SOURCE.slice(start, end)
1000
+ assert.ok(!/writePref|readPref|localStorage/.test(block),
1001
+ '评论只活在内存(退出查看器仍在、刷新丢);落盘是 P1 的事')
1002
+ assert.ok(!SOURCE.includes('dsh-knit:comment'), '不许新增 dsh-knit:comment 之类存储键')
1003
+ assert.ok(!SOURCE.includes('dsh-knit:pack'), '§6.4 的老守卫仍要绿:不许出现 dsh-knit:pack')
1004
+ })