menu-view.client.spec.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // @vitest-environment jsdom
  2. /**
  3. * MenuView rendering spec, props-direct: closed store
  4. * renders null, groups render in roster order under localized title rows
  5. * (unknown sources fall back to the raw name) with pending rows as loading,
  6. * pointer picks route (source, index) back without stealing focus, the
  7. * highlight is exposed through aria-activedescendant + aria-selected, and
  8. * the list height clamps to the space above the composer.
  9. */
  10. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  11. import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
  12. import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
  13. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  14. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  15. import { zh } from '../src/client/locales.ts'
  16. import type { MenuState, TriggerHit } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
  17. import { MenuView } from '../src/client/MenuView.tsx'
  18. const hit: TriggerHit = {
  19. trigger: '/',
  20. query: 'g',
  21. quoted: false,
  22. position: 'leading',
  23. span: { start: 0, end: 2, draftRev: 1 },
  24. }
  25. const CLOSED: MenuState = { open: false, hit: null, generation: 0, groups: [], highlight: null }
  26. function openState(partial?: Partial<MenuState>): MenuState {
  27. return {
  28. open: true,
  29. hit,
  30. generation: 1,
  31. groups: [
  32. { source: 'command', status: 'ready', items: [{ name: 'goal', description: 'Set up a goal', icon: '⚑' }, { name: 'plan' }] },
  33. { source: 'skill', status: 'pending', items: [] },
  34. ],
  35. highlight: { source: 'command', index: 0 },
  36. ...partial,
  37. }
  38. }
  39. // jsdom has no scrollIntoView; the view calls it on the highlighted option.
  40. const scrollIntoView = vi.fn()
  41. beforeEach(() => {
  42. Element.prototype.scrollIntoView = scrollIntoView
  43. scrollIntoView.mockClear()
  44. })
  45. afterEach(() => {
  46. cleanup()
  47. vi.restoreAllMocks()
  48. })
  49. // The framework-injected t seat, stubbed over the zh dictionaries (the
  50. // default locale); the stub mirrors the LocaleRuntime key fallback, so an
  51. // unknown source comes back verbatim (its raw name).
  52. const t = makeTranslate(zh, commonZh)
  53. function mount(state: MenuState) {
  54. const menu = createSnapshotStore<MenuState>(state)
  55. const onPick = vi.fn()
  56. const onDismiss = vi.fn()
  57. const view = render(<MenuView menu={menu} onPick={onPick} onDismiss={onDismiss} t={t} />)
  58. return { menu, onPick, onDismiss, view }
  59. }
  60. /** The non-interactive group title rows (role=presentation), in document order. */
  61. function titles(container: HTMLElement): string[] {
  62. return [...container.querySelectorAll('div[role="presentation"][data-source]')]
  63. .map(el => el.textContent ?? '')
  64. }
  65. describe('MenuView', () => {
  66. it('renders null while closed and appears when the store opens', () => {
  67. const { menu, view } = mount(CLOSED)
  68. expect(view.container.childElementCount).toBe(0)
  69. act(() => { menu.set(openState()) })
  70. expect(screen.queryByRole('listbox')).not.toBeNull()
  71. act(() => { menu.set(CLOSED) })
  72. expect(view.container.childElementCount).toBe(0)
  73. })
  74. it('renders ready groups as option rows and pending groups as loading rows', () => {
  75. mount(openState())
  76. const options = screen.getAllByRole('option')
  77. expect(options.map(o => o.textContent)).toEqual(['⚑goalSet up a goal', 'plan'])
  78. expect(screen.queryByText('正在加载…')).not.toBeNull()
  79. })
  80. it('keeps an opted-out source title hidden while its candidates are pending', () => {
  81. mount(openState({
  82. groups: [{ source: 'reference', showGroupTitle: false, status: 'pending', items: [] }],
  83. highlight: null,
  84. }))
  85. expect(screen.queryByText('reference')).toBeNull()
  86. expect(screen.getByText('正在加载…')).toBeTruthy()
  87. })
  88. it('titles each group with the localized source name, raw name for unknown sources, none for empty ready groups', () => {
  89. const { view } = mount(openState({
  90. groups: [
  91. { source: 'command', status: 'ready', items: [{ name: 'goal' }] },
  92. { source: 'hollow', status: 'ready', items: [] },
  93. { source: 'mystery', status: 'ready', items: [{ name: 'x' }] },
  94. { source: 'skill', status: 'pending', items: [] },
  95. ],
  96. }))
  97. expect(titles(view.container)).toEqual(['命令', 'mystery', '技能'])
  98. })
  99. it('renders contiguous candidate sections once without changing option indexes', () => {
  100. const { onPick } = mount(openState({
  101. groups: [{
  102. source: 'reference',
  103. status: 'ready',
  104. items: [
  105. { name: 'Folder · src/', section: '文件与文件夹' },
  106. { name: 'File · README.md', section: '文件与文件夹' },
  107. { name: 'Session · Research', section: 'Session 对话' },
  108. ],
  109. }],
  110. highlight: { source: 'reference', index: 0 },
  111. }))
  112. expect(screen.queryByText('reference')).toBeNull()
  113. expect(screen.getAllByText('文件与文件夹')).toHaveLength(1)
  114. expect(screen.getAllByText('Session 对话')).toHaveLength(1)
  115. const options = screen.getAllByRole('option')
  116. expect(options.map(option => option.textContent)).toEqual([
  117. 'Folder · src/',
  118. 'File · README.md',
  119. 'Session · Research',
  120. ])
  121. fireEvent.mouseDown(options[2]!)
  122. expect(onPick).toHaveBeenCalledWith('reference', 2)
  123. })
  124. it('exposes the highlight via aria-activedescendant and aria-selected', () => {
  125. mount(openState({ highlight: { source: 'command', index: 1 } }))
  126. const listbox = screen.getByRole('listbox')
  127. const options = screen.getAllByRole('option')
  128. expect(options[1]!.id).toBeTruthy()
  129. expect(listbox.getAttribute('aria-activedescendant')).toBe(options[1]!.id)
  130. expect(options[1]!.getAttribute('aria-selected')).toBe('true')
  131. expect(options[0]!.getAttribute('aria-selected')).toBe('false')
  132. })
  133. it('omits aria-activedescendant without a highlight', () => {
  134. mount(openState({ highlight: null }))
  135. expect(screen.getByRole('listbox').getAttribute('aria-activedescendant')).toBeNull()
  136. })
  137. it('scrolls the highlighted option into view when the highlight moves', () => {
  138. const { menu } = mount(openState())
  139. scrollIntoView.mockClear()
  140. act(() => { menu.set(openState({ highlight: { source: 'command', index: 1 } })) })
  141. const options = screen.getAllByRole('option')
  142. expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' })
  143. expect(scrollIntoView.mock.instances.at(-1)).toBe(options[1])
  144. })
  145. it('caps the list height at the design maximum when the composer sits low enough', () => {
  146. vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ bottom: 800 } as DOMRect)
  147. mount(openState())
  148. expect(screen.getByRole('listbox').style.maxHeight).toBe('320px')
  149. })
  150. it('clamps the list height to the space above the composer minus the safe margin', () => {
  151. vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ bottom: 200 } as DOMRect)
  152. mount(openState())
  153. expect(screen.getByRole('listbox').style.maxHeight).toBe('188px')
  154. })
  155. it('re-fits the height when the window resizes', () => {
  156. const rect = vi.spyOn(Element.prototype, 'getBoundingClientRect')
  157. rect.mockReturnValue({ bottom: 800 } as DOMRect)
  158. mount(openState())
  159. expect(screen.getByRole('listbox').style.maxHeight).toBe('320px')
  160. rect.mockReturnValue({ bottom: 100 } as DOMRect)
  161. act(() => { window.dispatchEvent(new Event('resize')) })
  162. expect(screen.getByRole('listbox').style.maxHeight).toBe('88px')
  163. })
  164. it('pointerdown outside the menu (no composer card ancestor) dismisses', () => {
  165. const { onDismiss } = mount(openState())
  166. fireEvent.pointerDown(document.body)
  167. expect(onDismiss).toHaveBeenCalledTimes(1)
  168. })
  169. it('pointerdown inside the list does not dismiss', () => {
  170. const { onDismiss } = mount(openState())
  171. fireEvent.pointerDown(screen.getAllByRole('option')[0]!)
  172. expect(onDismiss).not.toHaveBeenCalled()
  173. })
  174. it('pointerdown inside the surrounding composer card does not dismiss; outside it does', () => {
  175. const menu = createSnapshotStore<MenuState>(openState())
  176. const onDismiss = vi.fn()
  177. render(
  178. <div data-composer-card="">
  179. <MenuView menu={menu} onPick={vi.fn()} onDismiss={onDismiss} t={t} />
  180. <button type="button" data-testid="composer-button" />
  181. </div>,
  182. )
  183. fireEvent.pointerDown(screen.getByTestId('composer-button'))
  184. expect(onDismiss).not.toHaveBeenCalled()
  185. fireEvent.pointerDown(document.body)
  186. expect(onDismiss).toHaveBeenCalledTimes(1)
  187. })
  188. it('ignores a pointerdown whose target is not a DOM node', () => {
  189. const { onDismiss } = mount(openState())
  190. const ev = new Event('pointerdown', { bubbles: true })
  191. Object.defineProperty(ev, 'target', { value: {} })
  192. document.dispatchEvent(ev)
  193. expect(onDismiss).not.toHaveBeenCalled()
  194. })
  195. it('closing the menu removes the dismiss listener', () => {
  196. const { menu, onDismiss } = mount(openState())
  197. act(() => { menu.set(CLOSED) })
  198. fireEvent.pointerDown(document.body)
  199. expect(onDismiss).not.toHaveBeenCalled()
  200. })
  201. it('mousedown on a row picks (source, index) and prevents the focus steal', () => {
  202. const { onPick } = mount(openState())
  203. const options = screen.getAllByRole('option')
  204. const notPrevented = fireEvent.mouseDown(options[1]!)
  205. // fireEvent returns false when preventDefault was called.
  206. expect(notPrevented).toBe(false)
  207. expect(onPick).toHaveBeenCalledWith('command', 1)
  208. })
  209. })