apply.client.spec.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /** locale apply wiring: service + dictionaries provision, declaration-aware
  2. * Language row registration, snapshot projection into the row store, and
  3. * recovery after an HMR collapse of the declaring entry. */
  4. import { Context } from '@deepseek-ai/cordis'
  5. import { describe, expect, it, vi } from 'vitest'
  6. import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
  7. import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client'
  8. import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  9. import {
  10. apply, inject, SETTINGS_NS,
  11. } from '@deepseek-ai/dsh-client-locale/client'
  12. import type { LanguageRowInjected, LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  13. import { LOCALE_SETTINGS_NAMESPACE, LocaleSettingsSchema } from '../src/locale-settings.ts'
  14. import { LanguageRow } from '../src/client/LanguageRow.tsx'
  15. import type { createLanguageRowStore } from '../src/client/settings-store.ts'
  16. const SLOT = 'settings.general.item'
  17. async function bench() {
  18. const ctx = new Context()
  19. await ctx.plugin(SlotRegistry).await()
  20. let preference: string | undefined
  21. let revision = 0
  22. const namespace = () => ({
  23. ns: LOCALE_SETTINGS_NAMESPACE,
  24. schema: LocaleSettingsSchema.toJSON(),
  25. value: preference === undefined ? {} : { preference },
  26. applies: 'live' as const,
  27. secrets: [],
  28. revision,
  29. })
  30. const describe = vi.fn(async () => ({
  31. ok: true as const,
  32. value: { writable: true, hasDocument: true, namespaces: [namespace()] },
  33. }))
  34. const mutate = vi.fn(async (_ns: string, ops: { value: string }[]) => {
  35. preference = ops[0]!.value
  36. revision += 1
  37. return { ok: true as const, value: namespace() }
  38. })
  39. const events = new TestRemote(ctx, { settings: { describe, mutate } })
  40. await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await()
  41. return {
  42. ctx, slots: ctx.get('slots') as SlotRegistry, describe, mutate, events,
  43. setHostPreference: (next: string | undefined) => { preference = next; revision += 1 },
  44. }
  45. }
  46. /** Stand in for the settings shell: declare the General item slot from root. */
  47. function declareItems(slots: SlotRegistry): () => void {
  48. return slots.register(
  49. { name: 'root', children: { [SLOT]: { kind: 'list', scope: 'root' } } } as never,
  50. () => null,
  51. )
  52. }
  53. /** Mirror the framework's inject choreography: bake a real instance from the
  54. * declared handle and hand its actions to the entry's inject factory. */
  55. function faceOf(slots: SlotRegistry) {
  56. const entry = slots.entries(SLOT).find(e => e.component === LanguageRow)!
  57. const handle = entry.store as ReturnType<typeof createLanguageRowStore>
  58. const instance = handle.create()
  59. const face = (entry.inject as unknown as (a: typeof instance.actions) => LanguageRowInjected)(instance.actions)
  60. return { entry, instance, face }
  61. }
  62. describe('locale apply', () => {
  63. // These are wiring specs, not default-language specs. A fresh LocaleRuntime
  64. // with no jsdom `window` skips browser detection and opens on FALLBACK_LOCALE
  65. // (en); each test that reads localized copy stages its locale explicitly via
  66. // setLocale/Host preference instead of leaning on a dead browser pin.
  67. it('declares the slot service', () => {
  68. expect(inject).toEqual(['slots', 'remote', 'settingsScope'])
  69. })
  70. it('provides the service with base + settings dictionaries and registers the row (declaration before or after apply)', async () => {
  71. const before = await bench()
  72. declareItems(before.slots)
  73. await before.ctx.plugin({ inject: [...inject], apply }).await()
  74. const locale = before.ctx.get('locale') as LocaleRuntime
  75. // Base dictionaries are registered: the (ns, locale) seats are occupied.
  76. expect(() => locale.register('common', 'zh', {})).toThrow('already has locale')
  77. expect(() => locale.register('common', 'en', {})).toThrow('already has locale')
  78. // The lane has no jsdom `window`, so detection never runs and a fresh
  79. // service opens on FALLBACK_LOCALE (en); read the zh side explicitly.
  80. locale.setLocale('zh')
  81. expect(locale.bind(SETTINGS_NS)('language.title')).toBe('语言')
  82. const entry = before.slots.entries(SLOT).find(e => e.component === LanguageRow)!
  83. expect(entry.options).toMatchObject({ id: 'language', order: 0 })
  84. const after = await bench()
  85. const fiber = after.ctx.plugin({ inject: [...inject], apply })
  86. await fiber.await()
  87. expect(after.slots.entries(SLOT)).toHaveLength(0)
  88. declareItems(after.slots)
  89. await Promise.resolve()
  90. expect(after.slots.entries(SLOT).some(e => e.component === LanguageRow)).toBe(true)
  91. })
  92. it('projects service snapshots into the row store and routes face writes back', async () => {
  93. const b = await bench()
  94. declareItems(b.slots)
  95. await b.ctx.plugin({ inject: [...inject], apply }).await()
  96. const locale = b.ctx.get('locale') as LocaleRuntime
  97. // An event ahead of any inject hits the unbound-actions arm.
  98. locale.setLocale('en')
  99. const { entry, instance, face } = faceOf(b.slots)
  100. // The inject-time re-sync sealed the init window: the mirror is current.
  101. expect(instance.getSnapshot().active).toBe('en')
  102. expect(instance.getSnapshot().options.map(o => o.id)).toEqual(['zh', 'en'])
  103. // Copy rides the standard locale seat: the entry declares the namespace.
  104. expect(entry.locale).toBe(SETTINGS_NS)
  105. expect(locale.bind(SETTINGS_NS)('language.title')).toBe('Language')
  106. face.setLocale('zh')
  107. expect(locale.getLocale().active).toBe('zh')
  108. expect(instance.getSnapshot().active).toBe('zh')
  109. expect(locale.bind(SETTINGS_NS)('language.title')).toBe('语言')
  110. await vi.waitFor(() => { expect(b.mutate).toHaveBeenCalledTimes(2) })
  111. })
  112. it('projects external locale registration and disposal into the Language row', async () => {
  113. const b = await bench()
  114. declareItems(b.slots)
  115. await b.ctx.plugin({ inject: [...inject], apply }).await()
  116. const { instance } = faceOf(b.slots)
  117. const languagePack = b.ctx.plugin({
  118. inject: ['locale'],
  119. apply: packCtx => packCtx.effect(
  120. () => packCtx.locale.addLanguage({ id: 'ja', label: '日本語', fallback: 'en' }),
  121. 'test language pack registration',
  122. ),
  123. })
  124. await languagePack.await()
  125. expect(instance.getSnapshot().options).toEqual([
  126. { id: 'zh', label: '中文' },
  127. { id: 'en', label: 'English' },
  128. { id: 'ja', label: '日本語' },
  129. ])
  130. await languagePack.dispose()
  131. expect(instance.getSnapshot().options.map(option => option.id)).toEqual(['zh', 'en'])
  132. })
  133. it('loads and refreshes the explicit Host preference after nonblocking activation', async () => {
  134. const b = await bench()
  135. // The shared mirror read once at bench time; a Host-side change reaches it
  136. // through the document invalidation, exactly as production announces one.
  137. // Preference must differ from the provisional locale (FALLBACK_LOCALE = en
  138. // with no window), or clearing it below would be unobservable.
  139. b.setHostPreference('zh')
  140. b.events.emit('settings/document-updated', [LOCALE_SETTINGS_NAMESPACE, 0])
  141. declareItems(b.slots)
  142. await b.ctx.plugin({ inject: [...inject], apply }).await()
  143. const locale = b.ctx.get('locale') as LocaleRuntime
  144. await vi.waitFor(() => { expect(locale.getLocale().active).toBe('zh') })
  145. // Cleared preference falls back to the provisional locale.
  146. b.setHostPreference(undefined)
  147. b.events.emit('settings/document-updated', [LOCALE_SETTINGS_NAMESPACE, 0])
  148. await vi.waitFor(() => { expect(locale.getLocale().active).toBe('en') })
  149. // Re-selecting zh after the clear is an explicit pick of the provisional
  150. // value and must persist as a written preference.
  151. b.setHostPreference('zh')
  152. b.events.emit('settings/document-updated', [LOCALE_SETTINGS_NAMESPACE, 0])
  153. await vi.waitFor(() => { expect(locale.getLocale().active).toBe('zh') })
  154. expect(b.describe).toHaveBeenCalledTimes(4)
  155. })
  156. it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => {
  157. const b = await bench()
  158. const host = declareItems(b.slots)
  159. await b.ctx.plugin({ inject: [...inject], apply }).await()
  160. expect(b.slots.entries(SLOT)).toHaveLength(1)
  161. // Collapse: the declarer dies, the cascade removes our entry while the
  162. // apply closure still holds its (now stale) disposer.
  163. host()
  164. expect(b.slots.entries(SLOT)).toHaveLength(0)
  165. declareItems(b.slots)
  166. await Promise.resolve()
  167. expect(b.slots.entries(SLOT).some(e => e.component === LanguageRow)).toBe(true)
  168. })
  169. it('teardown removes the row; teardown without a declaration is quiet', async () => {
  170. const b = await bench()
  171. declareItems(b.slots)
  172. const fiber = b.ctx.plugin({ inject: [...inject], apply })
  173. await fiber.await()
  174. expect(b.slots.entries(SLOT)).toHaveLength(1)
  175. await fiber.dispose()
  176. expect(b.slots.entries(SLOT)).toHaveLength(0)
  177. // Never-declared bench: the effect disposer's dispose arm stays undefined.
  178. const quiet = await bench()
  179. const f2 = quiet.ctx.plugin({ inject: [...inject], apply })
  180. await f2.await()
  181. await f2.dispose()
  182. expect(quiet.slots.entries(SLOT)).toHaveLength(0)
  183. })
  184. })