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,232 @@
1
+ /**
2
+ * 会话入口按钮测试。
3
+ *
4
+ * 背景:产物卡片「打开」右侧「更多」菜单加不了第三项(官方硬编码)。
5
+ * 替代方案是在官方留出的 **list 座位**上挂一个入口按钮:
6
+ * - conversation.session.header.utilities (会话头部右侧,右侧栏按钮旁边)
7
+ *
8
+ * 只挂这一处:输入框工具行那处实测「太刻意」,已去掉(回归用例见文件末尾)。
9
+ *
10
+ * 跑法:node --test test/
11
+ */
12
+ import test from 'node:test'
13
+ import assert from 'node:assert/strict'
14
+
15
+ import { loadClientModule, createHarness, byClass, textOf, makeLocale } from './harness.mjs'
16
+
17
+ const harness = createHarness()
18
+ const React = globalThis.__knitReact
19
+ const h = React.createElement
20
+
21
+ /* ── 脚手架 ─────────────────────────────────────────── */
22
+
23
+ /**
24
+ * 造一个假的 cordis 上下文。
25
+ * @param {object} services - 可用服务表(sidebarRight / betterSidebar / slots)
26
+ * @returns {{ctx: object, log: object}} 上下文与记录
27
+ */
28
+ function fakeCtx(services = {}) {
29
+ const log = { slots: [], tabs: [], bsTabs: [], effects: [] }
30
+ const { locale, registered } = makeLocale({ active: services.locale || 'zh' })
31
+ const table = { ...services, locale }
32
+ if (services.sidebarRightTabs) {
33
+ table.sidebarRightTabs = { register(def) { log.tabs.push(def); return () => {} } }
34
+ }
35
+ if (services.betterSidebar) {
36
+ table.betterSidebar = { registerTab(d) { log.bsTabs.push(d); return () => {} } }
37
+ }
38
+ table.slots = {
39
+ inject(name, cb) { cb(); return () => {} },
40
+ register(opts, component) { log.slots.push({ opts, component }); return () => {} },
41
+ }
42
+
43
+ const ctx = {
44
+ slots: table.slots,
45
+ locale,
46
+ effect(fn, label) { log.effects.push(label); return fn() },
47
+ get(name) { return table[name] },
48
+ inject(deps, callback) {
49
+ for (const dep of deps) if (!table[dep]) return
50
+ const face = { ...table }
51
+ face.effect = (fn) => { fn() }
52
+ callback(face)
53
+ },
54
+ }
55
+ return { ctx, log, registered }
56
+ }
57
+
58
+ /* ── openKnitPanel:宿主解析 ────────────────────────── */
59
+
60
+ test('openKnitPanel:优先用官方右侧栏 openTab(kind)', () => {
61
+ const { exports } = loadClientModule()
62
+ const { openKnitPanel } = exports.__test
63
+
64
+ const calls = []
65
+ const ctx = { get: (n) => (n === 'sidebarRight' ? { openTab: (k) => calls.push(k) } : undefined) }
66
+
67
+ assert.equal(openKnitPanel(ctx), true)
68
+ assert.deepEqual(calls, ['knit'], '应调用 openTab("knit")')
69
+ })
70
+
71
+ test('openKnitPanel:官方右侧栏不在时退回 better-sidebar', () => {
72
+ const { exports } = loadClientModule()
73
+ const { openKnitPanel } = exports.__test
74
+
75
+ const calls = []
76
+ const ctx = {
77
+ get: (n) => (n === 'betterSidebar' ? { openTab: (seed) => calls.push(seed) } : undefined),
78
+ }
79
+
80
+ assert.equal(openKnitPanel(ctx), true)
81
+ assert.deepEqual(calls, [{ type: 'knit:recent' }], '应调用 betterSidebar.openTab({type})')
82
+ })
83
+
84
+ test('openKnitPanel:两个宿主都没有时返回 false,不抛错', () => {
85
+ const { exports } = loadClientModule()
86
+ const { openKnitPanel } = exports.__test
87
+ assert.equal(openKnitPanel({ get: () => undefined }), false)
88
+ assert.equal(openKnitPanel(undefined), false)
89
+ assert.equal(openKnitPanel({}), false, 'ctx 没有 get 也要安全')
90
+ })
91
+
92
+ test('openKnitPanel:官方 openTab 抛错时退到 better-sidebar,不中断', () => {
93
+ const { exports } = loadClientModule()
94
+ const { openKnitPanel } = exports.__test
95
+
96
+ const calls = []
97
+ const ctx = {
98
+ get: (n) => {
99
+ if (n === 'sidebarRight') return { openTab: () => { throw new Error('炸了') } }
100
+ if (n === 'betterSidebar') return { openTab: (seed) => calls.push(seed) }
101
+ return undefined
102
+ },
103
+ }
104
+
105
+ assert.equal(openKnitPanel(ctx), true, '官方挂了应该还有兜底')
106
+ assert.deepEqual(calls, [{ type: 'knit:recent' }])
107
+ })
108
+
109
+ test('openKnitPanel:宿主服务存在但没有 openTab 时不误判成功', () => {
110
+ const { exports } = loadClientModule()
111
+ const { openKnitPanel } = exports.__test
112
+ assert.equal(openKnitPanel({ get: () => ({}) }), false)
113
+ })
114
+
115
+ /* ── 入口按钮组件 ───────────────────────────────────── */
116
+
117
+ test('入口按钮:渲染一个可点按钮,带无障碍标签', () => {
118
+ const { exports } = loadClientModule()
119
+ const { makeEntryButton } = exports.__test
120
+ const Button = makeEntryButton(() => true)
121
+
122
+ harness.reset()
123
+ const nodes = harness.render(h(Button, {}))
124
+ const btn = byClass(nodes, 'knit-entry')[0]
125
+
126
+ assert.ok(btn, '应渲染出 .knit-entry')
127
+ assert.equal(btn.type, 'button')
128
+ assert.equal(btn.props['aria-label'], 'Knit 最近文档')
129
+
130
+ // 图标是 mono SVG(不再是毛球 emoji);渲染细节由 test/icon.test.mjs 覆盖
131
+ const svg = nodes.find((n) => n.type === 'svg')
132
+ assert.ok(svg, '按钮里应是 SVG 图标')
133
+ })
134
+
135
+ test('入口按钮:点击触发打开,并阻止冒泡', () => {
136
+ const { exports } = loadClientModule()
137
+ const { makeEntryButton } = exports.__test
138
+
139
+ let opened = 0
140
+ let prevented = false
141
+ let stopped = false
142
+ const Button = makeEntryButton(() => { opened += 1; return true })
143
+
144
+ harness.reset()
145
+ const nodes = harness.render(h(Button, {}))
146
+ byClass(nodes, 'knit-entry')[0].props.onClick({
147
+ preventDefault() { prevented = true },
148
+ stopPropagation() { stopped = true },
149
+ })
150
+
151
+ assert.equal(opened, 1)
152
+ assert.equal(prevented, true, '要 preventDefault(避免触发头部其它行为)')
153
+ assert.equal(stopped, true, '要 stopPropagation')
154
+ })
155
+
156
+ test('入口按钮:没有宿主时点击不抛错', () => {
157
+ const { exports } = loadClientModule()
158
+ const { makeEntryButton } = exports.__test
159
+ const Button = makeEntryButton(() => false)
160
+
161
+ harness.reset()
162
+ const nodes = harness.render(h(Button, {}))
163
+ const btn = byClass(nodes, 'knit-entry')[0]
164
+ assert.doesNotThrow(() => btn.props.onClick({ preventDefault() {}, stopPropagation() {} }))
165
+ })
166
+
167
+ /* ── 注册:两处座位 ─────────────────────────────────── */
168
+
169
+ /**
170
+ * 从全部座位注册里挑出入口按钮那两条。
171
+ *
172
+ * 右侧栏的 tab body/title 也走同一个 slots,所以必须按 id 过滤,
173
+ * 不能拿 log.slots 的总数当断言。
174
+ *
175
+ * @param {object} log - fakeCtx 的记录
176
+ * @returns {object[]} 入口按钮的注册
177
+ */
178
+ function entryRegs(log) {
179
+ return log.slots.filter((s) => s.opts.id === 'knit:entry')
180
+ }
181
+
182
+ test('注册:入口按钮只挂会话头部一处 list 座位', () => {
183
+ const { ctx, log } = fakeCtx({ sidebarRightTabs: true })
184
+ const { exports } = loadClientModule()
185
+ exports.apply(ctx)
186
+
187
+ const entries = entryRegs(log)
188
+ assert.equal(entries.length, 1, '入口只挂一处')
189
+ assert.equal(entries[0].opts.name, 'conversation.session.header.utilities', '应挂到会话头部右侧')
190
+ assert.equal(entries[0].opts.id, 'knit:entry', 'id 要稳定,便于去重与替换')
191
+ assert.equal(typeof entries[0].opts.order, 'number', 'list 座位要按 order 排序')
192
+ assert.equal(typeof entries[0].component, 'function', '要给出组件')
193
+ })
194
+
195
+ test('注册:不再挂输入框工具行(那处实测太刻意)', () => {
196
+ const { ctx, log } = fakeCtx({ sidebarRightTabs: true })
197
+ const { exports } = loadClientModule()
198
+ exports.apply(ctx)
199
+
200
+ const seats = entryRegs(log).map((s) => s.opts.name)
201
+ assert.ok(!seats.includes('conversation.input.left'), '不该再挂输入框工具行')
202
+ assert.ok(!seats.includes('conversation.input.right'), '输入框右侧同样不挂')
203
+ })
204
+
205
+ test('注册:入口按钮用 list 语义(只给 id/order,不抢 key)', () => {
206
+ const { ctx, log } = fakeCtx({ sidebarRightTabs: true })
207
+ const { exports } = loadClientModule()
208
+ exports.apply(ctx)
209
+
210
+ for (const entry of entryRegs(log)) {
211
+ assert.equal(entry.opts.key, undefined, 'list 座位不用 key(那是 keyed 座位的东西)')
212
+ }
213
+ })
214
+
215
+ test('注册:即使没有任何侧边栏宿主,入口按钮照常注册(点击时才解析宿主)', () => {
216
+ const { ctx, log } = fakeCtx({})
217
+ const { exports } = loadClientModule()
218
+ exports.apply(ctx)
219
+
220
+ const seats = entryRegs(log).map((s) => s.opts.name)
221
+ assert.deepEqual(seats, ['conversation.session.header.utilities'])
222
+ })
223
+
224
+ test('注册:入口按钮与 tab 注册互不影响', () => {
225
+ const { ctx, log } = fakeCtx({ sidebarRightTabs: true, betterSidebar: true })
226
+ const { exports } = loadClientModule()
227
+ exports.apply(ctx)
228
+
229
+ assert.equal(log.tabs.length, 1, '官方右侧栏 tab 注册一份')
230
+ assert.equal(log.bsTabs.length, 1, 'better-sidebar tab 注册一份')
231
+ assert.equal(entryRegs(log).length, 1, '入口按钮一处,不重复')
232
+ })
@@ -0,0 +1,235 @@
1
+ /**
2
+ * 测试用的一套最小 React / DOM / fetch 替身。
3
+ *
4
+ * 目的:不改产品源码,就能在 Node 里把 __ModuleLoader__ 的工厂跑起来、
5
+ * 渲染组件树、模拟点击,并断言副作用(fetch 了哪个 URL、调了哪个宿主 API)。
6
+ *
7
+ * 只实现被测组件真正用到的那几个 hook:useState / useCallback / useEffect。
8
+ */
9
+ import { readFileSync } from 'node:fs'
10
+ import { fileURLToPath } from 'node:url'
11
+
12
+ const CLIENT_PATH = fileURLToPath(new URL('../src/client/client.js', import.meta.url))
13
+
14
+ /**
15
+ * 装一个假 window + 假 React,并把客户端模块的工厂函数取出来。
16
+ *
17
+ * @param {{primitives?: boolean}} options - `primitives: false` 用来测降级路径
18
+ * @returns {{factory: Function, markdownCalls: object[]}} 工厂与 MarkdownText 调用记录
19
+ */
20
+ export function loadClientModule(options = {}) {
21
+ const usePrimitives = options.primitives !== false
22
+
23
+ let captured = null
24
+ globalThis.window = {
25
+ __ModuleLoader__: { load(registration) { captured = registration } },
26
+ localStorage: {
27
+ _v: new Map(),
28
+ getItem(k) { return this._v.has(k) ? this._v.get(k) : null },
29
+ setItem(k, v) { this._v.set(k, String(v)) },
30
+ },
31
+ // 拖拽用的是 window 上的 pointermove / pointerup
32
+ addEventListener() {},
33
+ removeEventListener() {},
34
+ innerHeight: 800,
35
+ }
36
+
37
+ const markdownCalls = []
38
+ const primitives = {
39
+ // ⚠️ 真身是 React.memo(...) 的产物 —— 一个**对象**,不是函数。
40
+ // 测试替身必须照抄这个形态,否则「typeof === 'function'」这类守卫的 bug 测不出来。
41
+ MarkdownText: globalThis.__knitReact.memo(function MarkdownText(props) {
42
+ markdownCalls.push(props)
43
+ return { type: 'MarkdownText', props, children: [] }
44
+ }),
45
+ }
46
+
47
+ const requireStub = (spec) => {
48
+ if (spec === 'react') return globalThis.__knitReact
49
+ if (spec === '@deepseek-ai/dsh-client-ui-primitives') {
50
+ if (!usePrimitives) throw new Error('(测试)ui-primitives 不可用')
51
+ return primitives
52
+ }
53
+ throw new Error(`unexpected require: ${spec}`)
54
+ }
55
+
56
+ const source = readFileSync(CLIENT_PATH, 'utf8')
57
+ // 只为测试暴露内部件,产品文件本身不动
58
+ .replace(
59
+ "module.exports.inject = ['slots', 'locale']",
60
+ 'module.exports.__test = { KnitBody, OfficialTabBody, BetterSidebarTabBody, '
61
+ + 'sessionFileAddress, relTime, resolveRelative, pathImagesFor, clampRatio, '
62
+ + 'openKnitPanel, makeEntryButton, KnitGlyph, KnitTitle, KNIT_ICON_PATH, '
63
+ + 'MIN_RATIO, MAX_RATIO }\n'
64
+ + " module.exports.inject = ['slots', 'locale']",
65
+ )
66
+
67
+ new Function('window', source)(globalThis.window)
68
+ if (!captured) throw new Error('客户端模块没有调用 __ModuleLoader__.load')
69
+
70
+ return {
71
+ factory: captured.factory,
72
+ registration: captured,
73
+ markdownCalls,
74
+ exports: captured.factory(requireStub),
75
+ }
76
+ }
77
+
78
+ /**
79
+ * 装一套可重渲染的 hooks 替身。
80
+ *
81
+ * @returns {{install: Function, render: Function, flush: Function, reset: Function}}
82
+ */
83
+ export function createHarness() {
84
+ let hookStates = []
85
+ let hookIdx = 0
86
+ let pendingEffects = []
87
+
88
+ const React = {
89
+ createElement: (type, props, ...children) => ({
90
+ type,
91
+ props: props || {},
92
+ children: children.flat().filter((c) => c !== null && c !== undefined && c !== false),
93
+ }),
94
+ useState(init) {
95
+ const i = hookIdx++
96
+ if (!(i in hookStates)) hookStates[i] = typeof init === 'function' ? init() : init
97
+ return [hookStates[i], (v) => { hookStates[i] = typeof v === 'function' ? v(hookStates[i]) : v }]
98
+ },
99
+ useCallback: (fn) => fn,
100
+ useEffect: (fn) => { pendingEffects.push(fn) },
101
+ // 测试里不做记忆化:每次渲染重算即可,行为与真实 useMemo 等价
102
+ useMemo: (fn) => fn(),
103
+ // 真实 useRef 跨渲染稳定;这里每次渲染新建,但被测代码只读 .current(测试环境无 DOM 时为 null)
104
+ useRef: (init) => ({ current: init === undefined ? null : init }),
105
+ // 照抄 React.memo 的真实形态:返回对象而不是函数
106
+ memo: (fn) => ({ $$typeof: Symbol.for('react.memo'), type: fn, compare: null }),
107
+ }
108
+
109
+ globalThis.__knitReact = React
110
+ globalThis.setTimeout = () => 0
111
+ globalThis.clearTimeout = () => {}
112
+
113
+ return {
114
+ /** 重置 hook 槽位,供每个用例独立开始。 */
115
+ reset() { hookStates = []; hookIdx = 0; pendingEffects = [] },
116
+ /** 预置 useState 的初值(按 hook 调用顺序)。 */
117
+ seed(values) { hookStates = values.slice() },
118
+ /**
119
+ * 渲染一棵树并**展开函数组件**,返回扁平节点列表。
120
+ * 展开很重要:不展开就看不出子组件真实渲染了什么。
121
+ */
122
+ render(element) {
123
+ hookIdx = 0
124
+ pendingEffects = []
125
+ const walk = (node, out = []) => {
126
+ if (!node || typeof node !== 'object') return out
127
+ if (Array.isArray(node)) { node.forEach((n) => walk(n, out)); return out }
128
+ // React.memo / forwardRef 包出来的类型是对象,真身挂在 .type 上
129
+ const type = node.type
130
+ if (type && typeof type === 'object' && typeof type.type === 'function') {
131
+ walk(type.type(node.props), out)
132
+ return out
133
+ }
134
+ if (typeof type === 'function') { walk(type(node.props), out); return out }
135
+ out.push(node)
136
+ ;(node.children || []).forEach((c) => walk(c, out))
137
+ return out
138
+ }
139
+ return walk(element)
140
+ },
141
+ /** 跑一遍已登记的 useEffect(并给微任务一个 tick)。 */
142
+ async flush() {
143
+ const fx = pendingEffects.slice()
144
+ pendingEffects = []
145
+ fx.forEach((f) => f())
146
+ await new Promise((r) => setImmediate(r))
147
+ },
148
+ }
149
+ }
150
+
151
+ /**
152
+ * 把 `{name}` 占位符换成实参(与产品里的 format 同语义)。
153
+ * @param {string} template - 模板串
154
+ * @param {object} [params] - 实参
155
+ * @returns {string} 结果
156
+ */
157
+ export function formatTemplate(template, params) {
158
+ if (!params) return template
159
+ return template.replace(/\{(\w+)\}/g, (whole, key) => (
160
+ Object.prototype.hasOwnProperty.call(params, key) ? String(params[key]) : whole
161
+ ))
162
+ }
163
+
164
+ /**
165
+ * 造一个假的 locale 服务,语义对齐官方 LocaleRuntime:
166
+ * - `register(ns, { zh, en })` 收下词典
167
+ * - `bind(ns)` 返回「按调用时读取活动语言」的翻译函数
168
+ *
169
+ * @param {{active?: string}} [options] - 活动语言,默认 zh
170
+ * @returns {{locale: object, registered: object, active: string}} 替身与词典
171
+ */
172
+ export function makeLocale(options = {}) {
173
+ const active = options.active || 'zh'
174
+ const registered = {}
175
+
176
+ const locale = {
177
+ register(ns, dicts) {
178
+ registered[ns] = dicts
179
+ return () => {}
180
+ },
181
+ bind(ns) {
182
+ return (key, params) => {
183
+ const dict = registered[ns] && registered[ns][active]
184
+ const template = dict && dict[key] !== undefined ? dict[key] : key
185
+ return formatTemplate(template, params)
186
+ }
187
+ },
188
+ getLocale() { return { active, locales: [], revision: 0 } },
189
+ getSnapshot() { return { active, locales: [], revision: 0 } },
190
+ subscribe() { return () => {} },
191
+ }
192
+
193
+ return { locale, registered, active }
194
+ }
195
+
196
+ /**
197
+ * 从扁平节点里按 className 取节点(**子串**匹配)。
198
+ * @param {object[]} nodes - 扁平节点
199
+ * @param {string} className - 要匹配的 class(子串)
200
+ * @returns {object[]} 命中的节点
201
+ */
202
+ export function byClass(nodes, className) {
203
+ return nodes.filter((n) => String(n.props.className || '').includes(className))
204
+ }
205
+
206
+ /**
207
+ * 从扁平节点里按 className 取节点(**整段**匹配)。
208
+ *
209
+ * 子串匹配会把 `knit-preview` 同时命中 `knit-preview-head` / `-body` / `-title`,
210
+ * 计数类断言必须用这个。
211
+ *
212
+ * @param {object[]} nodes - 扁平节点
213
+ * @param {string} className - 要匹配的完整 class
214
+ * @returns {object[]} 命中的节点
215
+ */
216
+ export function byExactClass(nodes, className) {
217
+ return nodes.filter((n) => String(n.props.className || '') === className)
218
+ }
219
+
220
+ /**
221
+ * 取节点下所有字符串子节点的拼接。
222
+ * @param {object} node - 节点
223
+ * @returns {string} 文本
224
+ */
225
+ export function textOf(node) {
226
+ const acc = []
227
+ const walk = (n) => {
228
+ if (typeof n === 'string') { acc.push(n); return }
229
+ if (!n || typeof n !== 'object') return
230
+ if (Array.isArray(n)) { n.forEach(walk); return }
231
+ ;(n.children || []).forEach(walk)
232
+ }
233
+ walk(node)
234
+ return acc.join('')
235
+ }