dsh-knit 0.4.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,153 @@
1
+ /**
2
+ * 图标测试:Knit 的 mono SVG 图标(右边栏 / guide 胶囊 / tab 芯片)。
3
+ *
4
+ * 图标是内联在客户端代码里的(无构建步骤,加载期不能读文件),
5
+ * 源文件在 `assets/knit-icon-24-mono-4px.svg` —— 这里同时守住两者一致。
6
+ *
7
+ * 跑法:node --test test/
8
+ */
9
+ import test from 'node:test'
10
+ import assert from 'node:assert/strict'
11
+ import { readFileSync } from 'node:fs'
12
+
13
+ import { loadClientModule, createHarness, byClass } from './harness.mjs'
14
+
15
+ const harness = createHarness()
16
+ const React = globalThis.__knitReact
17
+ const h = React.createElement
18
+
19
+ const CLIENT_SOURCE = readFileSync(new URL('../src/client/client.js', import.meta.url), 'utf8')
20
+ const SVG_SOURCE = readFileSync(
21
+ new URL('../assets/knit-icon-24-mono-4px.svg', import.meta.url),
22
+ 'utf8',
23
+ )
24
+
25
+ /* ── 图标本体 ───────────────────────────────────────── */
26
+
27
+ test('图标:渲染成 svg,带正确的 viewBox 与描边参数', () => {
28
+ const { exports } = loadClientModule()
29
+ const { KnitGlyph } = exports.__test
30
+
31
+ harness.reset()
32
+ const nodes = harness.render(h(KnitGlyph, { size: 16 }))
33
+ const svg = nodes.find((n) => n.type === 'svg')
34
+
35
+ assert.ok(svg, '应渲染出 <svg>')
36
+ assert.equal(svg.props.width, 16)
37
+ assert.equal(svg.props.height, 16)
38
+ assert.equal(svg.props.viewBox, '0 0 100 100', 'viewBox 必须与源文件一致')
39
+ assert.equal(svg.props.stroke, 'currentColor', '颜色交给 CSS 控制')
40
+ assert.equal(svg.props.fill, 'none')
41
+ assert.equal(svg.props.strokeWidth, 16.67, '4px 描边(100 单位 viewBox)')
42
+ assert.equal(svg.props['aria-hidden'], 'true', '装饰性图标要对读屏隐藏')
43
+ })
44
+
45
+ test('图标:默认 16px,显式尺寸生效', () => {
46
+ const { exports } = loadClientModule()
47
+ const { KnitGlyph } = exports.__test
48
+
49
+ harness.reset()
50
+ const dflt = harness.render(h(KnitGlyph, {})).find((n) => n.type === 'svg')
51
+ assert.equal(dflt.props.width, 16)
52
+
53
+ harness.reset()
54
+ const big = harness.render(h(KnitGlyph, { size: 24 })).find((n) => n.type === 'svg')
55
+ assert.equal(big.props.width, 24)
56
+ assert.equal(big.props.height, 24)
57
+ })
58
+
59
+ test('图标:class 恒带 knit-icon(配色靠它),额外 class 会被拼上', () => {
60
+ const { exports } = loadClientModule()
61
+ const { KnitGlyph } = exports.__test
62
+
63
+ harness.reset()
64
+ const plain = harness.render(h(KnitGlyph, {})).find((n) => n.type === 'svg')
65
+ assert.equal(plain.props.className, 'knit-icon')
66
+
67
+ harness.reset()
68
+ const extra = harness.render(h(KnitGlyph, { className: 'x' })).find((n) => n.type === 'svg')
69
+ assert.equal(extra.props.className, 'knit-icon x')
70
+ })
71
+
72
+ test('图标:内联的 path 与 assets 里的源文件逐字一致', () => {
73
+ const { exports } = loadClientModule()
74
+ const { KNIT_ICON_PATH } = exports.__test
75
+
76
+ const fromSvg = /\sd="([^"]+)"/.exec(SVG_SOURCE)[1]
77
+
78
+ assert.equal(
79
+ KNIT_ICON_PATH,
80
+ fromSvg,
81
+ '内联 path 与 assets/knit-icon-24-mono-4px.svg 不一致 —— 改图标时两处要一起改',
82
+ )
83
+ })
84
+
85
+ /* ── 配色(用户明确要求:浅色纯黑、暗色纯白)─────────── */
86
+
87
+ test('配色:浅色模式纯黑、暗色模式纯白(锁死这条要求)', () => {
88
+ assert.match(
89
+ CLIENT_SOURCE,
90
+ /\.knit-icon\s*\{\s*color:\s*#000\s*\}/,
91
+ '缺少浅色模式的纯黑规则',
92
+ )
93
+ assert.match(
94
+ CLIENT_SOURCE,
95
+ /body\[data-ds-dark-theme\]\s+\.knit-icon\s*\{\s*color:\s*#fff\s*\}/,
96
+ '缺少暗色模式的纯白规则(DSH 的暗色信号挂在 body 上)',
97
+ )
98
+ })
99
+
100
+ test('配色:图标不依赖面板先渲染(样式表由图标自己保证注入)', () => {
101
+ const glyph = CLIENT_SOURCE.slice(CLIENT_SOURCE.indexOf('function KnitGlyph'))
102
+ const body = glyph.slice(0, glyph.indexOf('\n }'))
103
+ assert.match(
104
+ body,
105
+ /ensureStyle\(\)/,
106
+ 'KnitGlyph 必须自己调 ensureStyle —— guide 胶囊与 tab 芯片会在 KnitBody 之前渲染',
107
+ )
108
+ })
109
+
110
+ /* ── 用在哪儿 ───────────────────────────────────────── */
111
+
112
+ test('tab 芯片标题:图标 + 名称,且不再用 emoji', () => {
113
+ const { exports } = loadClientModule()
114
+ const { KnitTitle } = exports.__test
115
+
116
+ harness.reset()
117
+ const nodes = harness.render(h(KnitTitle, {}))
118
+ const svg = nodes.find((n) => n.type === 'svg')
119
+
120
+ assert.ok(svg, '芯片标题应带 SVG 图标')
121
+ assert.equal(svg.props.width, 16)
122
+
123
+ const text = nodes.flatMap((n) => (n.children || []).filter((c) => typeof c === 'string')).join('')
124
+ assert.equal(text, 'Knit', '图标旁边是类型名')
125
+
126
+ const all = JSON.stringify(nodes.map((n) => n.children))
127
+ assert.ok(!all.includes('🧶'), '芯片标题里不该再有毛球 emoji')
128
+ })
129
+
130
+ test('注册:guide 胶囊与 better-sidebar tab 都用同一个图标组件', () => {
131
+ const uses = CLIENT_SOURCE.match(/icon:\s*KnitGlyph/g) || []
132
+ assert.equal(uses.length, 2, `应有 2 处(guide 胶囊 + better-sidebar tab),实际 ${uses.length}`)
133
+ })
134
+
135
+ test('会话头部入口按钮:也用同一个 mono 图标', () => {
136
+ const { exports } = loadClientModule()
137
+ const { makeEntryButton } = exports.__test
138
+
139
+ harness.reset()
140
+ const nodes = harness.render(h(makeEntryButton(() => true), {}))
141
+ const svg = nodes.find((n) => n.type === 'svg')
142
+
143
+ assert.ok(svg, '入口按钮里应是 SVG 图标')
144
+ assert.equal(svg.props.width, 16)
145
+ assert.equal(svg.props.className, 'knit-icon', '和右边栏用同一套配色')
146
+ })
147
+
148
+ test('全项目不再有毛球 emoji', () => {
149
+ assert.ok(
150
+ !CLIENT_SOURCE.includes('🧶'),
151
+ '客户端源码里不该再出现 🧶 —— 右边栏与入口按钮都已换成 mono 图标',
152
+ )
153
+ })
@@ -0,0 +1,443 @@
1
+ /**
2
+ * 第一梯队测试:相对路径图片、预览高度与全屏、键盘导航、过滤框。
3
+ *
4
+ * 跑法:node --test test/
5
+ */
6
+ import test from 'node:test'
7
+ import assert from 'node:assert/strict'
8
+
9
+ import { loadClientModule, createHarness, byClass, byExactClass, textOf } from './harness.mjs'
10
+
11
+ const harness = createHarness()
12
+ const React = globalThis.__knitReact
13
+ const h = React.createElement
14
+
15
+ /** 预览面板本体(整段匹配,避免命中 head/body/title 等子串)。 */
16
+ const panelOf = (nodes) => byExactClass(nodes, 'knit-preview')
17
+
18
+ /* ── 共用脚手架 ─────────────────────────────────────── */
19
+
20
+ /**
21
+ * 造一份列表载荷。
22
+ * @param {object} overrides - 覆盖字段
23
+ * @returns {object} 载荷
24
+ */
25
+ function listPayload(overrides = {}) {
26
+ return {
27
+ ok: true,
28
+ root: '/p',
29
+ total: 3,
30
+ mode: 'time',
31
+ topic: '',
32
+ docs: [
33
+ { path: '/p/技术方案.md', rel: '技术方案.md', name: '技术方案.md', title: '技术方案', summary: '架构拆分', mtimeMs: Date.now() - 60000, score: null },
34
+ { path: '/p/docs/竞品分析.md', rel: 'docs/竞品分析.md', name: '竞品分析.md', title: '竞品分析', summary: '对比 Cursor', mtimeMs: Date.now() - 9e7, score: null },
35
+ { path: '/p/docs/guide.md', rel: 'docs/guide.md', name: 'guide.md', title: 'Guide', summary: 'usage', mtimeMs: Date.now() - 1e8, score: null },
36
+ ],
37
+ ...overrides,
38
+ }
39
+ }
40
+
41
+ /**
42
+ * 装一个 fetch 替身。
43
+ * @param {Function} responder - 按 url 返回载荷
44
+ * @returns {{calls: string[]}} 调用记录
45
+ */
46
+ function installFetch(responder) {
47
+ const calls = []
48
+ globalThis.fetch = async (url) => {
49
+ calls.push(url)
50
+ return { json: async () => responder(url) }
51
+ }
52
+ return { calls }
53
+ }
54
+
55
+ /**
56
+ * 渲染到列表加载完成。
57
+ * @param {object} comp - 组件
58
+ * @param {object} props - 入参
59
+ * @param {Array} seed - 预置的 useState 初值
60
+ * @returns {Promise<{nodes: object[], renderAgain: Function}>} 节点与重渲染函数
61
+ */
62
+ async function mount(comp, props, seed) {
63
+ harness.reset()
64
+ if (seed) harness.seed(seed)
65
+ let nodes = harness.render(h(comp, props))
66
+ await harness.flush()
67
+ nodes = harness.render(h(comp, props))
68
+ return {
69
+ nodes,
70
+ /**
71
+ * 重渲染。`flush: true` 时先渲染一次把新状态的 effect 登记上,再执行它们,
72
+ * 最后渲染出新结果 —— 顺序不能反,否则 effect 根本还没被登记就跑了个空。
73
+ * @param {boolean} flush - 是否执行 effect
74
+ * @returns {Promise<object[]>} 扁平节点
75
+ */
76
+ renderAgain: async (flush = false) => {
77
+ let next = harness.render(h(comp, props))
78
+ if (flush) {
79
+ await harness.flush()
80
+ next = harness.render(h(comp, props))
81
+ }
82
+ return next
83
+ },
84
+ }
85
+ }
86
+
87
+ /**
88
+ * 按 className 取第一个节点的文本。
89
+ * @param {object[]} nodes - 扁平节点
90
+ * @param {string} cls - class 子串
91
+ * @returns {string} 文本
92
+ */
93
+ function textByClass(nodes, cls) {
94
+ const hit = byClass(nodes, cls)[0]
95
+ return hit ? textOf(hit) : ''
96
+ }
97
+
98
+ /* ── 1. 相对路径图片 ───────────────────────────────── */
99
+
100
+ test('resolveRelative:同目录 / 子目录 / 上级目录', () => {
101
+ const { exports } = loadClientModule()
102
+ const { resolveRelative } = exports.__test
103
+
104
+ assert.equal(resolveRelative('技术方案.md', './img/a.png'), 'img/a.png')
105
+ assert.equal(resolveRelative('技术方案.md', 'img/a.png'), 'img/a.png')
106
+ assert.equal(resolveRelative('docs/guide.md', './img/a.png'), 'docs/img/a.png')
107
+ assert.equal(resolveRelative('docs/guide.md', '../assets/b.png'), 'assets/b.png')
108
+ assert.equal(resolveRelative('a/b/c.md', '../../x.png'), 'x.png')
109
+ assert.equal(resolveRelative('docs/guide.md', 'img/../pic/a.png'), 'docs/pic/a.png')
110
+ })
111
+
112
+ test('resolveRelative:网络地址 / 锚点 / 协议相对一律不接管', () => {
113
+ const { exports } = loadClientModule()
114
+ const { resolveRelative } = exports.__test
115
+
116
+ assert.equal(resolveRelative('a.md', 'https://x.com/y.png'), '')
117
+ assert.equal(resolveRelative('a.md', 'http://x.com/y.png'), '')
118
+ assert.equal(resolveRelative('a.md', 'data:image/png;base64,AAAA'), '')
119
+ assert.equal(resolveRelative('a.md', 'file:///tmp/x.png'), '')
120
+ assert.equal(resolveRelative('a.md', '#anchor'), '')
121
+ assert.equal(resolveRelative('a.md', '//cdn.x.com/y.png'), '')
122
+ assert.equal(resolveRelative('a.md', ' '), '')
123
+ })
124
+
125
+ test('resolveRelative:去掉查询串与 hash', () => {
126
+ const { exports } = loadClientModule()
127
+ const { resolveRelative } = exports.__test
128
+ assert.equal(resolveRelative('docs/g.md', './img/a.png?v=2'), 'docs/img/a.png')
129
+ assert.equal(resolveRelative('docs/g.md', './img/a.png#frag'), 'docs/img/a.png')
130
+ })
131
+
132
+ test('pathImagesFor:返回同源相对地址,带正确的编码', () => {
133
+ const { exports } = loadClientModule()
134
+ const { pathImagesFor } = exports.__test
135
+
136
+ const resolver = pathImagesFor('s-1', 'docs/需求 文档.md')
137
+ assert.equal(typeof resolver.resolve, 'function', 'pathImages 必须是带 resolve 的对象')
138
+ assert.equal(
139
+ resolver.resolve('./img/图 1.png'),
140
+ '/knit/api/raw?sessionId=s-1&rel=docs%2Fimg%2F%E5%9B%BE%201.png',
141
+ )
142
+ assert.equal(resolver.resolve('https://x.com/y.png'), undefined, '网络图片不接管')
143
+ })
144
+
145
+ test('渲染:把 pathImages 传给 MarkdownText', async () => {
146
+ installFetch((url) => (url.includes('/api/doc')
147
+ ? { ok: true, rel: 'docs/guide.md', title: 'Guide', text: '![](./img/a.png)', truncated: false }
148
+ : listPayload()))
149
+
150
+ const { exports, markdownCalls } = loadClientModule()
151
+ const { KnitBody } = exports.__test
152
+ const { nodes, renderAgain } = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
153
+ byClass(nodes, 'knit-doc')[2].props.onClick()
154
+ const after = await renderAgain(true)
155
+
156
+ assert.ok(markdownCalls.length >= 1, '应渲染 MarkdownText')
157
+ const passed = markdownCalls.at(-1).pathImages
158
+ assert.ok(passed && typeof passed.resolve === 'function', 'pathImages 必须传下去')
159
+ assert.equal(passed.resolve('./img/a.png'), '/knit/api/raw?sessionId=s1&rel=docs%2Fimg%2Fa.png')
160
+ assert.equal(panelOf(after).length, 1)
161
+ })
162
+
163
+ /* ── 2. 预览高度与全屏 ─────────────────────────────── */
164
+
165
+ test('clampRatio:夹在 20%–80%,非法值回落默认', () => {
166
+ const { exports } = loadClientModule()
167
+ const { clampRatio, MIN_RATIO, MAX_RATIO } = exports.__test
168
+
169
+ assert.equal(clampRatio(0.5), 0.5)
170
+ assert.equal(clampRatio(0.05), MIN_RATIO)
171
+ assert.equal(clampRatio(0.95), MAX_RATIO)
172
+ assert.equal(clampRatio('abc'), 0.46)
173
+ assert.equal(clampRatio(NaN), 0.46)
174
+ })
175
+
176
+ test('渲染:预览高度接到 maxHeight 上,且拖拽条存在', async () => {
177
+ installFetch((url) => (url.includes('/api/doc')
178
+ ? { ok: true, rel: '技术方案.md', title: '技术方案', text: '# T', truncated: false }
179
+ : listPayload()))
180
+
181
+ const { exports } = loadClientModule()
182
+ const { KnitBody } = exports.__test
183
+ const { nodes, renderAgain } = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
184
+ byClass(nodes, 'knit-doc')[0].props.onClick()
185
+ const after = await renderAgain()
186
+
187
+ const panel = panelOf(after)[0]
188
+ assert.ok(panel, '应有预览面板')
189
+ assert.equal(panel.props.style.maxHeight, '46%', '默认高度应接到 maxHeight')
190
+ assert.equal(byClass(after, 'knit-resize').length, 1, '应有拖拽条')
191
+ })
192
+
193
+ test('渲染:全屏切换后藏掉列表、去掉拖拽条、面板不再限高', async () => {
194
+ installFetch((url) => (url.includes('/api/doc')
195
+ ? { ok: true, rel: '技术方案.md', title: '技术方案', text: '# T', truncated: false }
196
+ : listPayload()))
197
+
198
+ const { exports } = loadClientModule()
199
+ const { KnitBody } = exports.__test
200
+ const { nodes, renderAgain } = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
201
+ byClass(nodes, 'knit-doc')[0].props.onClick()
202
+ let after = await renderAgain()
203
+
204
+ const fullBtn = byClass(after, 'knit-btn').find((n) => textOf(n) === '全屏')
205
+ assert.ok(fullBtn, '应有「全屏」按钮')
206
+ fullBtn.props.onClick()
207
+
208
+ after = await renderAgain()
209
+ const root = byClass(after, 'knit-root')[0]
210
+ assert.ok(String(root.props.className).includes('fullscreen'), '根节点应带 fullscreen')
211
+ assert.equal(byClass(after, 'knit-resize').length, 0, '全屏时不该有拖拽条')
212
+ assert.equal(panelOf(after)[0].props.style, undefined, '全屏时不再限高')
213
+ })
214
+
215
+ test('渲染:拖拽回调存在且可调用,不抛错', async () => {
216
+ installFetch((url) => (url.includes('/api/doc')
217
+ ? { ok: true, rel: '技术方案.md', title: '技术方案', text: '# T', truncated: false }
218
+ : listPayload()))
219
+
220
+ const { exports } = loadClientModule()
221
+ const { KnitBody } = exports.__test
222
+ const { nodes } = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
223
+ byClass(nodes, 'knit-doc')[0].props.onClick()
224
+ harness.render(h(KnitBody, { sessionId: 's1' }))
225
+ const after = harness.render(h(KnitBody, { sessionId: 's1' }))
226
+
227
+ const handle = byClass(after, 'knit-resize')[0]
228
+ assert.equal(typeof handle.props.onPointerDown, 'function')
229
+ // 没有真实 window 事件系统,至少不能因为缺 clientY 而崩
230
+ assert.doesNotThrow(() => handle.props.onPointerDown({
231
+ preventDefault() {},
232
+ clientY: 300,
233
+ }))
234
+ })
235
+
236
+ /* ── 3. 键盘导航 ───────────────────────────────────── */
237
+
238
+ /**
239
+ * 造一个键盘事件。
240
+ * @param {string} key - 键名
241
+ * @returns {object} 事件
242
+ */
243
+ function keyEvent(key) {
244
+ return { key, defaultPrevented: false, preventDefault() { this.defaultPrevented = true } }
245
+ }
246
+
247
+ /**
248
+ * 取列表容器节点。
249
+ * @param {object[]} nodes - 扁平节点
250
+ * @returns {object} 列表节点
251
+ */
252
+ function listNode(nodes) {
253
+ return byClass(nodes, 'knit-list')[0]
254
+ }
255
+
256
+ test('键盘:↓ 移动选中项并即时预览', async () => {
257
+ const docCalls = []
258
+ installFetch((url) => {
259
+ if (url.includes('/api/doc')) {
260
+ docCalls.push(decodeURIComponent(url.split('rel=')[1]))
261
+ return { ok: true, rel: 'x', title: 'x', text: '# x', truncated: false }
262
+ }
263
+ return listPayload()
264
+ })
265
+
266
+ const { exports } = loadClientModule()
267
+ const { KnitBody } = exports.__test
268
+ let { nodes, renderAgain } = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
269
+
270
+ // 初次渲染后 cursor 落在第一项
271
+ nodes = await renderAgain(true)
272
+ let docs = byClass(nodes, 'knit-doc')
273
+ assert.ok(String(docs[0].props.className).includes('cursor'), 'cursor 应落在第一项')
274
+
275
+ listNode(nodes).props.onKeyDown(keyEvent('ArrowDown'))
276
+ nodes = await renderAgain(true)
277
+ docs = byClass(nodes, 'knit-doc')
278
+ assert.ok(String(docs[1].props.className).includes('cursor'), '↓ 后 cursor 应到第二项')
279
+ assert.ok(docCalls.includes('docs/竞品分析.md'), '↓ 应即时拉取第二项正文')
280
+ assert.equal(panelOf(nodes).length, 1, '应打开预览')
281
+ })
282
+
283
+ test('键盘:↑ 到顶停住,不循环', async () => {
284
+ installFetch((url) => (url.includes('/api/doc')
285
+ ? { ok: true, rel: 'x', title: 'x', text: '# x', truncated: false }
286
+ : listPayload()))
287
+
288
+ const { exports } = loadClientModule()
289
+ const { KnitBody } = exports.__test
290
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
291
+ let nodes = await mounted.renderAgain(true)
292
+
293
+ listNode(nodes).props.onKeyDown(keyEvent('ArrowUp'))
294
+ nodes = await mounted.renderAgain(true)
295
+ assert.ok(String(byClass(nodes, 'knit-doc')[0].props.className).includes('cursor'), '↑ 到顶应停住')
296
+ })
297
+
298
+ test('键盘:Esc 收起预览', async () => {
299
+ installFetch((url) => (url.includes('/api/doc')
300
+ ? { ok: true, rel: 'x', title: 'x', text: '# x', truncated: false }
301
+ : listPayload()))
302
+
303
+ const { exports } = loadClientModule()
304
+ const { KnitBody } = exports.__test
305
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
306
+ let nodes = await mounted.renderAgain(true)
307
+
308
+ nodes = await mounted.renderAgain(true)
309
+ byClass(nodes, 'knit-doc')[0].props.onClick()
310
+ nodes = await mounted.renderAgain()
311
+ assert.equal(panelOf(nodes).length, 1, '先打开预览')
312
+
313
+ const event = keyEvent('Escape')
314
+ listNode(nodes).props.onKeyDown(event)
315
+ nodes = await mounted.renderAgain()
316
+ assert.equal(panelOf(nodes).length, 0, 'Esc 应收起预览')
317
+ assert.equal(event.defaultPrevented, true)
318
+ })
319
+
320
+ test('键盘:Enter 切换预览', async () => {
321
+ installFetch((url) => (url.includes('/api/doc')
322
+ ? { ok: true, rel: 'x', title: 'x', text: '# x', truncated: false }
323
+ : listPayload()))
324
+
325
+ const { exports } = loadClientModule()
326
+ const { KnitBody } = exports.__test
327
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
328
+ let nodes = await mounted.renderAgain(true)
329
+
330
+ listNode(nodes).props.onKeyDown(keyEvent('Enter'))
331
+ nodes = await mounted.renderAgain()
332
+ assert.equal(panelOf(nodes).length, 1, 'Enter 应打开预览')
333
+
334
+ listNode(nodes).props.onKeyDown(keyEvent('Enter'))
335
+ nodes = await mounted.renderAgain()
336
+ assert.equal(panelOf(nodes).length, 0, '再按 Enter 应收起')
337
+ })
338
+
339
+ test('键盘:列表为空时按键不报错', async () => {
340
+ installFetch(() => listPayload({ docs: [], total: 0 }))
341
+ const { exports } = loadClientModule()
342
+ const { KnitBody } = exports.__test
343
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
344
+ const nodes = await mounted.renderAgain(true)
345
+ assert.doesNotThrow(() => listNode(nodes).props.onKeyDown(keyEvent('ArrowDown')))
346
+ })
347
+
348
+ /* ── 4. 过滤框 ─────────────────────────────────────── */
349
+
350
+ test('过滤:输入即缩小列表并显示命中计数', async () => {
351
+ installFetch(() => listPayload())
352
+ const { exports } = loadClientModule()
353
+ const { KnitBody } = exports.__test
354
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
355
+ let nodes = await mounted.renderAgain(true)
356
+
357
+ assert.equal(byClass(nodes, 'knit-doc').length, 3, '初始 3 篇')
358
+ assert.equal(textByClass(nodes, 'knit-count'), '3 篇')
359
+
360
+ const input = byClass(nodes, 'knit-filter')[0]
361
+ assert.ok(input, '应有过滤输入框')
362
+ input.props.onChange({ target: { value: '竞品' } })
363
+ nodes = await mounted.renderAgain()
364
+
365
+ assert.equal(byClass(nodes, 'knit-doc').length, 1, '应只剩竞品分析')
366
+ assert.equal(textByClass(nodes, 'knit-count'), '1 / 3 篇', '应显示命中计数')
367
+ })
368
+
369
+ test('过滤:能按摘要和路径匹配,大小写不敏感', async () => {
370
+ installFetch(() => listPayload())
371
+ const { exports } = loadClientModule()
372
+ const { KnitBody } = exports.__test
373
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
374
+ let nodes = await mounted.renderAgain(true)
375
+
376
+ const input = byClass(nodes, 'knit-filter')[0]
377
+
378
+ input.props.onChange({ target: { value: 'cursor' } })
379
+ nodes = await mounted.renderAgain()
380
+ assert.equal(byClass(nodes, 'knit-doc').length, 1, '摘要里的 Cursor 应大小写不敏感命中')
381
+
382
+ input.props.onChange({ target: { value: 'docs/' } })
383
+ nodes = await mounted.renderAgain()
384
+ assert.equal(byClass(nodes, 'knit-doc').length, 2, '路径片段应命中')
385
+ })
386
+
387
+ test('过滤:无命中时给出明确空态,且不影响宿主请求', async () => {
388
+ const { calls } = installFetch(() => listPayload())
389
+ const { exports } = loadClientModule()
390
+ const { KnitBody } = exports.__test
391
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
392
+ let nodes = await mounted.renderAgain(true)
393
+ const before = calls.length
394
+
395
+ byClass(nodes, 'knit-filter')[0].props.onChange({ target: { value: 'zzzz' } })
396
+ nodes = await mounted.renderAgain()
397
+
398
+ assert.equal(byClass(nodes, 'knit-doc').length, 0)
399
+ assert.match(textByClass(nodes, 'knit-msg'), /没有匹配/)
400
+ assert.equal(calls.length, before, '过滤是纯客户端的,不该重新请求宿主')
401
+ })
402
+
403
+ test('过滤:输入框里按 Esc 清空', async () => {
404
+ installFetch(() => listPayload())
405
+ const { exports } = loadClientModule()
406
+ const { KnitBody } = exports.__test
407
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
408
+ let nodes = await mounted.renderAgain(true)
409
+
410
+ const input = byClass(nodes, 'knit-filter')[0]
411
+ input.props.onChange({ target: { value: '竞品' } })
412
+ nodes = await mounted.renderAgain()
413
+ assert.equal(byClass(nodes, 'knit-doc').length, 1)
414
+
415
+ let stopped = false
416
+ input.props.onKeyDown({ key: 'Escape', stopPropagation() { stopped = true } })
417
+ nodes = await mounted.renderAgain()
418
+ assert.equal(byClass(nodes, 'knit-doc').length, 3, 'Esc 应清空过滤')
419
+ assert.equal(stopped, true, '应阻止冒泡到列表的键盘处理')
420
+ })
421
+
422
+ test('过滤:过滤掉当前 cursor 后 cursor 落回第一项', async () => {
423
+ installFetch((url) => (url.includes('/api/doc')
424
+ ? { ok: true, rel: 'x', title: 'x', text: '# x', truncated: false }
425
+ : listPayload()))
426
+ const { exports } = loadClientModule()
427
+ const { KnitBody } = exports.__test
428
+ const mounted = await mount(KnitBody, { sessionId: 's1' }, ['', 'time'])
429
+ let nodes = await mounted.renderAgain(true)
430
+
431
+ // cursor 移到第三项
432
+ listNode(nodes).props.onKeyDown(keyEvent('ArrowDown'))
433
+ nodes = await mounted.renderAgain(true)
434
+ listNode(nodes).props.onKeyDown(keyEvent('ArrowDown'))
435
+ nodes = await mounted.renderAgain(true)
436
+ assert.ok(String(byClass(nodes, 'knit-doc')[2].props.className).includes('cursor'))
437
+
438
+ // 过滤掉它
439
+ byClass(nodes, 'knit-filter')[0].props.onChange({ target: { value: '技术' } })
440
+ nodes = await mounted.renderAgain(true)
441
+ assert.equal(byClass(nodes, 'knit-doc').length, 1)
442
+ assert.ok(String(byClass(nodes, 'knit-doc')[0].props.className).includes('cursor'), 'cursor 应落回唯一剩下的那项')
443
+ })