dsh-web-toggle 0.0.0-stage → 0.1.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,355 @@
1
+ /**
2
+ * 离线验证 Browser 半侧(client.js):用极简的 React 打桩 + 假的 ctx/remote,
3
+ * 检查槽位注册、亮灭两态渲染、点击后发出的命令、以及各类失败提示。
4
+ * 这不是浏览器,只保证组件逻辑与命令线格式正确。
5
+ * 用法:node tests/client.test.mjs
6
+ */
7
+ import assert from 'node:assert/strict'
8
+
9
+ // ---- 浏览器环境打桩 --------------------------------------------------------
10
+ const storages = new Map()
11
+ globalThis.localStorage = {
12
+ getItem: (key) => (storages.has(key) ? storages.get(key) : null),
13
+ setItem: (key, value) => storages.set(key, String(value)),
14
+ removeItem: (key) => storages.delete(key),
15
+ }
16
+ // 探针用的 0ms 定时器只入队,由 flushTimers() 手动执行,避免测试里冒出意料之外的第二次命令。
17
+ let timers = []
18
+ globalThis.window = {
19
+ setTimeout: (fn) => {
20
+ timers.push(fn)
21
+ return timers.length
22
+ },
23
+ clearTimeout: () => {},
24
+ }
25
+ /** 执行所有排队中的定时器(挂载探针就在这里面)。 */
26
+ const flushTimers = () => {
27
+ const pending = timers
28
+ timers = []
29
+ for (const fn of pending) fn()
30
+ }
31
+
32
+ // ---- 极简 React 打桩 ------------------------------------------------------
33
+ // 真实环境里 client.js 的 factory 只在页面加载时执行一次,之后切会话是组件重挂载。
34
+ // 所以这里:factory 只跑一次(模块级缓存共享),每次 mount 只换一套 hook 池。
35
+ const makePool = () => {
36
+ const values = new Map()
37
+ const effects = new Map()
38
+ let cursor = 0
39
+ return {
40
+ begin() {
41
+ cursor = 0
42
+ },
43
+ useState(initial) {
44
+ const index = cursor++
45
+ if (!values.has(index)) values.set(index, typeof initial === 'function' ? initial() : initial)
46
+ return [values.get(index), (next) => values.set(index, typeof next === 'function' ? next(values.get(index)) : next)]
47
+ },
48
+ useRef(initial) {
49
+ const index = cursor++
50
+ if (!values.has(index)) values.set(index, { current: initial })
51
+ return values.get(index)
52
+ },
53
+ useEffect(run, deps) {
54
+ const index = cursor++
55
+ const previous = effects.get(index)
56
+ const unchanged =
57
+ previous !== undefined &&
58
+ deps !== undefined &&
59
+ previous.deps !== undefined &&
60
+ previous.deps.length === deps.length &&
61
+ deps.every((item, at) => Object.is(item, previous.deps[at]))
62
+ if (unchanged) return
63
+ effects.set(index, { deps })
64
+ run()
65
+ },
66
+ }
67
+ }
68
+ let currentPool
69
+ const React = {
70
+ createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }),
71
+ useState: (initial) => currentPool.useState(initial),
72
+ useRef: (initial) => currentPool.useRef(initial),
73
+ useEffect: (run, deps) => currentPool.useEffect(run, deps),
74
+ }
75
+
76
+ // ---- 载入 client.js(只用它交给 ModuleLoader 的描述) ---------------------
77
+ let loadedModule
78
+ globalThis.window.__ModuleLoader__ = {
79
+ load(definition) {
80
+ loadedModule = definition
81
+ },
82
+ }
83
+ await import('../client.js')
84
+ assert.ok(loadedModule !== undefined, 'client.js 应调用 __ModuleLoader__.load')
85
+ assert.equal(loadedModule.id, 'dsh-web-toggle', '浏览器模块 id 必须等于包名')
86
+
87
+ // —— 页面级单例:factory 一次、apply 一次,等价于同一个页面活到测试结束 ——
88
+ const page = (() => {
89
+ const moduleExports = loadedModule.factory((name) => {
90
+ if (name === 'react') return React
91
+ throw new Error(`unexpected require: ${name}`)
92
+ })
93
+ assert.deepEqual(moduleExports.inject, ['slots', 'locale', 'remote', 'remote.commands'])
94
+
95
+ const dictionary = {}
96
+ const state = { slot: undefined, component: undefined, remote: undefined, effects: [] }
97
+ const ctx = {
98
+ locale: {
99
+ register(namespace, localeOrDicts, dict) {
100
+ assert.equal(namespace, 'web-toggle')
101
+ // 真实接口:register(ns, 'zh', {...}) 或 register(ns, { en: {...}, zh: {...} })
102
+ if (typeof localeOrDicts === 'string') {
103
+ Object.assign(dictionary, dict)
104
+ return
105
+ }
106
+ for (const [locale, entries] of Object.entries(localeOrDicts)) {
107
+ assert.ok(['en', 'zh'].includes(locale), `意外的 locale:${locale}`)
108
+ Object.assign(dictionary, entries)
109
+ }
110
+ },
111
+ bind() {
112
+ return (key) => dictionary[key] ?? key
113
+ },
114
+ },
115
+ slots: {
116
+ inject(name, factory) {
117
+ assert.equal(name, 'conversation.input.left')
118
+ factory()
119
+ },
120
+ register(definition, component) {
121
+ state.slot = definition
122
+ state.component = component
123
+ return () => {}
124
+ },
125
+ },
126
+ effect(run, label) {
127
+ state.effects.push(label)
128
+ return run()
129
+ },
130
+ get(name) {
131
+ return name === 'remote' ? state.remote : undefined
132
+ },
133
+ }
134
+ moduleExports.apply(ctx)
135
+ const t = (key) => dictionary[key] ?? key
136
+ return { state, dictionary, t }
137
+ })()
138
+
139
+ /**
140
+ * 挂载一次组件实例:新的 hook 池,会话 id 可变。
141
+ * 模块级状态(已探过的会话等)与 page 单例一起跨 mount 保留,正好模拟切走再切回。
142
+ */
143
+ function mount(sessionId = 'session-a') {
144
+ currentPool = makePool()
145
+ const render = (props) => {
146
+ currentPool.begin()
147
+ return page.state.component({
148
+ t: page.t,
149
+ sessionId,
150
+ useSessions: (selector) => selector({ byId: {} }),
151
+ ...props,
152
+ })
153
+ }
154
+ return { state: page.state, dictionary: page.dictionary, render, t: page.t }
155
+ }
156
+ /** 一个回固定结果的假 remote,同时记录每次调用。 */
157
+ const stubRemote = (calls, text) => ({
158
+ commands: {
159
+ execute: async (...args) => {
160
+ calls.push(args)
161
+ return { ok: true, value: { result: { kind: 'success', text } } }
162
+ },
163
+ },
164
+ })
165
+
166
+ // ---- 1. 默认渲染:亮着 -----------------------------------------------------
167
+ {
168
+ storages.clear()
169
+ const { render, t } = mount('s1')
170
+ const tree = render({})
171
+ const button = tree.children[0]
172
+ assert.equal(tree.props['data-off'], 'false')
173
+ assert.equal(button.props['aria-pressed'], 'true')
174
+ assert.equal(button.props.title, t('title.on'))
175
+ assert.equal(tree.children[1], null, '初始不应有提示')
176
+ console.log('1 默认亮态渲染 ok')
177
+ }
178
+
179
+ // ---- 2. 槽位定义与样式表 ---------------------------------------------------
180
+ {
181
+ const { state, t } = mount('s2')
182
+ assert.equal(state.slot.name, 'conversation.input.left')
183
+ assert.equal(state.slot.id, 'web-toggle')
184
+ assert.equal(state.slot.locale, 'web-toggle')
185
+ assert.equal(state.slot.order, 11)
186
+ assert.equal(typeof state.slot.label(), 'string')
187
+ assert.ok(t('label') !== 'label', '运行期字典应已注册')
188
+ assert.ok(state.effects.some((label) => String(label).includes('stylesheet')))
189
+ console.log('2 槽位与样式注册 ok')
190
+ }
191
+
192
+ // ---- 3. 点一次:发 off,灭态 + 提示,并记住 ------------------------------
193
+ {
194
+ storages.clear()
195
+ const { state, render, dictionary } = mount('s3')
196
+ const calls = []
197
+ state.remote = stubRemote(calls, '联网工具已关闭 [web:off]')
198
+ let tree = render({})
199
+ tree.children[0].props.onClick()
200
+ await Promise.resolve()
201
+ await Promise.resolve()
202
+ assert.equal(calls.length, 1)
203
+ assert.equal(calls[0].length, 3, 'execute 应带三个 wire 参数')
204
+ assert.deepEqual(calls[0].slice(0, 2), ['s3', '/webtoggle off'])
205
+ tree = render({})
206
+ assert.equal(tree.props['data-off'], 'true')
207
+ assert.equal(tree.children[0].props['aria-pressed'], 'false')
208
+ assert.equal(globalThis.localStorage.getItem('dsh-web-toggle:off:s3'), '1', '应记住 off')
209
+ assert.equal(tree.children[1].props['data-kind'], 'ok')
210
+ assert.equal(tree.children[1].children[0], dictionary['note.off'])
211
+ console.log('3 关闭流程 ok')
212
+ }
213
+
214
+ // ---- 4. 记住 off 后重新挂载:显示灭态、探针只发一次、宿主确认时不出提示 --
215
+ {
216
+ storages.clear()
217
+ globalThis.localStorage.setItem('dsh-web-toggle:off:s4', '1')
218
+ const calls = []
219
+ const first = mount('s4')
220
+ first.state.remote = stubRemote(calls, '本来就是关闭的 [web:off]')
221
+ let tree = first.render({})
222
+ assert.equal(tree.props['data-off'], 'true', '应读回记住的状态')
223
+ flushTimers()
224
+ await Promise.resolve()
225
+ await Promise.resolve()
226
+ await Promise.resolve()
227
+ assert.equal(calls.length, 1, '挂载应只探一次')
228
+ assert.equal(calls[0][1], '/webtoggle status')
229
+ tree = first.render({})
230
+ assert.equal(tree.props['data-off'], 'true')
231
+ assert.equal(tree.children[1], null, '宿主确认仍是关闭时不应弹提示(切来切去不再重复出现)')
232
+
233
+ // 再点一次 → on
234
+ const onCalls = []
235
+ first.state.remote = stubRemote(onCalls, '联网工具已恢复 [web:on]')
236
+ tree.children[0].props.onClick()
237
+ await Promise.resolve()
238
+ await Promise.resolve()
239
+ assert.equal(onCalls[0][1], '/webtoggle on')
240
+ tree = first.render({})
241
+ assert.equal(tree.props['data-off'], 'false')
242
+ assert.equal(globalThis.localStorage.getItem('dsh-web-toggle:off:s4'), null)
243
+ console.log('4 重新挂载与恢复 ok')
244
+ }
245
+
246
+ // ---- 5. 切走再切回:不重发 status、不再弹提示 ---------------------------
247
+ {
248
+ storages.clear()
249
+ globalThis.localStorage.setItem('dsh-web-toggle:off:s5', '1')
250
+ const firstCalls = []
251
+ const first = mount('s5')
252
+ first.state.remote = stubRemote(firstCalls, '本来就是关闭的 [web:off]')
253
+ first.render({})
254
+ flushTimers()
255
+ await Promise.resolve()
256
+ await Promise.resolve()
257
+ assert.equal(firstCalls.length, 1)
258
+
259
+ // 模拟切到别的会话再切回来:组件重新挂载,模块级缓存还在
260
+ const secondCalls = []
261
+ const second = mount('s5')
262
+ second.state.remote = stubRemote(secondCalls, '本来就是关闭的 [web:off]')
263
+ const tree = second.render({})
264
+ flushTimers()
265
+ await Promise.resolve()
266
+ await Promise.resolve()
267
+ assert.equal(secondCalls.length, 0, '同一页面内不应重复探测')
268
+ assert.equal(tree.props['data-off'], 'true')
269
+ assert.equal(tree.children[1], null, '不应再次弹提示')
270
+ console.log('5 切走切回不重复提示 ok')
271
+ }
272
+
273
+ // ---- 6. 轮次进行中:按钮禁用、点了也不发命令 -----------------------------
274
+ {
275
+ storages.clear()
276
+ const { state, render, t } = mount('s6')
277
+ let called = 0
278
+ state.remote = { commands: { execute: async () => (called++, { ok: true, value: { result: { kind: 'success', text: '[web:on]' } } }) } }
279
+ const tree = render({ useSessions: (selector) => selector({ byId: { s6: { running: true } } }) })
280
+ assert.equal(tree.children[0].props.disabled, true)
281
+ assert.equal(tree.children[0].props.title, t('title.running'))
282
+ assert.equal(called, 0)
283
+ console.log('6 运行中禁用 ok')
284
+ }
285
+
286
+ // ---- 7. 失败分支 ---------------------------------------------------------
287
+ {
288
+ storages.clear()
289
+ const { state, render, t } = mount('s7')
290
+
291
+ // 7.1 没有 remote
292
+ state.remote = undefined
293
+ let tree = render({})
294
+ tree.children[0].props.onClick()
295
+ await Promise.resolve()
296
+ tree = render({})
297
+ assert.equal(tree.children[1].props['data-kind'], 'error')
298
+ assert.equal(tree.children[1].children[0], t('error.noRemote'))
299
+
300
+ // 7.2 命令未注册(value undefined)
301
+ state.remote = { commands: { execute: async () => ({ ok: true, value: undefined }) } }
302
+ tree = render({})
303
+ tree.children[0].props.onClick()
304
+ await Promise.resolve()
305
+ await Promise.resolve()
306
+ tree = render({})
307
+ assert.equal(tree.children[1].children[0], t('error.commandMissing'))
308
+
309
+ // 7.3 Remote 失败
310
+ state.remote = { commands: { execute: async () => ({ ok: false, error: { message: 'socket closed' } }) } }
311
+ tree = render({})
312
+ tree.children[0].props.onClick()
313
+ await Promise.resolve()
314
+ await Promise.resolve()
315
+ tree = render({})
316
+ assert.match(tree.children[1].children[0], /socket closed/)
317
+
318
+ // 7.4 Host 明确拒绝:原文展示,状态不变
319
+ state.remote = {
320
+ commands: {
321
+ execute: async () => ({ ok: true, value: { result: { kind: 'error', text: '当前任务正在执行,等这一轮结束后再切换联网开关' } } }),
322
+ },
323
+ }
324
+ tree = render({})
325
+ tree.children[0].props.onClick()
326
+ await Promise.resolve()
327
+ await Promise.resolve()
328
+ tree = render({})
329
+ assert.equal(tree.children[1].children[0], '当前任务正在执行,等这一轮结束后再切换联网开关')
330
+ assert.equal(tree.props['data-off'], 'false', '被拒绝时状态不变')
331
+ console.log('7 失败分支 ok')
332
+ }
333
+
334
+ // ---- 8. 挂载探针:记住 off 但宿主已重置 → 纠正成亮态并提示 -------------
335
+ {
336
+ storages.clear()
337
+ globalThis.localStorage.setItem('dsh-web-toggle:off:s8', '1')
338
+ const { state, render, t } = mount('s8')
339
+ const calls = []
340
+ state.remote = stubRemote(calls, '本来就是开启的 [web:on]')
341
+ let tree = render({})
342
+ flushTimers()
343
+ await Promise.resolve()
344
+ await Promise.resolve()
345
+ assert.equal(calls.length, 1)
346
+ assert.equal(calls[0][1], '/webtoggle status')
347
+ assert.equal(globalThis.localStorage.getItem('dsh-web-toggle:off:s8'), null, '应把记忆纠正成 on')
348
+ tree = render({})
349
+ assert.equal(tree.props['data-off'], 'false')
350
+ assert.equal(tree.children[1].props['data-kind'], 'ok')
351
+ assert.equal(tree.children[1].children[0], t('note.syncedOn'))
352
+ console.log('8 挂载探针纠正 ok')
353
+ }
354
+
355
+ console.log('\n全部通过')