dsh-knit 0.16.0 → 0.17.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.
@@ -2175,3 +2175,604 @@ test('可见性:官方座位把契约的 `tab.visible` 一路传到 KnitBody',
2175
2175
  assert.equal(listCalls(calls).length, 1, '拿不到 visible 时要照旧取数')
2176
2176
  })
2177
2177
 
2178
+ /* ── v0.17 文档生命周期 ───────────────────────────────────────────────
2179
+ 五条纪律一起守:
2180
+ ① 文档行只多**一个弱化文字**(未读 / 已读 ×N / 读后已更新 / 修改后已重新读取)——
2181
+ 不抢标题、不加图标、不加颜色、不评分;
2182
+ ② 「最近读取」是**事实**(最近一次成功 read 的文件),不是「正在阅读」;
2183
+ ③ 上下文外读取默认折叠,展开才逐篇列出,且**只陈述**「不在包里但读过」;
2184
+ ④ 只展示**最近一次** Context Delta,符号只有 `+` / `-` / `↔`,绝不生成时间线;
2185
+ ⑤ 以上一切只在「使用情况」打开时出现 —— 关着时 DOM 与 v0.16 逐字一致。 */
2186
+
2187
+ /** 取节点直接子节点里 className **整段**匹配的那些。
2188
+ * 扁平节点列表里裸看 `.children` 会把兄弟行的节点也算进来,所以按父节点取。 */
2189
+ function kidsOf(node, className) {
2190
+ return (node.children || []).filter((n) => n && n.props && String(n.props.className || '') === className)
2191
+ }
2192
+
2193
+ /**
2194
+ * 一份带 v0.17 生命周期投影的载荷:四种状态各来一篇,外加包外两篇。
2195
+ * 每篇文档在行里的期望文案见 `LIFE_EXPECTED`。
2196
+ */
2197
+ function lifecyclePayload(overrides = {}) {
2198
+ const delta = overrides.delta || {
2199
+ appeared: [{ rel: 'docs/algo.md', tier: 'primary', rank: 1 }],
2200
+ disappeared: [{ rel: 'README.md', tier: 'related', rank: 4 }],
2201
+ moved: [{ rel: 'docs/eval.md', from: 'supporting', to: 'related' }],
2202
+ taskChanged: false,
2203
+ }
2204
+ return contextPayload({
2205
+ usage: {
2206
+ at: 1_700_000_000_000,
2207
+ epochId: 4,
2208
+ stats: {
2209
+ reads: 7,
2210
+ distinct: 3,
2211
+ outside: 2,
2212
+ outsideReads: ['docs/old-plan.md', 'docs/test-case.md'],
2213
+ firstReadTier: 'primary',
2214
+ firstReadRel: 'docs/algo.md',
2215
+ firstReadAt: 1,
2216
+ primaryRel: 'docs/algo.md',
2217
+ primaryFollowThrough: true,
2218
+ byTier: {
2219
+ primary: { total: 1, read: 1 },
2220
+ supporting: { total: 2, read: 1 },
2221
+ related: { total: 1, read: 0 },
2222
+ },
2223
+ supportingCoverage: 0.5,
2224
+ churn: { snapshots: 2, deltas: 2, retained: 2, appeared: 1, disappeared: 1, moved: 1, taskChanged: 0 },
2225
+ },
2226
+ delta,
2227
+ latestDelta: delta,
2228
+ recentRead: {
2229
+ rel: 'docs/eval.md',
2230
+ at: Date.now() - 12 * 60_000,
2231
+ seq: 42,
2232
+ epochId: 4,
2233
+ tier: 'supporting',
2234
+ rank: 2,
2235
+ inside: true,
2236
+ },
2237
+ outsideDocs: [
2238
+ { rel: 'docs/old-plan.md', count: 3, lastReadAt: 1, seq: 10 },
2239
+ { rel: 'docs/test-case.md', count: 1, lastReadAt: 2, seq: 20 },
2240
+ ],
2241
+ lifecycle: {
2242
+ 'docs/algo.md': { status: 'read', count: 3, lastReadAt: 1 },
2243
+ 'docs/eval.md': { status: 'reread_after_update', count: 2, lastReadAt: 2 },
2244
+ 'CHANGELOG.md': { status: 'updated_after_read', count: 1, lastReadAt: 3 },
2245
+ 'README.md': { status: 'unread', count: 0, lastReadAt: 0 },
2246
+ 'docs/old-plan.md': { status: 'read', count: 3, lastReadAt: 4 },
2247
+ 'docs/test-case.md': { status: 'read', count: 1, lastReadAt: 5 },
2248
+ },
2249
+ },
2250
+ })
2251
+ }
2252
+
2253
+ /** 分层视图里五行文档各自该显示的状态文字(顺序 = 屏幕顺序)。 */
2254
+ const LIFE_EXPECTED = ['已读 ×3', '修改后已重新读取', '读后已更新', '未读', '未读']
2255
+
2256
+ /**
2257
+ * 挂上面板并**打开「使用情况」**(数据到位后再点,与真实用法一致)。
2258
+ * @param {object} payload - 宿主载荷
2259
+ * @returns {Promise<{nodes:object[], render:Function, calls:string[]}>} 节点与重渲染
2260
+ */
2261
+ async function mountUsage(payload) {
2262
+ const { calls } = installFetch(() => payload)
2263
+ const { KnitBody } = loadClientModule().exports.__test
2264
+ harness.reset()
2265
+ harness.seed(['', 'relevance'])
2266
+ const render = () => harness.render(h(KnitBody, { sessionId: 's1' }))
2267
+ let nodes = render()
2268
+ await harness.flush()
2269
+ nodes = render()
2270
+ await harness.flush()
2271
+ nodes = render()
2272
+ const toggle = byExactClass(nodes, 'knit-btn').find((node) => textOf(node) === '使用情况')
2273
+ assert.ok(toggle, '头部必须有「使用情况」按钮')
2274
+ toggle.props.onClick()
2275
+ await harness.flush()
2276
+ nodes = render()
2277
+ await harness.flush()
2278
+ return { nodes: render(), render, calls }
2279
+ }
2280
+
2281
+ test('v0.17 生命周期:使用情况关着 —— 一个状态节点都不出现', async () => {
2282
+ const { calls } = installFetch(() => lifecyclePayload())
2283
+ const { KnitBody } = loadClientModule().exports.__test
2284
+ harness.reset()
2285
+ harness.seed(['', 'relevance'])
2286
+ const render = () => harness.render(h(KnitBody, { sessionId: 's1' }))
2287
+ render()
2288
+ await harness.flush()
2289
+ const nodes = render()
2290
+
2291
+ assert.ok(!calls.some((url) => url.includes('usage=1')), '关着就不该开闸')
2292
+ assert.equal(byExactClass(nodes, 'knit-life').length, 0, '关着不许有状态文字')
2293
+ assert.equal(byExactClass(nodes, 'knit-usage-more').length, 0, '关着不许有折叠区')
2294
+ assert.equal(byExactClass(nodes, 'knit-more-btn').length, 0, '关着不许有展开按钮')
2295
+ const rowText = byExactClass(nodes, 'knit-row1').map(textOf).join(' ')
2296
+ assert.ok(!/未读|已读|读后已更新|修改后已重新读取/.test(rowText), '关着时行里只有标题与时间')
2297
+ })
2298
+
2299
+ test('v0.17 生命周期:四种状态都落在文档行里,且只是一个弱化文字', async () => {
2300
+ const { nodes } = await mountUsage(lifecyclePayload())
2301
+
2302
+ const lives = byExactClass(nodes, 'knit-life')
2303
+ assert.deepEqual(lives.map(textOf), LIFE_EXPECTED, '四档事实状态按屏幕顺序逐行显示')
2304
+ // 状态是**弱化辅助信息**:没有图标、没有 aria、没有颜色、没有百分比
2305
+ for (const node of lives) {
2306
+ assert.deepEqual(Object.keys(node.props).sort(), ['className'], '状态只是一个 span')
2307
+ }
2308
+ const allText = textOf(byExactClass(nodes, 'knit-usage')[0])
2309
+ assert.ok(!allText.includes('%'), '不许有百分比')
2310
+ assert.ok(!/评分|置信|分数|质量|命中率|漏召回/.test(allText), '不许把事实写成评分')
2311
+ })
2312
+
2313
+ test('v0.17 生命周期:状态插在标题与时间之间,行结构不变', async () => {
2314
+ const { nodes } = await mountUsage(lifecyclePayload())
2315
+
2316
+ const rows = byExactClass(nodes, 'knit-row1')
2317
+ assert.equal(rows.length, 5, '五行文档各一条 row1')
2318
+ for (const row of rows) {
2319
+ assert.equal(kidsOf(row, 'knit-title').length, 1, '一行只有一个标题')
2320
+ assert.equal(kidsOf(row, 'knit-time').length, 1, '一行只有一个时间')
2321
+ assert.equal(kidsOf(row, 'knit-life').length, 1, '一行只有一个状态文字')
2322
+ const order = row.children.map((n) => String(n.props.className || ''))
2323
+ assert.ok(
2324
+ order.indexOf('knit-title') < order.indexOf('knit-life')
2325
+ && order.indexOf('knit-life') < order.indexOf('knit-time'),
2326
+ `状态必须在标题与时间之间:${order.join(' / ')}`,
2327
+ )
2328
+ }
2329
+ // 每行的前两个直接子节点仍然是「号 / 占位符 + 正文」(v0.15 起就钉住的形状)
2330
+ for (const doc of byClass(nodes, 'knit-doc')) {
2331
+ const classes = doc.children.map((n) => String(n.props.className || ''))
2332
+ assert.ok(
2333
+ classes[0] === 'knit-num' || classes[0] === 'knit-gapmark',
2334
+ `行首必须是号或占位符:${classes.join(' / ')}`,
2335
+ )
2336
+ assert.equal(classes[1], 'knit-body', '第二个直接子节点必须是正文')
2337
+ }
2338
+ })
2339
+
2340
+ test('v0.17 最近读取:如实说「最近读取:谁 · 多久前」,不说「正在阅读」', async () => {
2341
+ const { nodes } = await mountUsage(lifecyclePayload())
2342
+
2343
+ const line = byExactClass(nodes, 'knit-usage')[0]
2344
+ const text = textOf(line)
2345
+ assert.match(text, /最近读取:docs\/eval\.md · 12分钟前/, '最近一次成功 read 的文件要如实说出来')
2346
+ assert.ok(!/正在阅读|当前正在|正在读/.test(text), 'Knit 证明不了「此刻正在读」')
2347
+ // 与 v0.16 的既有事实行并存,没有多出统计指标
2348
+ assert.match(text, /当前上下文 · Epoch 4/)
2349
+ assert.match(text, /读了 7 次/)
2350
+ })
2351
+
2352
+ test('v0.17 上下文外读取:默认折叠,展开才逐篇列出', async () => {
2353
+ const { nodes, render } = await mountUsage(lifecyclePayload())
2354
+
2355
+ const buttons = byExactClass(nodes, 'knit-more-btn')
2356
+ const gapBtn = buttons.find((node) => textOf(node) === '上下文外读取 · 2 篇')
2357
+ assert.ok(gapBtn, '包外读取要有一行可展开的统计')
2358
+ assert.equal(gapBtn.props['aria-expanded'], 'false', '默认折叠')
2359
+ assert.equal(byExactClass(nodes, 'knit-gap-list').length, 0, '折叠时不渲染明细节点')
2360
+ assert.equal(byExactClass(nodes, 'knit-gap-row').length, 0, '折叠时一行明细都不许有')
2361
+
2362
+ gapBtn.props.onClick()
2363
+ const open = render()
2364
+ const list = byExactClass(open, 'knit-gap-list')
2365
+ assert.equal(list.length, 1, '展开后出现明细区')
2366
+ const rows = kidsOf(list[0], 'knit-gap-row')
2367
+ assert.equal(rows.length, 2, '两篇包外文档各一行')
2368
+ assert.deepEqual(
2369
+ rows.map((row) => kidsOf(row, 'knit-gap-rel')[0].props.title),
2370
+ ['docs/old-plan.md', 'docs/test-case.md'],
2371
+ )
2372
+ assert.deepEqual(rows.map((row) => textOf(kidsOf(row, 'knit-life')[0])), ['已读 ×3', '已读'])
2373
+ // 只陈述事实:不评价 Knit 推荐得对不对
2374
+ const openText = textOf(kidsOf(list[0], 'knit-gap-row')[0]) + textOf(byExactClass(open, 'knit-usage')[0])
2375
+ assert.ok(!/漏掉|推荐错|绕过|不认可|低质量|命中率/.test(openText), '包外读取不是「Knit 漏了」')
2376
+ })
2377
+
2378
+ test('v0.17 Context Delta:只展示最近一次,符号只有 + / - / ↔', async () => {
2379
+ const { nodes, render } = await mountUsage(lifecyclePayload())
2380
+
2381
+ const deltaBtn = byExactClass(nodes, 'knit-more-btn').find((node) => textOf(node) === '上下文刚刚变化')
2382
+ assert.ok(deltaBtn, '有变化就要有一行摘要')
2383
+ assert.equal(deltaBtn.props['aria-expanded'], 'false', '默认折叠')
2384
+ const digest = byExactClass(nodes, 'knit-delta-row')
2385
+ assert.deepEqual(digest.map(textOf), [
2386
+ '+ docs/algo.md',
2387
+ '- README.md',
2388
+ '↔ docs/eval.md · 辅助 → 相关',
2389
+ ])
2390
+ // 进出换层共用一种行样式:不用颜色区分「好 / 坏」
2391
+ assert.equal(new Set(digest.map((row) => row.props.className)).size, 1)
2392
+ assert.equal(byExactClass(nodes, 'knit-delta-head').length, 0, '折叠时没有分组标题')
2393
+
2394
+ deltaBtn.props.onClick()
2395
+ const open = render()
2396
+ assert.deepEqual(byExactClass(open, 'knit-delta-head').map(textOf), ['进入', '离开', '换层'])
2397
+ const openText = textOf(byExactClass(open, 'knit-usage')[0])
2398
+ assert.ok(!/\d{2}:\d{2}/.test(openText), '不许出现时间线')
2399
+ })
2400
+
2401
+ test('v0.17 Context Delta:超过三条折叠成「还有 N 条」,任务变化只说一句', async () => {
2402
+ const many = {
2403
+ appeared: [
2404
+ { rel: 'a.md', tier: 'primary', rank: 1 },
2405
+ { rel: 'b.md', tier: 'related', rank: 2 },
2406
+ { rel: 'c.md', tier: 'related', rank: 3 },
2407
+ { rel: 'd.md', tier: 'related', rank: 4 },
2408
+ ],
2409
+ disappeared: [],
2410
+ moved: [],
2411
+ taskChanged: false,
2412
+ }
2413
+ const folded = await mountUsage(lifecyclePayload({ delta: many }))
2414
+ assert.deepEqual(byExactClass(folded.nodes, 'knit-delta-row').map(textOf), [
2415
+ '+ a.md', '+ b.md', '+ c.md', '还有 1 条',
2416
+ ])
2417
+
2418
+ const task = await mountUsage(lifecyclePayload({
2419
+ delta: { appeared: [{ rel: 'docs/algo.md', tier: 'primary', rank: 1 }], disappeared: [], moved: [], taskChanged: true },
2420
+ }))
2421
+ const text = byExactClass(task.nodes, 'knit-delta-row').map(textOf)
2422
+ assert.deepEqual(text, ['+ docs/algo.md', '任务上下文已更新'], '任务变化也是一句事实,不是时间线')
2423
+ })
2424
+
2425
+ test('v0.17 样式:状态与折叠区只用语义 token —— 没有卡片 / 固定色 / 边框', async () => {
2426
+ const { readFileSync } = await import('node:fs')
2427
+ const { fileURLToPath } = await import('node:url')
2428
+ const source = readFileSync(
2429
+ fileURLToPath(new URL('../src/client/client.js', import.meta.url)),
2430
+ 'utf8',
2431
+ )
2432
+ // 状态是弱化说明文字,颜色必须走 caption token(十六进制只能出现在 var() 兜底里)
2433
+ assert.match(source, /\.knit-life\{[^}]*color:var\(--dsw-alias-label-caption/)
2434
+ assert.ok(!/\.knit-life\{[^}]*color:\s*#[0-9a-fA-F]{3,6}/.test(source), '不许写死颜色')
2435
+ assert.ok(!/\.knit-life\{[^}]*background/.test(source), '状态不画底色')
2436
+ // 折叠按钮是纯文字按钮:无边框、无底色
2437
+ assert.match(source, /\.knit-more-btn\{[^}]*border:0/)
2438
+ assert.match(source, /\.knit-more-btn\{[^}]*background:none/)
2439
+ // 明细行共用一套中性样式,不用颜色区分「进 / 出」
2440
+ assert.match(source, /\.knit-gap-row,\.knit-delta-row\{[^}]*color:var\(--dsw-alias-label-caption/)
2441
+ assert.ok(!/\.knit-gap-row,\.knit-delta-row\{[^}]*border/.test(source), '不要全宽分割线')
2442
+ })
2443
+
2444
+ test('v0.17 生命周期:英文环境下状态与折叠文案都是英文', async () => {
2445
+ installFetch(() => lifecyclePayload())
2446
+ const { exports } = loadClientModule()
2447
+ // 词典是模块级状态:apply 到 en 之后整块面板都说英文(与真机一致)
2448
+ exports.apply(fakeCtx({ sidebarRightTabs: true, locale: 'en' }).ctx)
2449
+ const { KnitBody } = exports.__test
2450
+ harness.reset()
2451
+ harness.seed(['', 'relevance'])
2452
+ const render = () => harness.render(h(KnitBody, { sessionId: 's1' }))
2453
+ let nodes = render()
2454
+ await harness.flush()
2455
+ nodes = render()
2456
+ await harness.flush()
2457
+ nodes = render()
2458
+ const toggle = byExactClass(nodes, 'knit-btn').find((node) => textOf(node) === 'Usage')
2459
+ assert.ok(toggle, '英文环境下开关文案是 Usage')
2460
+ toggle.props.onClick()
2461
+ await harness.flush()
2462
+ nodes = render()
2463
+ await harness.flush()
2464
+ nodes = render()
2465
+
2466
+ assert.deepEqual(
2467
+ byExactClass(nodes, 'knit-life').map(textOf),
2468
+ ['Read ×3', 'Re-read after update', 'Updated after read', 'Unread', 'Unread'],
2469
+ '四档状态在英文下也是英文',
2470
+ )
2471
+ assert.ok(
2472
+ byExactClass(nodes, 'knit-more-btn').some((node) => textOf(node) === 'Read outside the pack · 2'),
2473
+ '包外明细的按钮文案也要翻译',
2474
+ )
2475
+ const deltaBtn = byExactClass(nodes, 'knit-more-btn').find((node) => textOf(node) === 'Context just changed')
2476
+ assert.ok(deltaBtn, '变化摘要的按钮文案也要翻译')
2477
+ deltaBtn.props.onClick()
2478
+ const open = render()
2479
+ assert.deepEqual(byExactClass(open, 'knit-delta-head').map(textOf), ['Entered', 'Left', 'Moved tier'])
2480
+
2481
+ const allText = byExactClass(open, 'knit-usage').map(textOf).join(' ')
2482
+ assert.match(allText, /Recently read: docs\/eval\.md · 12 min ago/)
2483
+ assert.ok(!/[\u4e00-\u9fff]/.test(allText), '英文环境里一个汉字都不许有')
2484
+ })
2485
+
2486
+ /* ── v0.17:列表的进出动效(2026-10-03 用户拍板的那套手感)──────────────
2487
+ 用户原话:「新读取跟挤掉旧的未读的,这里的交互可能要优化,因为现在是一闪一闪的…
2488
+ 从当前的、如辅助上下文中新增,它应该是从低向上的…消失的时候从上到下,渐隐掉」。
2489
+ 补间在宿主浏览器里走 WAAPI(`Element.animate`),这里守的是**决定播什么**那部分:
2490
+ 差集怎么算、交错怎么排、幽灵行插哪儿。 */
2491
+
2492
+ /** 造一条「上一帧的位置」记录,形状与 `KnitBody` 里的 `motionRows` 一致。 */
2493
+ function motionRow(rel, tierKey, index, title) {
2494
+ return { rel, tierKey, index, doc: { rel, title: title || rel } }
2495
+ }
2496
+
2497
+ test('v0.17 动效:首屏与「换屏」都不播 —— 只有同一屏里多出来的行才算新来的', () => {
2498
+ const { planRowMotion } = loadClientModule().exports.__test
2499
+ const rows = [{ rel: 'a.md' }, { rel: 'b.md' }]
2500
+ // 第一次渲染没有上一帧可比:整屏一起飞进来会很吵(原型里首屏也刻意不播)
2501
+ assert.deepEqual(planRowMotion(null, 'doc|relevance|', rows), { entered: [], left: [] })
2502
+ // 换类型 / 换排序 / 搜索词变了 ⇒ 视图签名不同 ⇒ 照旧不播:那是「换屏」,不是「来了新的」
2503
+ const prev = { view: 'doc|relevance|', rows: [motionRow('a.md', 'primary', 0)] }
2504
+ assert.deepEqual(planRowMotion(prev, 'all|relevance|', rows), { entered: [], left: [] })
2505
+ })
2506
+
2507
+ test('v0.17 动效:新来的行按屏幕顺序交错飞入,交错有上限', () => {
2508
+ const T = loadClientModule().exports.__test
2509
+ const prev = { view: 'v', rows: [motionRow('a.md', 'primary', 0)] }
2510
+ assert.deepEqual(
2511
+ T.planRowMotion(prev, 'v', [{ rel: 'a.md' }, { rel: 'b.md' }, { rel: 'c.md' }, { rel: 'd.md' }]).entered,
2512
+ [
2513
+ { rel: 'b.md', delay: 0 },
2514
+ { rel: 'c.md', delay: T.MOTION_STAGGER_MS },
2515
+ { rel: 'd.md', delay: T.MOTION_STAGGER_MS * 2 },
2516
+ ],
2517
+ '交错的序号只数新来的行(第一篇的 delay 就是 0,不能当成「没排」)',
2518
+ )
2519
+ // 一次涌进来十几篇(换话题)时不排长队:越过上限的都落在同一拍上
2520
+ const many = Array.from({ length: 14 }, (_, i) => ({ rel: `m${i}.md` }))
2521
+ const delays = T.planRowMotion(prev, 'v', many).entered.map((row) => row.delay)
2522
+ assert.equal(delays.length, 14)
2523
+ assert.equal(Math.max(...delays), T.MOTION_STAGGER_MS * T.MOTION_STAGGER_MAX)
2524
+ assert.equal(
2525
+ delays.filter((d) => d === T.MOTION_STAGGER_MS * T.MOTION_STAGGER_MAX).length,
2526
+ 14 - T.MOTION_STAGGER_MAX,
2527
+ '封顶之后的都落在同一拍',
2528
+ )
2529
+ })
2530
+
2531
+ test('v0.17 动效:走了的行要带着它原来的位置与内容', () => {
2532
+ const { planRowMotion } = loadClientModule().exports.__test
2533
+ const prev = {
2534
+ view: 'v',
2535
+ rows: [motionRow('a.md', 'primary', 0, 'A'), motionRow('b.md', 'supporting', 0, 'B')],
2536
+ }
2537
+ const plan = planRowMotion(prev, 'v', [{ rel: 'a.md' }])
2538
+ assert.deepEqual(plan.entered, [])
2539
+ assert.deepEqual(plan.left.map((row) => row.rel), ['b.md'])
2540
+ assert.equal(plan.left[0].tierKey, 'supporting', '要知道它原来在哪个区')
2541
+ assert.equal(plan.left[0].index, 0, '要知道它原来在第几行')
2542
+ assert.equal(plan.left[0].doc.title, 'B', '幽灵行要用上一帧那份文档对象,不是只留个路径')
2543
+ })
2544
+
2545
+ test('v0.17 动效:同一篇只是换了层 —— 既不算飞入,也不算离开', () => {
2546
+ const { planRowMotion } = loadClientModule().exports.__test
2547
+ const prev = { view: 'v', rows: [motionRow('a.md', 'supporting', 1)] }
2548
+ assert.deepEqual(planRowMotion(prev, 'v', [motionRow('a.md', 'primary', 0)]), { entered: [], left: [] })
2549
+ })
2550
+
2551
+ test('v0.17 动效:幽灵行插回原位;还活着的不造幽灵;别的区一个都不插', () => {
2552
+ const { mergeGhostRows } = loadClientModule().exports.__test
2553
+ const docs = [{ rel: 'a.md' }, { rel: 'b.md' }]
2554
+ const ghost = (rel, index, tierKey) =>
2555
+ ({ rel, index, tierKey: tierKey || 'primary', doc: { rel, title: rel } })
2556
+
2557
+ assert.deepEqual(
2558
+ mergeGhostRows(docs, [ghost('x.md', 1)], 'primary').map((d) => d.rel),
2559
+ ['a.md', 'x.md', 'b.md'],
2560
+ '插回原来的位置 —— 否则看起来像「这篇跳到末尾才消失」',
2561
+ )
2562
+ assert.equal(mergeGhostRows(docs, [ghost('x.md', 1)], 'primary')[1].knitLeaving, true,
2563
+ '幽灵行要打上标记,DocRow 才会演离开')
2564
+ assert.deepEqual(
2565
+ mergeGhostRows([{ rel: 'a.md' }], [ghost('x.md', 0), ghost('y.md', 1)], 'primary').map((d) => d.rel),
2566
+ ['x.md', 'y.md', 'a.md'],
2567
+ '同一拍走掉两篇时各按上一帧的位置插回',
2568
+ )
2569
+ assert.deepEqual(mergeGhostRows(docs, [ghost('x.md', 9)], 'primary').map((d) => d.rel),
2570
+ ['a.md', 'b.md', 'x.md'], 'index 超出这一帧长度时落在末尾')
2571
+ assert.deepEqual(mergeGhostRows(docs, [ghost('a.md', 0)], 'primary').map((d) => d.rel),
2572
+ ['a.md', 'b.md'], '还活着的那篇不造幽灵(它只是换了层)')
2573
+ assert.equal(mergeGhostRows(docs, [ghost('x.md', 0, 'related')], 'primary'), docs,
2574
+ '别的区的幽灵不许插进这一区(没得插就原样返回)')
2575
+ assert.equal(mergeGhostRows(docs, [], 'primary'), docs, '没有幽灵时原样返回')
2576
+ assert.equal(mergeGhostRows(docs, null, 'primary'), docs, '没传幽灵也照样出数据')
2577
+ })
2578
+
2579
+ test('v0.17 动效:这套补间只在真机上跑 —— 测试进程里恒被挡掉', () => {
2580
+ const T = loadClientModule().exports.__test
2581
+ assert.equal(T.motionAllowed(), false,
2582
+ '替身没有 document ⇒ 一律不播(渲染树里不会多出 entering / leaving)')
2583
+ assert.ok(T.MOTION_EXIT_MS < T.MOTION_ENTER_MS, '离开要比进入利落:收起不能拖')
2584
+ assert.equal(T.MOTION_EASE, 'cubic-bezier(.22,1,.36,1)',
2585
+ '缓动照抄原型,不许在真客户端另调一套')
2586
+ })
2587
+
2588
+ test('v0.17 动效:CSS 里只有静态那两笔 —— 补间在 JS 里,不留第二套真相', async () => {
2589
+ const { readFileSync } = await import('node:fs')
2590
+ const { fileURLToPath } = await import('node:url')
2591
+ const source = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
2592
+ const start = source.indexOf('const CSS = `') + 'const CSS = `'.length
2593
+ const css = source.slice(start, source.indexOf('`', start)).replace(/\/\*[\s\S]*?\*\//g, '')
2594
+
2595
+ const leaving = css.match(/\.knit-doc\.leaving\{([^}]*)\}/)
2596
+ assert.ok(leaving, '必须有 .knit-doc.leaving 这条规则')
2597
+ assert.match(leaving[1], /pointer-events:none/, '幽灵行不吃指针事件(它已经在走了)')
2598
+ assert.match(leaving[1], /overflow:hidden/, '收起高度时要能裁掉内容')
2599
+ assert.ok(!leaving[1].includes('animation'),
2600
+ 'CSS 不许自己播关键帧:高度要按量出来的自然高度补间,写死会跳')
2601
+ assert.ok(!/@keyframes/.test(css), 'CSS 里不留 @keyframes —— 只有一套真相')
2602
+ assert.match(css, /@media \(prefers-reduced-motion: reduce\)\{[\s\S]*?\.knit-doc\{transition:none\}/,
2603
+ '系统要求减弱动态效果 ⇒ 连底色过渡一起去掉')
2604
+ })
2605
+
2606
+ test('v0.17 动效:换层 / 重排的位移按 FLIP 算 —— 亚像素抖动不当成「动过」', () => {
2607
+ const T = loadClientModule().exports.__test
2608
+ const { motionShift } = T
2609
+
2610
+ assert.equal(motionShift({ left: 10, top: 40 }, { left: 10, top: 40 }), null, '没动就不补间')
2611
+ assert.equal(motionShift({ left: 10, top: 40 }, { left: 10, top: 40.3 }), null,
2612
+ '亚像素抖动(浏览器缩放 / 滚动残留)不该让整屏一直在微微地飘')
2613
+ assert.deepEqual(motionShift({ left: 12, top: 120 }, { left: 12, top: 40 }),
2614
+ { dx: 0, dy: 80 },
2615
+ '正数=上一帧更靠右下:先把行往下拉回老位置,再补间归位')
2616
+ assert.deepEqual(motionShift({ left: 60, top: 40 }, { left: 12, top: 40 }),
2617
+ { dx: 48, dy: 0 }, '横向也是同一套:分栏里换列同样要飞过去')
2618
+ assert.equal(motionShift(null, { left: 0, top: 0 }), null, '没有上一帧(新行)不归 FLIP 管')
2619
+ assert.equal(motionShift({ left: 0, top: 0 }, null), null, '量不到这一帧就不敢补')
2620
+ assert.equal(motionShift({ left: 0, top: 0 }, { left: 0, top: 3 }, 4), null,
2621
+ '阈值可传:小于它一律算没动')
2622
+ assert.deepEqual(motionShift({ left: 0, top: 0 }, { left: 0, top: 3 }, 2), { dx: 0, dy: -3 },
2623
+ '超过阈值就照实补(负值=上一帧更靠左上)')
2624
+ assert.equal(motionShift({ left: 0, top: NaN }, { left: 0, top: 0 }), null,
2625
+ '矩形里出现 NaN(节点刚卸载)时宁可不播,也别补出一段乱飞')
2626
+ assert.ok(T.MOTION_MOVE_MS > 0 && T.MOTION_MOVE_EPS > 0 && T.MOTION_MOVE_EPS <= 1,
2627
+ 'FLIP 的时长与死区都得是正常量级')
2628
+ })
2629
+
2630
+ test('v0.17 动效:FLIP 给挪过位置的幸存行排补间 —— 进 / 出的行跳过,只补 transform', () => {
2631
+ const T = loadClientModule().exports.__test
2632
+ const { applyRowFlips } = T
2633
+
2634
+ // 鸭子类型的行节点:只实现 FLIP 真正会碰的那几个成员。
2635
+ const row = (rel, top, left) => ({
2636
+ rel,
2637
+ played: [],
2638
+ getAttribute: () => rel,
2639
+ getBoundingClientRect: () => ({ left: left || 0, top }),
2640
+ animate(frames, opts) {
2641
+ this.played.push({ frames, opts })
2642
+ return { finished: Promise.resolve() }
2643
+ },
2644
+ })
2645
+ const host = (...els) => ({ querySelectorAll: () => els })
2646
+
2647
+ // ① 换层 / 重排:先从老位置拉回来,再补到归位
2648
+ const moved = row('a.md', 40)
2649
+ const prev = new Map([['a.md', { left: 0, top: 120 }]])
2650
+ const after = applyRowFlips(host(moved), prev, new Set())
2651
+ assert.equal(moved.played.length, 1, '挪了位置就该补一段')
2652
+ assert.deepEqual(moved.played[0].frames, [
2653
+ { transform: 'translate(0px, 80px)' },
2654
+ { transform: 'translate(0px, 0px)' },
2655
+ ], '正数=上一帧更靠下:先把行拉到老位置,再补回新位置')
2656
+ assert.equal(moved.played[0].opts.duration, T.MOTION_MOVE_MS, '时长用同一个常量')
2657
+ assert.equal(moved.played[0].opts.easing, T.MOTION_EASE, '缓动与进 / 出补间同一套')
2658
+ assert.deepEqual([...after], [['a.md', { left: 0, top: 40 }]], '这一帧的矩形要留给下一帧')
2659
+
2660
+ // ② 正在进 / 出的行跳过(它们有自己的补间,叠一层会打架)
2661
+ const entering = row('b.md', 40)
2662
+ const ghost = row('c.md', 40)
2663
+ const skipped = applyRowFlips(host(entering, ghost), new Map([
2664
+ ['b.md', { left: 0, top: 120 }], ['c.md', { left: 0, top: 120 }],
2665
+ ]), new Set(['b.md', 'c.md']))
2666
+ assert.equal(entering.played.length + ghost.played.length, 0, '进 / 出的行一个都不补')
2667
+ assert.equal(skipped.size, 0,
2668
+ '进 / 出的行连位置都不记 —— 那一刻量到的是补间中间态,记下来下一帧会凭空飘一下')
2669
+
2670
+ // ③ 亚像素抖动不算动;④ 新来的行没得比
2671
+ const jitter = row('d.md', 40.3)
2672
+ const brandNew = row('e.md', 90)
2673
+ const quiet = applyRowFlips(host(jitter, brandNew), new Map([['d.md', { left: 0, top: 40 }]]), new Set())
2674
+ assert.equal(jitter.played.length, 0, '零点几像素不补 —— 否则整屏一直在微微地飘')
2675
+ assert.equal(brandNew.played.length, 0, '第一次出现的行归「飞入」管,FLIP 不接手')
2676
+ assert.deepEqual([...quiet.keys()], ['d.md', 'e.md'], '两行的位置都要记')
2677
+
2678
+ // ⑤ 环境不完整时一声不响(测试进程里就是这样)
2679
+ assert.equal(applyRowFlips(null, new Map(), new Set()).size, 0, '没有列表容器就什么都不做')
2680
+ assert.equal(applyRowFlips({}, null, null).size, 0, '容器不会查节点也照样返回空表')
2681
+ const noAnim = { getAttribute: () => 'f.md', getBoundingClientRect: () => ({ left: 0, top: 10 }) }
2682
+ const onlyMeasure = applyRowFlips({ querySelectorAll: () => [noAnim] },
2683
+ new Map([['f.md', { left: 0, top: 90 }]]), new Set())
2684
+ assert.equal(onlyMeasure.size, 1, '节点不认 WAAPI 时只记位置、不补间,不抛错')
2685
+ })
2686
+
2687
+ test('v0.17 动效:FLIP 量的是布局坐标 —— 滚动 / 悬停 / 容器变高都不算「行挪了位置」', () => {
2688
+ const T = loadClientModule().exports.__test
2689
+ const { applyRowFlips, rowLayoutPoint } = T
2690
+
2691
+ // 一行两套坐标:`offsetTop/offsetLeft` 是**布局坐标**(谁真挪了位置才动),
2692
+ // `getBoundingClientRect` 是**视口坐标**(容器一滚、容器自己一高一变、行上挂个 transform 都会动)。
2693
+ const row = (rel, top, left, viewTop, viewLeft) => ({
2694
+ rel,
2695
+ offsetTop: top,
2696
+ offsetLeft: left,
2697
+ played: [],
2698
+ getAttribute: () => rel,
2699
+ getBoundingClientRect: () => ({ left: viewLeft, top: viewTop }),
2700
+ animate(frames) { this.played.push(frames); return { finished: Promise.resolve() } },
2701
+ })
2702
+ const host = (...els) => ({
2703
+ querySelectorAll: () => els,
2704
+ getBoundingClientRect: () => ({ left: 0, top: 100 }),
2705
+ })
2706
+
2707
+ // ① 容器滚了 80px:视口矩形整体平移,布局坐标一动没动 ⇒ 一行都不许补。
2708
+ // 这就是用户那句「我没有输入任何的对话……文档列表就开始跳动」。
2709
+ const scrolled = row('a.md', 120, 0, 40, 0)
2710
+ const after = applyRowFlips(host(scrolled), new Map([['a.md', { left: 0, top: 120 }]]), new Set())
2711
+ assert.equal(scrolled.played.length, 0, '滚动不是「行换了位置」—— 拿视口矩形量会让整屏凭空补一段')
2712
+ assert.deepEqual([...after], [['a.md', { left: 0, top: 120 }]], '存下来的也必须是布局坐标')
2713
+
2714
+ // ② 鼠标正悬停在那行:`.knit-doc:hover{transform:translateX(-2px)}` 是死区 0.5px 的四倍,
2715
+ // 但那 2px 是 CSS 的事,不许被当成「这行挪了」再补一段(补了会跟悬停过渡打架)
2716
+ const hovered = row('b.md', 200, 0, 200, -2)
2717
+ applyRowFlips(host(hovered), new Map([['b.md', { left: 0, top: 200 }]]), new Set())
2718
+ assert.equal(hovered.played.length, 0, '悬停的 2px 不算位移')
2719
+
2720
+ // ③ 真的换了位置(换层 / 重排):补的差值取自布局坐标,不是视口矩形
2721
+ const moved = row('c.md', 160, 0, 40, -2)
2722
+ applyRowFlips(host(moved), new Map([['c.md', { left: 0, top: 120 }]]), new Set())
2723
+ assert.equal(moved.played.length, 1, '真挪了就补')
2724
+ assert.deepEqual(moved.played[0][0], { transform: 'translate(0px, -40px)' },
2725
+ '差值取自 offsetTop(120→160);取视口矩形(120→40)会补出 80px 的乱飞')
2726
+
2727
+ // ④ 节点没有 offset*(测试替身 / 已卸载)时才退回视口矩形,但要减掉容器那块、加回滚动量
2728
+ const noOffset = { getAttribute: () => 'd.md', getBoundingClientRect: () => ({ left: 0, top: 40 }) }
2729
+ const box = {
2730
+ querySelectorAll: () => [noOffset],
2731
+ getBoundingClientRect: () => ({ left: 0, top: 100 }),
2732
+ scrollTop: 80,
2733
+ }
2734
+ assert.deepEqual(rowLayoutPoint(box, noOffset), { left: 0, top: 20 },
2735
+ '视口 40 − 容器 100 + 滚动 80 = 20:还是布局坐标')
2736
+ assert.equal(rowLayoutPoint(box, null), null, '没有节点就是量不到')
2737
+ assert.equal(rowLayoutPoint({}, {}), null, '两套坐标都拿不到时宁可不补')
2738
+ })
2739
+
2740
+ test('v0.17 动效:FLIP 真的接在提交之后 —— 跳过进 / 出、落盘位置', async () => {
2741
+ const { readFileSync } = await import('node:fs')
2742
+ const { fileURLToPath } = await import('node:url')
2743
+ const source = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
2744
+ const mark = source.indexOf('/* ── 活下来的行换了位置:FLIP')
2745
+ assert.ok(mark > 0, 'KnitBody 的提交后 layout effect 里必须接上 FLIP')
2746
+ const code = source.slice(mark, source.indexOf('const withGhosts', mark))
2747
+ .replace(/\/\*[\s\S]*?\*\//g, '')
2748
+
2749
+ assert.match(code, /const skip = new Set\(\[\.\.\.motion\.entered\.keys\(\), \.\.\.motion\.ghosts\.keys\(\)\]\)/,
2750
+ '正在进 / 出的 rel 组成跳过表')
2751
+ assert.match(code, /store\.tweenUntil = Date\.now\(\) \+ MOTION_ENTER_MS \+ MOTION_STAGGER_MS/,
2752
+ '进 / 出补间在飞的那几百毫秒留一个「别量」的窗口(量到的是中间态)')
2753
+ assert.match(code, /const settled = motionOn[\s\S]*?store\.view === motionView/,
2754
+ '换屏(视图签名变了)/ 补间还在飞 / 没有行的时候,一个都不量 —— 换屏照补就是「整屏一起飞」')
2755
+ assert.match(code, /store\.positions = settled \? applyRowFlips\(listRef\.current, store\.positions, skip\) : new Map\(\)/,
2756
+ '量的是真列表容器,位置表跨帧传递;不量时清空 —— 别拿上一帧的旧坐标去比')
2757
+ })
2758
+
2759
+ test('v0.17 交互审:列表只在光标真的换了(且焦点在列表上)时跟手滚 —— 刷新不许动列表', async () => {
2760
+ const { readFileSync } = await import('node:fs')
2761
+ const { fileURLToPath } = await import('node:url')
2762
+ const source = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
2763
+ // ⚠️ 起点必须含 `/*` 本身:否则切片从注释**中间**开始,下面那句去注释的正则找不到配对的
2764
+ // `/*`,会把那段解释「为什么不能依赖 state.docs」的注释当成代码,于是这条测试自己误报。
2765
+ const mark = source.indexOf('/* 键盘焦点跟手滚进视口')
2766
+ assert.ok(mark > 0, 'KnitBody 里必须有「光标跟手滚进视口」那条 effect')
2767
+ const end = source.indexOf('// 预览高度:拖完就记住', mark)
2768
+ assert.ok(end > mark, '切片终点应是「预览高度」那条 effect 的注释')
2769
+ const code = source.slice(mark, end).replace(/\/\*[\s\S]*?\*\//g, '')
2770
+
2771
+ assert.match(code, /\}, \[cursor, query\]\)/, '依赖里只许有 cursor / query')
2772
+ assert.ok(!/state\.docs/.test(code),
2773
+ '不许依赖 state.docs:那是每 5 秒一次的新数组,会把列表每 5 秒拽回光标行一次'
2774
+ + '(用户的原话:「我没有输入任何的对话……文档列表就开始跳动」)')
2775
+ assert.match(code, /document\.activeElement/, '只在列表自己拿着键盘焦点时滚 —— 这条服务的是键盘导航')
2776
+ assert.match(code, /scrollIntoView\(\{ block: 'nearest' \}\)/, '滚的是最小距离,不是把行顶到最上面')
2777
+ })
2778
+