@linxin666/dsh-pet 0.4.5 → 0.4.6
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.
- package/README.i18n.yaml +2 -2
- package/README.md +28 -2
- package/README.zh.md +28 -2
- package/lib/client.js +76 -39
- package/lib/client.js.map +1 -1
- package/lib/index.js +280 -25
- package/lib/types/announce.d.ts +16 -0
- package/lib/types/announce.d.ts.map +1 -1
- package/lib/types/announce.js +16 -0
- package/lib/types/client/PetDockEntry.d.ts +6 -0
- package/lib/types/client/PetDockEntry.d.ts.map +1 -1
- package/lib/types/client/PetDockEntry.js +1 -1
- package/lib/types/client/PetSettingsCard.d.ts +4 -0
- package/lib/types/client/PetSettingsCard.d.ts.map +1 -1
- package/lib/types/client/PetSettingsCard.js +16 -1
- package/lib/types/client/PetSprite.d.ts +7 -0
- package/lib/types/client/PetSprite.d.ts.map +1 -1
- package/lib/types/client/PetSprite.js +23 -13
- package/lib/types/client/index.d.ts.map +1 -1
- package/lib/types/client/index.js +42 -10
- package/lib/types/client/locales.d.ts +4 -0
- package/lib/types/client/locales.d.ts.map +1 -1
- package/lib/types/client/locales.js +4 -0
- package/lib/types/index.d.ts +14 -3
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js +15 -2
- package/lib/types/panel-actions.d.ts +96 -0
- package/lib/types/panel-actions.d.ts.map +1 -0
- package/lib/types/panel-actions.js +134 -0
- package/lib/types/routes.d.ts.map +1 -1
- package/lib/types/routes.js +10 -0
- package/lib/types/service.d.ts +137 -9
- package/lib/types/service.d.ts.map +1 -1
- package/lib/types/service.js +151 -19
- package/package.json +1 -1
- package/src/announce.ts +17 -0
- package/src/client/PetDockEntry.test.tsx +1 -0
- package/src/client/PetDockEntry.tsx +7 -0
- package/src/client/PetSettingsCard.test.tsx +88 -0
- package/src/client/PetSettingsCard.tsx +31 -0
- package/src/client/PetSprite.test.tsx +197 -0
- package/src/client/PetSprite.tsx +56 -12
- package/src/client/index.test.tsx +74 -4
- package/src/client/index.ts +42 -10
- package/src/client/locales.ts +4 -0
- package/src/index.test.ts +22 -0
- package/src/index.ts +28 -2
- package/src/panel-actions.test.ts +130 -0
- package/src/panel-actions.ts +182 -0
- package/src/routes.ts +9 -0
- package/src/service.test.ts +128 -0
- package/src/service.ts +206 -22
package/src/client/index.ts
CHANGED
|
@@ -42,7 +42,7 @@ import { live2dRenderer } from './renderers/live2d.ts'
|
|
|
42
42
|
import { frames2dRenderer } from './renderers/frames2d.ts'
|
|
43
43
|
import { registerPetUiTeardown, takeoverPetUiTeardown } from './ui-teardown.ts'
|
|
44
44
|
import { PetSettingsSection, PetSettingsCardController, type PetSettings } from './PetSettingsCard.tsx'
|
|
45
|
-
import { NS, en, zh
|
|
45
|
+
import { NS, en, zh } from './locales.ts'
|
|
46
46
|
import { mainViewSessionId } from './main-session.ts'
|
|
47
47
|
import { reportDailyHeartbeat } from './telemetry.ts'
|
|
48
48
|
|
|
@@ -56,6 +56,7 @@ interface PetHttpApi {
|
|
|
56
56
|
setConfig(patch: Partial<PetDisplayConfig>): Promise<{ ok: true; display: PetDisplayConfig }>
|
|
57
57
|
setName(name: string): Promise<{ ok: true; name: string } | { ok: false; error: string }>
|
|
58
58
|
setPet(petId: string): Promise<{ ok: true; petId: string } | { ok: false; error: string }>
|
|
59
|
+
panelAction(id: string): Promise<{ ok: boolean; error?: string }>
|
|
59
60
|
setSkin(skin?: string): Promise<{ ok: boolean; error?: string; skin?: string }>
|
|
60
61
|
gameplayTouch(zone?: string): Promise<PetGameplayVerbResult>
|
|
61
62
|
gameplaySetMode(mode: string | null): Promise<PetGameplayVerbResult>
|
|
@@ -88,6 +89,7 @@ const petApi: PetHttpApi = {
|
|
|
88
89
|
setConfig: (patch) => petFetch('/api/pet/set-config', patch),
|
|
89
90
|
setName: (name) => petFetch('/api/pet/set-name', { name }),
|
|
90
91
|
setPet: (petId) => petFetch('/api/pet/set-pet', { petId }),
|
|
92
|
+
panelAction: (id) => petFetch('/api/pet/panel-action', { id }),
|
|
91
93
|
setSkin: (skin) => petFetch('/api/pet/set-skin', skin === undefined ? {} : { skin }),
|
|
92
94
|
gameplayTouch: (zone) => petFetch('/api/pet/gameplay/touch', zone === undefined ? {} : { zone }),
|
|
93
95
|
gameplaySetMode: (mode) => petFetch('/api/pet/gameplay/mode', { mode }),
|
|
@@ -176,19 +178,26 @@ class DeferredSettingsForm implements ConfigForm<PetSettings> {
|
|
|
176
178
|
this.ctx = ctx
|
|
177
179
|
this.fallback = ctx.configForms.get<PetSettings>(this.resolveFallbackEntryId())
|
|
178
180
|
// No binder yet: the aggregate publishes it after an async mount, so keep
|
|
179
|
-
// probing. A shared form that can answer for itself is adopted at
|
|
181
|
+
// probing. A shared form that can already answer for itself is adopted at
|
|
182
|
+
// once; one still loading has simply not been filled in yet.
|
|
180
183
|
if (!this.resolve() && !this.fallbackSettled()) this.scheduleRetry()
|
|
181
184
|
else if (this.current === undefined) this.adoptFallback()
|
|
182
185
|
}
|
|
183
186
|
|
|
184
187
|
/**
|
|
185
|
-
* True
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
+
* True only once the shared mirror answers for the pet namespace itself.
|
|
189
|
+
*
|
|
190
|
+
* 'ready' is the only state that answers (#1813). A host-persisted row starts
|
|
191
|
+
* out as 'loading' — the mirror has published no view yet — and that is not
|
|
192
|
+
* an answer: adopting it on sight drops the retry window, and under the
|
|
193
|
+
* aggregate, which serves only the renamed 'web-ui-pet' row, the form then
|
|
194
|
+
* settles into 'unavailable' and the page stays "not exposed" for good. So
|
|
195
|
+
* 'loading' and 'unavailable' both keep the window open and let the binder be
|
|
196
|
+
* adopted the moment the aggregate publishes it.
|
|
188
197
|
*/
|
|
189
198
|
private fallbackSettled(): boolean {
|
|
190
199
|
try {
|
|
191
|
-
return this.fallback.getSnapshot().status
|
|
200
|
+
return this.fallback.getSnapshot().status === 'ready'
|
|
192
201
|
} catch {
|
|
193
202
|
return false
|
|
194
203
|
}
|
|
@@ -241,9 +250,10 @@ class DeferredSettingsForm implements ConfigForm<PetSettings> {
|
|
|
241
250
|
}
|
|
242
251
|
|
|
243
252
|
/**
|
|
244
|
-
* Adopt the shared per-entry form. It is used immediately unless it
|
|
245
|
-
*
|
|
246
|
-
* and the retry window takes over
|
|
253
|
+
* Adopt the shared per-entry form. It is used immediately unless it cannot
|
|
254
|
+
* answer yet (still loading, or reporting the namespace unavailable), in which
|
|
255
|
+
* case the binder may still be on its way and the retry window takes over
|
|
256
|
+
* (see scheduleRetry).
|
|
247
257
|
*/
|
|
248
258
|
private adoptFallback(): void {
|
|
249
259
|
this.current = this.fallback
|
|
@@ -576,6 +586,19 @@ export function apply(ctx: ClientContext): void {
|
|
|
576
586
|
// Ignore; next poll resyncs.
|
|
577
587
|
})
|
|
578
588
|
},
|
|
589
|
+
// A panel action click (issue #6) travels back to the host, which
|
|
590
|
+
// dispatches it to the plugin that registered the action. The plugin's
|
|
591
|
+
// own callback does the work; the browser half only reports the id, and
|
|
592
|
+
// the next poll brings back whatever that callback changed. A click on
|
|
593
|
+
// an action the plugin already disposed answers { ok: false } — the
|
|
594
|
+
// button was one poll tick stale, which is not a pet failure.
|
|
595
|
+
panelAction: (id) => {
|
|
596
|
+
petApi.panelAction(id).then((result) => {
|
|
597
|
+
if (result.ok) pollNow()
|
|
598
|
+
}, () => {
|
|
599
|
+
// Ignore; next poll resyncs.
|
|
600
|
+
})
|
|
601
|
+
},
|
|
579
602
|
feedbackDone: () => {
|
|
580
603
|
setFeedback(null)
|
|
581
604
|
},
|
|
@@ -630,7 +653,16 @@ export function apply(ctx: ClientContext): void {
|
|
|
630
653
|
// root then owns the whole surface, so a root-keyed suppressor (the
|
|
631
654
|
// portrait mobile layer, which hides [data-dsh-plugin="pet"]) really
|
|
632
655
|
// hides the sprite instead of missing the portaled float.
|
|
633
|
-
|
|
656
|
+
//
|
|
657
|
+
// The floating surface has no session-scoped locale seat, so it must be
|
|
658
|
+
// handed the framework one explicitly. Resolving its copy from the
|
|
659
|
+
// plugin's own zh/en dictionary keyed on <html lang> sent every
|
|
660
|
+
// registered language except English to Chinese: a ru/ja/de page showed a
|
|
661
|
+
// Chinese panel while the settings card beside it was translated. Binding
|
|
662
|
+
// the 'pet' namespace instead follows the active language, the English
|
|
663
|
+
// fallback, and every language pack that registers a dictionary for it
|
|
664
|
+
// (the settings section label already resolves through the same seat).
|
|
665
|
+
petRoot.render(createElement(PetDockEntry, { ...injected(), t: ctx.locale.bind(NS), portalTarget: container }))
|
|
634
666
|
|
|
635
667
|
let uiGone = false
|
|
636
668
|
disposeUi = () => {
|
package/src/client/locales.ts
CHANGED
|
@@ -64,6 +64,8 @@ export const zh = {
|
|
|
64
64
|
'settings.enabledHint': '关闭后隐藏宠物并停止轮询,可在设置里重新启用。',
|
|
65
65
|
'settings.decoration': '状态装饰',
|
|
66
66
|
'settings.decorationHint': '在宠物状态气泡里显示喷水鲸鱼等状态装饰;关闭后气泡只剩文字。',
|
|
67
|
+
'settings.statusBubbles': '状态气泡',
|
|
68
|
+
'settings.statusBubblesHint': '宠物自带的会话/状态气泡(正在思考、正在使用 xxx)。关掉后只剩第三方插件通过公告契约推送的气泡与互动反馈气泡;默认开启。',
|
|
67
69
|
'settings.visible': '显示宠物',
|
|
68
70
|
'settings.visibleHint': '关闭后宠物隐藏,可从聊天输入区重新召唤。',
|
|
69
71
|
'settings.size': '大小(px)',
|
|
@@ -149,6 +151,8 @@ export const en = {
|
|
|
149
151
|
'settings.enabledHint': 'When off, the pet hides and polling stops; re-enable it here.',
|
|
150
152
|
'settings.decoration': 'Status decoration',
|
|
151
153
|
'settings.decorationHint': 'Show ornaments like the spouting whale inside the pet status bubbles; when off, bubbles stay text-only.',
|
|
154
|
+
'settings.statusBubbles': 'Status bubbles',
|
|
155
|
+
'settings.statusBubblesHint': 'The pet\'s own session/status bubbles (thinking, using ...). Turning them off leaves only bubbles a third-party plugin pushes through the announcement contract, plus the interaction feedback bubble; on by default.',
|
|
152
156
|
'settings.visible': 'Show the pet',
|
|
153
157
|
'settings.visibleHint': 'When off, the pet hides; summon it again from the input row.',
|
|
154
158
|
'settings.size': 'Size (px)',
|
package/src/index.test.ts
CHANGED
|
@@ -33,6 +33,7 @@ describe('pet configuration schema', () => {
|
|
|
33
33
|
bubbleScale: 1,
|
|
34
34
|
enabled: true,
|
|
35
35
|
decorationEnabled: true,
|
|
36
|
+
statusBubbles: 'auto',
|
|
36
37
|
})
|
|
37
38
|
})
|
|
38
39
|
|
|
@@ -69,6 +70,7 @@ describe('pet configuration schema', () => {
|
|
|
69
70
|
petId: true,
|
|
70
71
|
enabled: true,
|
|
71
72
|
decorationEnabled: true,
|
|
73
|
+
statusBubbles: true,
|
|
72
74
|
})
|
|
73
75
|
})
|
|
74
76
|
})
|
|
@@ -93,6 +95,7 @@ describe('petSettingsSection', () => {
|
|
|
93
95
|
petId: 'doro',
|
|
94
96
|
enabled: true,
|
|
95
97
|
decorationEnabled: true,
|
|
98
|
+
statusBubbles: 'auto',
|
|
96
99
|
})
|
|
97
100
|
})
|
|
98
101
|
|
|
@@ -109,6 +112,25 @@ describe('petSettingsSection', () => {
|
|
|
109
112
|
expect(before.size).toBe(160)
|
|
110
113
|
})
|
|
111
114
|
|
|
115
|
+
it('user switches the pet\'s own bubbles off from the settings page (#6)', () => {
|
|
116
|
+
// Given a resolved config whose user turned the status bubbles off
|
|
117
|
+
const resolved = Config({ statusBubbles: 'off' })
|
|
118
|
+
// When the plugin resolves the settings section it runs with
|
|
119
|
+
const section = petSettingsSection(resolved, 'whale-girl')
|
|
120
|
+
// Then the running pet is told to render no built-in bubbles
|
|
121
|
+
expect(section.statusBubbles).toBe('off')
|
|
122
|
+
// And the edit lands in the running activation, not only in the document
|
|
123
|
+
commitLive(resolved.statusBubbles, 'off')
|
|
124
|
+
expect(petSettingsSection(resolved, 'whale-girl').statusBubbles).toBe('off')
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('user keeps the status bubbles when the document carries no choice', () => {
|
|
128
|
+
// Given a mount outside a Loader, where no schema default was applied
|
|
129
|
+
const section = petSettingsSection({}, 'whale-girl')
|
|
130
|
+
// Then the shipped behavior stands rather than the bubbles silently vanishing
|
|
131
|
+
expect(section.statusBubbles).toBe('auto')
|
|
132
|
+
})
|
|
133
|
+
|
|
112
134
|
it('user keeps the pet selection it already has when the config names none', () => {
|
|
113
135
|
// Given a mount whose config carries no pet selection
|
|
114
136
|
// When the plugin resolves the settings section it runs with
|
package/src/index.ts
CHANGED
|
@@ -16,20 +16,28 @@ import { Context, type Volatile } from '@deepseek-ai/cordis'
|
|
|
16
16
|
import type {} from '@deepseek-ai/dsh-settings'
|
|
17
17
|
import type {} from '@deepseek-ai/dsh-host-webserver'
|
|
18
18
|
import z from '@deepseek-ai/schemastery'
|
|
19
|
-
import { PET_SETTINGS_NAMESPACE, PetService, type PetConfig, type PetSettingsSection } from './service.ts'
|
|
19
|
+
import { DEFAULT_STATUS_BUBBLE_MODE, PET_SETTINGS_NAMESPACE, PetService, STATUS_BUBBLE_MODES, statusBubbleMode, type PetConfig, type PetSettingsSection, type PetStatusBubbleMode } from './service.ts'
|
|
20
20
|
import { makePetRoutes } from './routes.ts'
|
|
21
21
|
import { loadPetRegistry, petPackageRoot } from './registry.ts'
|
|
22
22
|
import { BUBBLE_SCALE_MAX, BUBBLE_SCALE_MIN, DEFAULT_PET_ID, DISPLAY_INSET_MAX, DISPLAY_SIZE_MAX, DISPLAY_SIZE_MIN, type PetDisplayConfig } from './persist.ts'
|
|
23
23
|
import { mountOnce } from './mount-once.ts'
|
|
24
24
|
|
|
25
|
-
export { PetService, MAX_SESSION_BUBBLES } from './service.ts'
|
|
25
|
+
export { PetService, MAX_SESSION_BUBBLES, DEFAULT_STATUS_BUBBLE_MODE, STATUS_BUBBLE_MODES, statusBubbleMode } from './service.ts'
|
|
26
26
|
export type {
|
|
27
27
|
PetConfig,
|
|
28
28
|
PetInteractResult,
|
|
29
29
|
PetSettingsSection,
|
|
30
30
|
PetSessionView,
|
|
31
31
|
PetStateView,
|
|
32
|
+
PetStatusBubbleMode,
|
|
32
33
|
} from './service.ts'
|
|
34
|
+
export { MAX_PANEL_ACTIONS, PanelActionRegistry, normalizePanelAction } from './panel-actions.ts'
|
|
35
|
+
export type {
|
|
36
|
+
PetPanelActionContext,
|
|
37
|
+
PetPanelActionHandler,
|
|
38
|
+
PetPanelActionRegistration,
|
|
39
|
+
PetPanelActionView,
|
|
40
|
+
} from './panel-actions.ts'
|
|
33
41
|
export {
|
|
34
42
|
AFFINITY_MAX,
|
|
35
43
|
AFFINITY_RANKS,
|
|
@@ -133,6 +141,7 @@ export const PET_FORM_DEFAULTS = {
|
|
|
133
141
|
petId: DEFAULT_PET_ID,
|
|
134
142
|
enabled: true,
|
|
135
143
|
decorationEnabled: true,
|
|
144
|
+
statusBubbles: DEFAULT_STATUS_BUBBLE_MODE,
|
|
136
145
|
} as const
|
|
137
146
|
|
|
138
147
|
/**
|
|
@@ -149,6 +158,12 @@ export interface PetFormConfig {
|
|
|
149
158
|
enabled?: LiveField<boolean>
|
|
150
159
|
/** Status-decoration master switch (pet-center M5, #567); defaults to on. */
|
|
151
160
|
decorationEnabled?: LiveField<boolean>
|
|
161
|
+
/**
|
|
162
|
+
* Whether the pet renders its own session/status bubbles (issue #6);
|
|
163
|
+
* defaults to 'auto', which is exactly the behavior that shipped before
|
|
164
|
+
* the switch existed.
|
|
165
|
+
*/
|
|
166
|
+
statusBubbles?: LiveField<PetStatusBubbleMode | undefined>
|
|
152
167
|
/** Master switch for the pet surface. */
|
|
153
168
|
visible?: LiveField<boolean>
|
|
154
169
|
/** Scale of the rendered pet in px (sprite cell height). */
|
|
@@ -189,6 +204,11 @@ export const Config = z.object({
|
|
|
189
204
|
petId: z.string().volatile(),
|
|
190
205
|
enabled: z.boolean().default(PET_FORM_DEFAULTS.enabled).volatile(),
|
|
191
206
|
decorationEnabled: z.boolean().default(PET_FORM_DEFAULTS.decorationEnabled).volatile(),
|
|
207
|
+
// The pet's own session/status bubbles (issue #6). 'auto' is the shipped
|
|
208
|
+
// behavior; 'off' is the opt-in a user (or a plugin that drives its own
|
|
209
|
+
// bubble surface) needs, and it hides ONLY those bubbles — the sprite, the
|
|
210
|
+
// interaction feedback and a sibling plugin's announcement bubble stay.
|
|
211
|
+
statusBubbles: z.union([...STATUS_BUBBLE_MODES]).default(PET_FORM_DEFAULTS.statusBubbles).volatile(),
|
|
192
212
|
})
|
|
193
213
|
|
|
194
214
|
/**
|
|
@@ -283,6 +303,11 @@ export function petSettingsSection(
|
|
|
283
303
|
petId: readLive(config.petId, fallbackPetId),
|
|
284
304
|
enabled,
|
|
285
305
|
decorationEnabled: readLive(config.decorationEnabled, PET_FORM_DEFAULTS.decorationEnabled),
|
|
306
|
+
// Not a display field: the bubble switch has no persisted pet.json twin
|
|
307
|
+
// (it is a plugin-level rendering preference, like `decorationEnabled`),
|
|
308
|
+
// so it reads the live value directly and normalizes anything unknown to
|
|
309
|
+
// the shipped default instead of trusting the document.
|
|
310
|
+
statusBubbles: statusBubbleMode(readLive<PetStatusBubbleMode | undefined>(config.statusBubbles, undefined)),
|
|
286
311
|
}
|
|
287
312
|
}
|
|
288
313
|
|
|
@@ -344,6 +369,7 @@ function applyImpl(ctx: Context, config: PetPluginConfig = {}): void {
|
|
|
344
369
|
...config,
|
|
345
370
|
enabled: readLive(config.enabled, PET_FORM_DEFAULTS.enabled),
|
|
346
371
|
decorationEnabled: readLive(config.decorationEnabled, PET_FORM_DEFAULTS.decorationEnabled),
|
|
372
|
+
statusBubbles: statusBubbleMode(readLive<PetStatusBubbleMode | undefined>(config.statusBubbles, undefined)),
|
|
347
373
|
registry,
|
|
348
374
|
})
|
|
349
375
|
// The mirror back into the settings document (see syncSettingsFromPet) has to
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { MAX_PANEL_ACTIONS, normalizePanelAction, PanelActionRegistry } from './panel-actions.ts'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The hover-panel action registry (issue #6). Registration validates the
|
|
6
|
+
* shape a plugin hands the pet service, the table stays ordered and bounded,
|
|
7
|
+
* and a click dispatches to the registering plugin's own callback.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
describe('normalizePanelAction', () => {
|
|
11
|
+
it('accepts a registration with the documented shape', () => {
|
|
12
|
+
expect(normalizePanelAction({ id: 'pet-quota-swap', label: '换装' })).toEqual({
|
|
13
|
+
id: 'pet-quota-swap',
|
|
14
|
+
label: '换装',
|
|
15
|
+
order: 0,
|
|
16
|
+
})
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('carries the optional tooltip and order the plugin declared', () => {
|
|
20
|
+
expect(normalizePanelAction({ id: 'swap', label: '换装', title: '切换到下一只宠物', order: -5 }))
|
|
21
|
+
.toEqual({ id: 'swap', label: '换装', title: '切换到下一只宠物', order: -5 })
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('rejects an id a click could not be dispatched back on', () => {
|
|
25
|
+
for (const id of [undefined, '', 'Swap', 'pet quota', '../escape', 'a'.repeat(65)]) {
|
|
26
|
+
expect(normalizePanelAction({ id, label: '换装' })).toBeUndefined()
|
|
27
|
+
}
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('rejects a registration with no label and truncates an over-long one', () => {
|
|
31
|
+
expect(normalizePanelAction({ id: 'swap', label: ' ' })).toBeUndefined()
|
|
32
|
+
expect(normalizePanelAction({ id: 'swap' })).toBeUndefined()
|
|
33
|
+
expect(normalizePanelAction({ id: 'swap', label: 'x'.repeat(80) })?.label).toBe('x'.repeat(24))
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('ignores unknown fields and a non-numeric order', () => {
|
|
37
|
+
expect(normalizePanelAction({ id: 'swap', label: '换装', order: 'first', evil: true }))
|
|
38
|
+
.toEqual({ id: 'swap', label: '换装', order: 0 })
|
|
39
|
+
})
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
describe('PanelActionRegistry', () => {
|
|
43
|
+
it('serves the registered actions and dispatches a click to the plugin', async () => {
|
|
44
|
+
const registry = new PanelActionRegistry()
|
|
45
|
+
const onSelect = vi.fn()
|
|
46
|
+
registry.register({ id: 'swap', label: '换装', onSelect })
|
|
47
|
+
|
|
48
|
+
expect(registry.views()).toEqual([{ id: 'swap', label: '换装', order: 0 }])
|
|
49
|
+
await expect(registry.select('swap', { petId: 'whale-girl' })).resolves.toBe(true)
|
|
50
|
+
expect(onSelect).toHaveBeenCalledWith({ petId: 'whale-girl' })
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('reports an unregistered id instead of invoking anything', async () => {
|
|
54
|
+
const registry = new PanelActionRegistry()
|
|
55
|
+
const onSelect = vi.fn()
|
|
56
|
+
registry.register({ id: 'swap', label: '换装', onSelect })
|
|
57
|
+
|
|
58
|
+
await expect(registry.select('other', { petId: 'whale-girl' })).resolves.toBe(false)
|
|
59
|
+
expect(onSelect).not.toHaveBeenCalled()
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('lets a later registration of the same id replace the earlier one', async () => {
|
|
63
|
+
const registry = new PanelActionRegistry()
|
|
64
|
+
const first = vi.fn()
|
|
65
|
+
const second = vi.fn()
|
|
66
|
+
registry.register({ id: 'swap', label: '换装', onSelect: first })
|
|
67
|
+
registry.register({ id: 'swap', label: '更衣', onSelect: second })
|
|
68
|
+
|
|
69
|
+
await registry.select('swap', { petId: 'whale-girl' })
|
|
70
|
+
expect(first).not.toHaveBeenCalled()
|
|
71
|
+
expect(second).toHaveBeenCalledTimes(1)
|
|
72
|
+
expect(registry.views()).toEqual([{ id: 'swap', label: '更衣', order: 0 }])
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('keeps the replacing registration when the superseded one disposes', async () => {
|
|
76
|
+
// The trap this guards: a hot-reloaded plugin disposes its old
|
|
77
|
+
// registration after the new one is in, and the naive "delete by id"
|
|
78
|
+
// disposer would take the live action with it.
|
|
79
|
+
const registry = new PanelActionRegistry()
|
|
80
|
+
const disposeFirst = registry.register({ id: 'swap', label: '换装', onSelect: vi.fn() })
|
|
81
|
+
registry.register({ id: 'swap', label: '更衣', onSelect: vi.fn() })
|
|
82
|
+
|
|
83
|
+
disposeFirst()
|
|
84
|
+
expect(registry.views().map(view => view.label)).toEqual(['更衣'])
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('reclaims the action when the registering plugin disposes it', async () => {
|
|
88
|
+
const registry = new PanelActionRegistry()
|
|
89
|
+
const dispose = registry.register({ id: 'swap', label: '换装', onSelect: vi.fn() })
|
|
90
|
+
|
|
91
|
+
dispose()
|
|
92
|
+
expect(registry.views()).toEqual([])
|
|
93
|
+
await expect(registry.select('swap', { petId: 'whale-girl' })).resolves.toBe(false)
|
|
94
|
+
// Disposing twice is the shape an effect re-run produces; it is a no-op.
|
|
95
|
+
expect(() => dispose()).not.toThrow()
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('renders the registered block in order, ties on id', () => {
|
|
99
|
+
const registry = new PanelActionRegistry()
|
|
100
|
+
registry.register({ id: 'b', label: 'B', order: 1, onSelect: vi.fn() })
|
|
101
|
+
registry.register({ id: 'a', label: 'A', order: 1, onSelect: vi.fn() })
|
|
102
|
+
registry.register({ id: 'c', label: 'C', order: 0, onSelect: vi.fn() })
|
|
103
|
+
|
|
104
|
+
expect(registry.views().map(view => view.id)).toEqual(['c', 'a', 'b'])
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('refuses a malformed registration where it was written', () => {
|
|
108
|
+
const registry = new PanelActionRegistry()
|
|
109
|
+
expect(() => registry.register({ label: '换装', onSelect: vi.fn() })).toThrow(/invalid panel action/)
|
|
110
|
+
expect(() => registry.register({ id: 'swap', label: '换装' })).toThrow(/onSelect/)
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
it('bounds the row so plugins cannot grow it without limit', () => {
|
|
114
|
+
const registry = new PanelActionRegistry()
|
|
115
|
+
for (let index = 0; index < MAX_PANEL_ACTIONS; index += 1) {
|
|
116
|
+
registry.register({ id: 'swap-' + index, label: '换装', onSelect: vi.fn() })
|
|
117
|
+
}
|
|
118
|
+
expect(registry.views()).toHaveLength(MAX_PANEL_ACTIONS)
|
|
119
|
+
expect(() => registry.register({ id: 'swap-overflow', label: '换装', onSelect: vi.fn() })).toThrow(/limit/)
|
|
120
|
+
// Re-registering an id that is already in the row is not a new row.
|
|
121
|
+
expect(() => registry.register({ id: 'swap-0', label: '换装', onSelect: vi.fn() })).not.toThrow()
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
it('propagates a failing callback so the caller can report it', async () => {
|
|
125
|
+
const registry = new PanelActionRegistry()
|
|
126
|
+
registry.register({ id: 'swap', label: '换装', onSelect: () => { throw new Error('plugin bug') } })
|
|
127
|
+
|
|
128
|
+
await expect(registry.select('swap', { petId: 'whale-girl' })).rejects.toThrow('plugin bug')
|
|
129
|
+
})
|
|
130
|
+
})
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hover-panel action contract — the extension point a sibling plugin uses to
|
|
3
|
+
* add its own button to the pet's floating hover panel (issue #6).
|
|
4
|
+
*
|
|
5
|
+
* A plugin registers one action in process through the pet service
|
|
6
|
+
* (`ctx.pet.registerPanelAction({ id, label, onSelect })`); the host validates
|
|
7
|
+
* it into a bounded view, serves the registered actions in the state snapshot
|
|
8
|
+
* (`PetStateView.panelActions`), and the browser half renders one button per
|
|
9
|
+
* entry at the end of the panel's action row. A click travels back through
|
|
10
|
+
* `POST /api/pet/panel-action`, which dispatches to the registering plugin's
|
|
11
|
+
* own callback — the pet owns the row, the plugin owns what the button does.
|
|
12
|
+
*
|
|
13
|
+
* The validation and the registry live in this pure module so the contract has
|
|
14
|
+
* exactly one home and stays testable without the cordis service.
|
|
15
|
+
* @module @linxin666/dsh-pet/panel-actions
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** How many plugin actions one hover panel can carry at most. */
|
|
19
|
+
export const MAX_PANEL_ACTIONS = 8
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Action id grammar: a lowercase id in the shape pet and decoration ids use
|
|
23
|
+
* (`^` + kebab/dot segments). The id is what a click travels back on, so it
|
|
24
|
+
* has to be stable, addressable and free of separators the wire would treat as
|
|
25
|
+
* structure.
|
|
26
|
+
*/
|
|
27
|
+
const ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Label bound. The action row is compact and wraps beyond a few characters per
|
|
31
|
+
* button, so a plugin names its action (换装, Quota) rather than a sentence;
|
|
32
|
+
* the optional title carries the longer explanation as a tooltip.
|
|
33
|
+
*/
|
|
34
|
+
const LABEL_MAX = 24
|
|
35
|
+
|
|
36
|
+
/** Title (tooltip) bound; the same reason voice-pack labels are bounded. */
|
|
37
|
+
const TITLE_MAX = 80
|
|
38
|
+
|
|
39
|
+
/** One registered action as the browser half renders it. */
|
|
40
|
+
export interface PetPanelActionView {
|
|
41
|
+
/** Registration id; the click dispatches back on it. */
|
|
42
|
+
id: string
|
|
43
|
+
/** Button label. */
|
|
44
|
+
label: string
|
|
45
|
+
/** Optional tooltip (the label's longer explanation). */
|
|
46
|
+
title?: string
|
|
47
|
+
/** Sort key within the registered block; ties break on id. */
|
|
48
|
+
order: number
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* What a panel action click knows about the pet at the moment it arrives. The
|
|
53
|
+
* registering plugin may read more off the service (`selectedPetId()`), so this
|
|
54
|
+
* stays a read-only snapshot rather than a live handle.
|
|
55
|
+
*/
|
|
56
|
+
export interface PetPanelActionContext {
|
|
57
|
+
/** The selected pet id when the click arrived. */
|
|
58
|
+
petId: string
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The callback a registration carries; a click invokes it in the host. */
|
|
62
|
+
export type PetPanelActionHandler = (context: PetPanelActionContext) => void | Promise<void>
|
|
63
|
+
|
|
64
|
+
/** One action a sibling plugin registers into the panel's action row. */
|
|
65
|
+
export interface PetPanelActionRegistration {
|
|
66
|
+
/** Unique, stable id (kebab-case); re-registering the same id replaces it. */
|
|
67
|
+
id: string
|
|
68
|
+
/** Button label (bounded). */
|
|
69
|
+
label: string
|
|
70
|
+
/** Optional tooltip rendered as the button's `title`. */
|
|
71
|
+
title?: string
|
|
72
|
+
/** Sort key within the registered block (default 0; ascending, ties on id). */
|
|
73
|
+
order?: number
|
|
74
|
+
/** Invoked in the host when the browser half dispatches this action. */
|
|
75
|
+
onSelect: PetPanelActionHandler
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A validated registration: the wire view plus the host-side callback. */
|
|
79
|
+
interface PanelActionEntry {
|
|
80
|
+
view: PetPanelActionView
|
|
81
|
+
onSelect: PetPanelActionHandler
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function boundedString(value: unknown, max: number): string | undefined {
|
|
85
|
+
if (typeof value !== 'string') return undefined
|
|
86
|
+
const trimmed = value.trim()
|
|
87
|
+
if (trimmed === '') return undefined
|
|
88
|
+
return trimmed.length <= max ? trimmed : trimmed.slice(0, max)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Validate one registration. Returns undefined — never throws — when the shape
|
|
93
|
+
* is unusable: the id must match the id grammar and the label must survive
|
|
94
|
+
* truncation, so a click can always be dispatched back to a known row.
|
|
95
|
+
* @param input - the registration a sibling plugin passed to the service.
|
|
96
|
+
* @returns the wire view, or undefined when the registration is malformed.
|
|
97
|
+
*/
|
|
98
|
+
export function normalizePanelAction(input: unknown): PetPanelActionView | undefined {
|
|
99
|
+
if (typeof input !== 'object' || input === null) return undefined
|
|
100
|
+
const data = input as Record<string, unknown>
|
|
101
|
+
// The id is an identity, not copy: an over-long one is refused rather than
|
|
102
|
+
// truncated, because truncating it could silently collapse two plugins'
|
|
103
|
+
// registrations onto one row.
|
|
104
|
+
const id = typeof data.id === 'string' ? data.id.trim() : undefined
|
|
105
|
+
if (id === undefined || !ID_PATTERN.test(id)) return undefined
|
|
106
|
+
const label = boundedString(data.label, LABEL_MAX)
|
|
107
|
+
if (label === undefined) return undefined
|
|
108
|
+
const title = boundedString(data.title, TITLE_MAX)
|
|
109
|
+
const order = typeof data.order === 'number' && Number.isFinite(data.order) ? data.order : 0
|
|
110
|
+
return {
|
|
111
|
+
id,
|
|
112
|
+
label,
|
|
113
|
+
...(title === undefined ? {} : { title }),
|
|
114
|
+
order,
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The panel's action registry: one bounded, ordered table of plugin actions.
|
|
120
|
+
*
|
|
121
|
+
* Registration is id-wins (a later registration of the same id replaces the
|
|
122
|
+
* earlier one, and the superseded disposer stops touching the table so a
|
|
123
|
+
* disposing plugin can never remove the action that replaced it). The table is
|
|
124
|
+
* in-memory only — it dies with the pet service fiber — and every entry is
|
|
125
|
+
* reclaimed by the disposer the registering plugin runs with its own fiber.
|
|
126
|
+
*/
|
|
127
|
+
export class PanelActionRegistry {
|
|
128
|
+
private readonly actions = new Map<string, PanelActionEntry>()
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Register one action.
|
|
132
|
+
* @param input - the registration a sibling plugin passed to the service.
|
|
133
|
+
* @returns a disposer removing this registration.
|
|
134
|
+
* @throws when the registration is malformed. Unlike `announce` — a hot path
|
|
135
|
+
* whose payload a caller may build from untrusted data — a registration is
|
|
136
|
+
* built once at the registering plugin's own apply, so a bad id or label is a
|
|
137
|
+
* wiring mistake that should fail where it was written.
|
|
138
|
+
*/
|
|
139
|
+
register(input: unknown): () => void {
|
|
140
|
+
const registration = (typeof input === 'object' && input !== null ? input : {}) as PetPanelActionRegistration
|
|
141
|
+
const view = normalizePanelAction(registration)
|
|
142
|
+
if (view === undefined) throw new Error('[dsh-pet] invalid panel action: id and label are required')
|
|
143
|
+
if (typeof registration.onSelect !== 'function') {
|
|
144
|
+
throw new Error('[dsh-pet] invalid panel action: onSelect must be a function')
|
|
145
|
+
}
|
|
146
|
+
if (!this.actions.has(view.id) && this.actions.size >= MAX_PANEL_ACTIONS) {
|
|
147
|
+
throw new Error('[dsh-pet] panel action limit reached: ' + MAX_PANEL_ACTIONS)
|
|
148
|
+
}
|
|
149
|
+
const entry: PanelActionEntry = { view, onSelect: registration.onSelect }
|
|
150
|
+
this.actions.set(view.id, entry)
|
|
151
|
+
return () => {
|
|
152
|
+
// Only the registration that still owns the id may clear it.
|
|
153
|
+
if (this.actions.get(view.id) === entry) this.actions.delete(view.id)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The registered actions as the state view serves them, in render order. */
|
|
158
|
+
views(): PetPanelActionView[] {
|
|
159
|
+
return [...this.actions.values()]
|
|
160
|
+
.map(entry => entry.view)
|
|
161
|
+
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Dispatch a click to the plugin that registered this id.
|
|
166
|
+
* @param id - the id the browser half reported.
|
|
167
|
+
* @param context - what the pet looked like when the click arrived.
|
|
168
|
+
* @returns whether the id was registered. A handler that throws rejects:
|
|
169
|
+
* the caller decides how a sibling plugin's failure is reported.
|
|
170
|
+
*/
|
|
171
|
+
async select(id: string, context: PetPanelActionContext): Promise<boolean> {
|
|
172
|
+
const entry = this.actions.get(id)
|
|
173
|
+
if (entry === undefined) return false
|
|
174
|
+
await entry.onSelect(context)
|
|
175
|
+
return true
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Drop every registration (service teardown; tests). */
|
|
179
|
+
clear(): void {
|
|
180
|
+
this.actions.clear()
|
|
181
|
+
}
|
|
182
|
+
}
|
package/src/routes.ts
CHANGED
|
@@ -613,6 +613,15 @@ export function makePetRoutes(deps: { service: PetService; ctx: Context; assetCa
|
|
|
613
613
|
if (typeof petId !== 'string') return Promise.reject(new Error('invalid-pet'))
|
|
614
614
|
return service.setPetId(petId)
|
|
615
615
|
}),
|
|
616
|
+
// Hover-panel action click (issue #6): the browser half owns no plugin
|
|
617
|
+
// callbacks, so a click on a registered action travels back here and the
|
|
618
|
+
// service dispatches it to the plugin that registered it. Same loopback /
|
|
619
|
+
// paired-device guard as every other endpoint in this family.
|
|
620
|
+
postRoute(ctx, PET_API_PREFIX + '/panel-action', (body) => {
|
|
621
|
+
const id = body.id
|
|
622
|
+
if (typeof id !== 'string') return Promise.reject(new Error('invalid-panel-action'))
|
|
623
|
+
return service.selectPanelAction(id)
|
|
624
|
+
}),
|
|
616
625
|
// Gameplay verbs (miku-pet generalization): touch rolls a named zone's
|
|
617
626
|
// branch; the omitted-zone form is the plain-click boost during a touch
|
|
618
627
|
// animation. Mode/tick/buy drive the work, sleep and shop loops.
|