theme.client.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // @vitest-environment jsdom
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import { stubSettingsScope, type StubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
  5. import type {
  6. ThemeSettings,
  7. ThemeSnapshot,
  8. ThemeTokenOverrides,
  9. } from '@deepseek-ai/dsh-client-ui-theme/client'
  10. import { ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client'
  11. const make = (host = stubSettingsScope<ThemeSettings>()): {
  12. ctx: Context
  13. theme: ThemeRuntime
  14. events: ThemeSnapshot[]
  15. host: StubSettingsScope<ThemeSettings>
  16. } => {
  17. const ctx = new Context()
  18. const events: ThemeSnapshot[] = []
  19. ctx.on('theme/change', (snapshot) => { events.push(snapshot) })
  20. return { ctx, theme: new ThemeRuntime(ctx, host.scope), events, host }
  21. }
  22. describe('ThemeRuntime', () => {
  23. it('defaults to the system preference resolved against prefers-color-scheme', () => {
  24. const { theme } = make()
  25. const snapshot = theme.getTheme()
  26. expect(snapshot.preference).toBe('system')
  27. expect(snapshot.fontSize).toBe(14)
  28. // jsdom matchMedia is absent; system resolves to light.
  29. expect(snapshot.active.id).toBe('light')
  30. expect(snapshot.active.colorScheme).toBe('light')
  31. expect(snapshot.themes.map(t => t.id)).toEqual(['light', 'dark'])
  32. })
  33. it('seeds the initial font size from the boot-script body variable, ignoring junk', () => {
  34. // The Host boot script writes the durable size on body before any plugin
  35. // runs; the first snapshot must match it so activation never flashes 14.
  36. document.body.style.setProperty('--dsh-content-font-size', '16px')
  37. try {
  38. expect(make().theme.getTheme().fontSize).toBe(16)
  39. document.body.style.setProperty('--dsh-content-font-size', '99px')
  40. expect(make().theme.getTheme().fontSize).toBe(14)
  41. } finally {
  42. document.body.style.removeProperty('--dsh-content-font-size')
  43. }
  44. })
  45. it('setFontSize switches, writes through the scope, and republishes; same value is a no-op', () => {
  46. const { theme, events, host } = make()
  47. theme.setFontSize(17)
  48. expect(theme.getTheme().fontSize).toBe(17)
  49. expect(host.set).toHaveBeenCalledWith('fontSize', 17)
  50. expect(events).toHaveLength(1)
  51. theme.setFontSize(17)
  52. expect(events).toHaveLength(1)
  53. expect(host.set).toHaveBeenCalledOnce()
  54. })
  55. it('rejects out-of-range and fractional font sizes', () => {
  56. const { theme, events, host } = make()
  57. for (const px of [11, 18, 14.5, Number.NaN]) {
  58. expect(() => { theme.setFontSize(px) }).toThrow('outside 12..17')
  59. }
  60. expect(events).toHaveLength(0)
  61. expect(host.set).not.toHaveBeenCalled()
  62. })
  63. it('adopts a published Host font size without writing it back', () => {
  64. const { theme, events, host } = make()
  65. host.publish({ status: 'ready', value: { preference: 'system', fontSize: 12 }, revision: 1, writable: true })
  66. expect(theme.getTheme().fontSize).toBe(12)
  67. expect(events).toHaveLength(1)
  68. expect(host.set).not.toHaveBeenCalled()
  69. })
  70. it('setTheme switches, writes through the scope, republishes, and keeps DOM untouched', () => {
  71. const { theme, events, host } = make()
  72. theme.setTheme('dark')
  73. expect(theme.getTheme().preference).toBe('dark')
  74. expect(theme.getTheme().active.colorScheme).toBe('dark')
  75. expect(host.set).toHaveBeenCalledWith('preference', 'dark')
  76. expect(events).toHaveLength(1)
  77. expect(events[0]).toBe(theme.getTheme())
  78. // The service never touches presentation state.
  79. expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(false)
  80. // Same-value set is a no-op (no extra event).
  81. theme.setTheme('dark')
  82. expect(events).toHaveLength(1)
  83. expect(host.set).toHaveBeenCalledOnce()
  84. })
  85. it('adopts a published Host section without writing it back', () => {
  86. const { theme, events, host } = make()
  87. host.publish({ status: 'ready', value: { preference: 'dark', fontSize: 14 }, revision: 1, writable: true })
  88. expect(theme.getTheme().preference).toBe('dark')
  89. expect(events).toHaveLength(1)
  90. expect(host.set).not.toHaveBeenCalled()
  91. host.publish({ value: { preference: 'dark', fontSize: 14 }, revision: 2 })
  92. expect(events).toHaveLength(1)
  93. })
  94. it('adopts a section already standing at construction', () => {
  95. const host = stubSettingsScope<ThemeSettings>()
  96. host.publish({ status: 'ready', value: { preference: 'dark', fontSize: 14 }, revision: 1, writable: true })
  97. const { theme } = make(host)
  98. expect(theme.getTheme().preference).toBe('dark')
  99. })
  100. it('throws on unknown setTheme ids, duplicate registration, and the system id', () => {
  101. const { theme } = make()
  102. expect(() => { theme.setTheme('sepia') }).toThrow('not registered')
  103. expect(() => theme.register({ id: 'light', colorScheme: 'light', tokens: {} })).toThrow('already registered')
  104. expect(() => theme.register({ id: 'system', colorScheme: 'light', tokens: {} })).toThrow('preference')
  105. })
  106. it('registered themes join the snapshot; disposing the active one resets to default', () => {
  107. const { theme, events, host } = make()
  108. const dispose = theme.register({ id: 'sepia', colorScheme: 'light', tokens: { '--dsw-alias-bg-base': 'red' } })
  109. expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark', 'sepia'])
  110. theme.setTheme('sepia')
  111. expect(theme.getTheme().active.tokens['--dsw-alias-bg-base']).toBe('red')
  112. dispose()
  113. expect(theme.getTheme().preference).toBe('system')
  114. expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark'])
  115. // Custom ids are in-process extension themes; only the built-in product
  116. // preferences cross the Host settings schema.
  117. expect(host.set).not.toHaveBeenCalled()
  118. // register + set + dispose = three publishes; disposer is idempotent.
  119. expect(events.length).toBe(3)
  120. dispose()
  121. expect(events.length).toBe(3)
  122. })
  123. it('disposing an inactive theme keeps the active preference', () => {
  124. const { theme } = make()
  125. const dispose = theme.register({ id: 'sepia', colorScheme: 'light', tokens: {} })
  126. theme.setTheme('dark')
  127. dispose()
  128. expect(theme.getTheme().preference).toBe('dark')
  129. })
  130. it('revision increases monotonically across every publish', () => {
  131. const { theme, events } = make()
  132. theme.setTheme('dark')
  133. theme.setTheme('light')
  134. const dispose = theme.register({ id: 'sepia', colorScheme: 'dark', tokens: {} })
  135. dispose()
  136. expect(events.map(e => e.revision)).toEqual([1, 2, 3, 4])
  137. })
  138. it('stacks reversible token overrides in call order and selects the active palette value', () => {
  139. const { theme } = make()
  140. const firstTokens: ThemeTokenOverrides = {
  141. '--shared': { light: 'first-light', dark: 'first-dark' },
  142. '--first': { light: 'first-only-light', dark: 'first-only-dark' },
  143. }
  144. const disposeFirst = theme.overrideTokens('first', firstTokens)
  145. firstTokens['--shared']!.light = 'mutated-after-call'
  146. const disposeSecond = theme.overrideTokens('second', {
  147. '--shared': { light: 'second-light', dark: 'second-dark' },
  148. })
  149. expect(theme.getTheme().active.tokens).toMatchObject({
  150. '--first': 'first-only-light',
  151. '--shared': 'second-light',
  152. })
  153. theme.setTheme('dark')
  154. expect(theme.getTheme().active.tokens).toMatchObject({
  155. '--first': 'first-only-dark',
  156. '--shared': 'second-dark',
  157. })
  158. disposeSecond()
  159. expect(theme.getTheme().active.tokens['--shared']).toBe('first-dark')
  160. disposeFirst()
  161. expect(theme.getTheme().active.tokens['--shared']).toBeUndefined()
  162. })
  163. it('replacing one source leaves its stale disposer harmless', () => {
  164. const { theme, events } = make()
  165. const stale = theme.overrideTokens('package', {
  166. '--old': { light: 'old-light', dark: 'old-dark' },
  167. })
  168. const current = theme.overrideTokens('package', {
  169. '--new': { light: 'new-light', dark: 'new-dark' },
  170. })
  171. stale()
  172. expect(theme.getTheme().active.tokens).toEqual({ '--new': 'new-light' })
  173. current()
  174. current()
  175. expect(theme.getTheme().active.tokens).toEqual({})
  176. expect(events).toHaveLength(3)
  177. })
  178. it('exports sorted built-in, registered, and override-only token descriptions as copies', () => {
  179. const { theme } = make()
  180. theme.register({
  181. id: 'custom',
  182. colorScheme: 'light',
  183. tokens: {
  184. '--dsw-alias-bg-base': 'duplicate-built-in',
  185. '--registered': 'registered',
  186. },
  187. })
  188. theme.overrideTokens('package', {
  189. '--registered': { light: 'duplicate-registered', dark: 'duplicate-registered' },
  190. semanticAccent: { light: 'pink', dark: 'red' },
  191. })
  192. const tokens = theme.exportInspectTokens()
  193. expect(tokens.map(token => token.name)).toEqual([...tokens.map(token => token.name)].sort())
  194. expect(tokens.find(token => token.name === '--registered')).toMatchObject({
  195. valueType: 'CSS value',
  196. cssVariable: '--registered',
  197. })
  198. const semantic = tokens.find(token => token.name === 'semanticAccent')
  199. expect(semantic).toMatchObject({ valueType: 'CSS value' })
  200. expect(semantic).not.toHaveProperty('cssVariable')
  201. expect(tokens.filter(token => token.name === '--dsw-alias-bg-base')).toHaveLength(1)
  202. tokens[0]!.description = 'caller mutation'
  203. expect(theme.exportInspectTokens()[0]!.description).not.toBe('caller mutation')
  204. })
  205. it('rejects every malformed token override value with a teaching error', () => {
  206. const { theme } = make()
  207. const override = (value: unknown): void => {
  208. theme.overrideTokens('package', { '--bad': value } as unknown as ThemeTokenOverrides)
  209. }
  210. expect(() => { override('red') }).toThrow(/bare string.*light.*dark/)
  211. for (const value of [1, null, {}, { light: 1, dark: 'dark' }, { light: 'light' }]) {
  212. expect(() => { override(value) }).toThrow(/must map to a \{ light, dark \} pair/)
  213. }
  214. })
  215. it('context dispose releases the scope subscription', async () => {
  216. const { ctx, host } = make()
  217. expect(host.listenerCount()).toBe(1)
  218. await ctx.fiber.dispose()
  219. expect(host.listenerCount()).toBe(0)
  220. })
  221. describe('prefers-color-scheme resolution (stubbed matchMedia)', () => {
  222. type Listener = () => void
  223. const stubMedia = (initialMatches: boolean) => {
  224. const listeners = new Set<Listener>()
  225. const media = {
  226. matches: initialMatches,
  227. addEventListener: (_: 'change', fn: Listener) => { listeners.add(fn) },
  228. removeEventListener: (_: 'change', fn: Listener) => { listeners.delete(fn) },
  229. flip() {
  230. this.matches = !this.matches
  231. for (const fn of listeners) fn()
  232. },
  233. listenerCount: () => listeners.size,
  234. }
  235. vi.stubGlobal('matchMedia', () => media)
  236. return media
  237. }
  238. afterEach(() => { vi.unstubAllGlobals() })
  239. it('system resolves against the media query and follows OS flips', () => {
  240. const media = stubMedia(true)
  241. const { theme, events } = make()
  242. expect(theme.getTheme().preference).toBe('system')
  243. expect(theme.getTheme().active.id).toBe('dark')
  244. media.flip()
  245. expect(theme.getTheme().active.id).toBe('light')
  246. expect(events).toHaveLength(1)
  247. })
  248. it('OS flips do not republish while a concrete preference is set', () => {
  249. const media = stubMedia(false)
  250. const { theme, events } = make()
  251. theme.setTheme('light')
  252. expect(events).toHaveLength(1)
  253. media.flip()
  254. expect(events).toHaveLength(1)
  255. expect(theme.getTheme().active.id).toBe('light')
  256. })
  257. it('context dispose releases the media listener', async () => {
  258. const media = stubMedia(false)
  259. const { ctx } = make()
  260. expect(media.listenerCount()).toBe(1)
  261. await ctx.fiber.dispose()
  262. expect(media.listenerCount()).toBe(0)
  263. })
  264. })
  265. })