menu-view.client.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 skeleton
  6. * placeholders, pointer picks route (source, index) back without stealing
  7. * focus, the highlight is exposed through aria-activedescendant +
  8. * aria-selected, and 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 {
  17. InputTriggerCrumb, MenuState, TriggerHit,
  18. } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
  19. import { MenuView } from '../src/client/MenuView.tsx'
  20. const hit: TriggerHit = {
  21. trigger: '/',
  22. query: 'g',
  23. quoted: false,
  24. position: 'leading',
  25. span: { start: 0, end: 2, draftRev: 1 },
  26. }
  27. const CLOSED: MenuState = { open: false, hit: null, generation: 0, groups: [], highlight: null }
  28. function openState(partial?: Partial<MenuState>): MenuState {
  29. return {
  30. open: true,
  31. hit,
  32. generation: 1,
  33. groups: [
  34. { source: 'command', status: 'ready', items: [{ name: 'goal', description: 'Set up a goal', icon: 'file' }, { name: 'plan' }] },
  35. { source: 'skill', status: 'pending', items: [] },
  36. ],
  37. highlight: { source: 'command', index: 0 },
  38. ...partial,
  39. }
  40. }
  41. // jsdom has no scrollIntoView; the view calls it on the highlighted option.
  42. const scrollIntoView = vi.fn()
  43. beforeEach(() => {
  44. Element.prototype.scrollIntoView = scrollIntoView
  45. scrollIntoView.mockClear()
  46. })
  47. afterEach(() => {
  48. cleanup()
  49. vi.restoreAllMocks()
  50. })
  51. // The framework-injected t seat, stubbed over the zh dictionaries (the
  52. // default locale); the stub mirrors the LocaleRuntime key fallback, so an
  53. // unknown source comes back verbatim (its raw name).
  54. const t = makeTranslate(zh, commonZh)
  55. function mount(state: MenuState, crumbs: ReadonlyMap<string, readonly InputTriggerCrumb[]> = new Map()) {
  56. const menu = createSnapshotStore<MenuState>(state)
  57. const headers = createSnapshotStore<ReadonlyMap<string, readonly InputTriggerCrumb[]>>(crumbs)
  58. const onPick = vi.fn()
  59. const onCrumb = vi.fn()
  60. const onHover = vi.fn()
  61. const onDismiss = vi.fn()
  62. const view = render(
  63. <MenuView
  64. menu={menu}
  65. headers={headers}
  66. onPick={onPick}
  67. onCrumb={onCrumb}
  68. onHover={onHover}
  69. onDismiss={onDismiss}
  70. t={t}
  71. />,
  72. )
  73. return { menu, headers, onPick, onCrumb, onHover, onDismiss, view }
  74. }
  75. /** The bounded menu shell: it owns the height clamp, the listbox scrolls inside it. */
  76. function menuShell(): HTMLElement {
  77. const shell = document.querySelector('[data-trigger-menu]')
  78. if (!(shell instanceof HTMLElement)) throw new Error('menu shell is not rendered')
  79. return shell
  80. }
  81. /** The non-interactive group title rows (role=presentation), in document order. */
  82. function titles(container: HTMLElement): string[] {
  83. return [...container.querySelectorAll('div[role="presentation"][data-source]')]
  84. .map(el => el.textContent ?? '')
  85. }
  86. describe('MenuView', () => {
  87. it('renders null while closed and appears when the store opens', () => {
  88. const { menu, view } = mount(CLOSED)
  89. expect(view.container.childElementCount).toBe(0)
  90. act(() => { menu.set(openState()) })
  91. expect(screen.queryByRole('listbox')).not.toBeNull()
  92. act(() => { menu.set(CLOSED) })
  93. expect(view.container.childElementCount).toBe(0)
  94. })
  95. it('renders ready groups as option rows and pending groups as two skeleton rows', () => {
  96. mount(openState())
  97. const options = screen.getAllByRole('option')
  98. expect(options.map(o => o.textContent)).toEqual(['goalSet up a goal', 'plan'])
  99. // The icon token renders as an SVG glyph, not text.
  100. expect(options[0]?.querySelector('svg')).not.toBeNull()
  101. expect(options[1]?.querySelector('svg')).toBeNull()
  102. const status = screen.getByRole('status', { name: '正在加载…' })
  103. expect(status.children).toHaveLength(2)
  104. })
  105. it('renders a localized label as the title with the name as its alias, an icon component, and the description', () => {
  106. const Glyph = ({ size = 16 }: { size?: number | undefined }) => <svg data-glyph="plan" width={size} height={size} />
  107. mount(openState({
  108. groups: [{
  109. source: 'command',
  110. status: 'ready',
  111. items: [
  112. { name: 'plan', label: '计划', description: '进入或退出计划模式', icon: Glyph, section: '添加' },
  113. { name: 'file', label: 'File', section: '添加' },
  114. ],
  115. }],
  116. }))
  117. const options = screen.getAllByRole('option')
  118. expect(options.map(o => o.textContent)).toEqual(['计划plan进入或退出计划模式', 'File'])
  119. expect(options[0]?.querySelector('[data-glyph="plan"]')?.getAttribute('width')).toBe('16')
  120. // A label that is the name in another letter case renders no alias.
  121. expect(options[1]?.querySelectorAll('span')).toHaveLength(1)
  122. expect(screen.getAllByText('添加')).toHaveLength(1)
  123. })
  124. it('keeps an opted-out source title hidden while its candidates are pending', () => {
  125. mount(openState({
  126. groups: [{ source: 'reference', showGroupTitle: false, status: 'pending', items: [] }],
  127. highlight: null,
  128. }))
  129. expect(screen.queryByText('reference')).toBeNull()
  130. expect(screen.getByRole('status', { name: '正在加载…' })).toBeTruthy()
  131. })
  132. it('renders retained items instead of skeletons while a refinement is pending', () => {
  133. mount(openState({
  134. groups: [{ source: 'command', status: 'pending', items: [{ name: 'goal' }] }],
  135. highlight: null,
  136. }))
  137. expect(screen.getAllByRole('option').map(o => o.textContent)).toEqual(['goal'])
  138. expect(screen.queryByRole('status')).toBeNull()
  139. })
  140. it('titles each group with the localized source name, raw name for unknown sources, none for empty ready groups', () => {
  141. const { view } = mount(openState({
  142. groups: [
  143. { source: 'command', status: 'ready', items: [{ name: 'goal' }] },
  144. { source: 'hollow', status: 'ready', items: [] },
  145. { source: 'mystery', status: 'ready', items: [{ name: 'x' }] },
  146. { source: 'skill', status: 'pending', items: [] },
  147. ],
  148. }))
  149. expect(titles(view.container)).toEqual(['指令', 'mystery', '技能'])
  150. })
  151. it('renders contiguous candidate sections once without changing option indexes', () => {
  152. const { onPick } = mount(openState({
  153. groups: [{
  154. source: 'reference',
  155. status: 'ready',
  156. items: [
  157. { name: 'Folder · src/', section: '文件与文件夹' },
  158. { name: 'File · README.md', section: '文件与文件夹' },
  159. { name: 'Session · Research', section: '对话' },
  160. ],
  161. }],
  162. highlight: { source: 'reference', index: 0 },
  163. }))
  164. expect(screen.queryByText('reference')).toBeNull()
  165. expect(screen.getAllByText('文件与文件夹')).toHaveLength(1)
  166. expect(screen.getAllByText('对话')).toHaveLength(1)
  167. const options = screen.getAllByRole('option')
  168. expect(options.map(option => option.textContent)).toEqual([
  169. 'Folder · src/',
  170. 'File · README.md',
  171. 'Session · Research',
  172. ])
  173. fireEvent.mouseDown(options[2]!)
  174. expect(onPick).toHaveBeenCalledWith('reference', 2)
  175. })
  176. it('renders the drill chevron only on drillable rows and routes its own action', () => {
  177. const { onPick } = mount(openState({
  178. groups: [{
  179. source: 'reference',
  180. status: 'ready',
  181. items: [
  182. { name: 'Folder · src/', drill: true },
  183. { name: 'File · README.md' },
  184. ],
  185. }],
  186. highlight: { source: 'reference', index: 0 },
  187. }))
  188. const chevrons = screen.getAllByRole('button', { name: '进入目录' })
  189. expect(chevrons).toHaveLength(1)
  190. // The chevron drills; the row body still settles the pick untouched.
  191. fireEvent.mouseDown(chevrons[0]!)
  192. expect(onPick).toHaveBeenCalledWith('reference', 0, 'drill')
  193. fireEvent.mouseDown(screen.getAllByRole('option')[0]!)
  194. expect(onPick).toHaveBeenCalledWith('reference', 0)
  195. })
  196. it('exposes the highlight via aria-activedescendant and aria-selected', () => {
  197. mount(openState({ highlight: { source: 'command', index: 1 } }))
  198. const listbox = screen.getByRole('listbox')
  199. const options = screen.getAllByRole('option')
  200. expect(options[1]!.id).toBeTruthy()
  201. expect(listbox.getAttribute('aria-activedescendant')).toBe(options[1]!.id)
  202. expect(options[1]!.getAttribute('aria-selected')).toBe('true')
  203. expect(options[0]!.getAttribute('aria-selected')).toBe('false')
  204. })
  205. it('omits aria-activedescendant without a highlight', () => {
  206. mount(openState({ highlight: null }))
  207. expect(screen.getByRole('listbox').getAttribute('aria-activedescendant')).toBeNull()
  208. })
  209. it('scrolls the highlighted option into view when the highlight moves', () => {
  210. const { menu } = mount(openState())
  211. scrollIntoView.mockClear()
  212. act(() => { menu.set(openState({ highlight: { source: 'command', index: 1 } })) })
  213. const options = screen.getAllByRole('option')
  214. expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' })
  215. expect(scrollIntoView.mock.instances.at(-1)).toBe(options[1])
  216. })
  217. it('caps the list height at the design maximum when the composer sits low enough', () => {
  218. vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ bottom: 800 } as DOMRect)
  219. mount(openState())
  220. expect(menuShell().style.maxHeight).toBe('400px')
  221. })
  222. it('clamps the list height to the space above the composer minus the safe margin', () => {
  223. vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ bottom: 200 } as DOMRect)
  224. mount(openState())
  225. expect(menuShell().style.maxHeight).toBe('188px')
  226. })
  227. it('re-fits the height when the window resizes', () => {
  228. const rect = vi.spyOn(Element.prototype, 'getBoundingClientRect')
  229. rect.mockReturnValue({ bottom: 800 } as DOMRect)
  230. mount(openState())
  231. expect(menuShell().style.maxHeight).toBe('400px')
  232. rect.mockReturnValue({ bottom: 100 } as DOMRect)
  233. act(() => { window.dispatchEvent(new Event('resize')) })
  234. expect(menuShell().style.maxHeight).toBe('88px')
  235. })
  236. it('shows the bottom overflow hint until the list reaches its final row', () => {
  237. mount(openState())
  238. const listbox = screen.getByRole('listbox')
  239. Object.defineProperties(listbox, {
  240. clientHeight: { configurable: true, value: 320 },
  241. scrollHeight: { configurable: true, value: 392 },
  242. scrollTop: { configurable: true, value: 0, writable: true },
  243. })
  244. fireEvent.scroll(listbox)
  245. expect(menuShell().hasAttribute('data-overflow-below')).toBe(true)
  246. listbox.scrollTop = 72
  247. fireEvent.scroll(listbox)
  248. expect(menuShell().hasAttribute('data-overflow-below')).toBe(false)
  249. })
  250. it('pointerdown outside the menu (no composer card ancestor) dismisses', () => {
  251. const { onDismiss } = mount(openState())
  252. fireEvent.pointerDown(document.body)
  253. expect(onDismiss).toHaveBeenCalledTimes(1)
  254. })
  255. it('pointerdown inside the list does not dismiss', () => {
  256. const { onDismiss } = mount(openState())
  257. fireEvent.pointerDown(screen.getAllByRole('option')[0]!)
  258. expect(onDismiss).not.toHaveBeenCalled()
  259. })
  260. it('pointerdown inside the surrounding composer card does not dismiss; outside it does', () => {
  261. const menu = createSnapshotStore<MenuState>(openState())
  262. const onDismiss = vi.fn()
  263. render(
  264. <div data-composer-card="">
  265. <MenuView
  266. menu={menu}
  267. headers={createSnapshotStore<ReadonlyMap<string, readonly InputTriggerCrumb[]>>(new Map())}
  268. onPick={vi.fn()}
  269. onCrumb={vi.fn()}
  270. onHover={vi.fn()}
  271. onDismiss={onDismiss}
  272. t={t}
  273. />
  274. <button type="button" data-testid="composer-button" />
  275. </div>,
  276. )
  277. fireEvent.pointerDown(screen.getByTestId('composer-button'))
  278. expect(onDismiss).not.toHaveBeenCalled()
  279. fireEvent.pointerDown(document.body)
  280. expect(onDismiss).toHaveBeenCalledTimes(1)
  281. })
  282. it('ignores a pointerdown whose target is not a DOM node', () => {
  283. const { onDismiss } = mount(openState())
  284. const ev = new Event('pointerdown', { bubbles: true })
  285. Object.defineProperty(ev, 'target', { value: {} })
  286. document.dispatchEvent(ev)
  287. expect(onDismiss).not.toHaveBeenCalled()
  288. })
  289. it('closing the menu removes the dismiss listener', () => {
  290. const { menu, onDismiss } = mount(openState())
  291. act(() => { menu.set(CLOSED) })
  292. fireEvent.pointerDown(document.body)
  293. expect(onDismiss).not.toHaveBeenCalled()
  294. })
  295. it('mousedown on a row picks (source, index) and prevents the focus steal', () => {
  296. const { onPick } = mount(openState())
  297. const options = screen.getAllByRole('option')
  298. const notPrevented = fireEvent.mouseDown(options[1]!)
  299. // fireEvent returns false when preventDefault was called.
  300. expect(notPrevented).toBe(false)
  301. expect(onPick).toHaveBeenCalledWith('command', 1)
  302. })
  303. it('pointer motion over a row routes hover; the highlighted row stays silent', () => {
  304. const { onHover } = mount(openState())
  305. const options = screen.getAllByRole('option')
  306. fireEvent.mouseMove(options[1]!)
  307. expect(onHover).toHaveBeenCalledWith('command', 1)
  308. onHover.mockClear()
  309. // Index 0 already holds the highlight: no hover round-trip.
  310. fireEvent.mouseMove(options[0]!)
  311. expect(onHover).not.toHaveBeenCalled()
  312. })
  313. it('renders a source header as a breadcrumb above the list, current step last', () => {
  314. mount(openState(), new Map([['command', [
  315. { label: 'Workspace', value: 'root' },
  316. { label: 'src', value: 'src' },
  317. { label: 'module1', value: 'module1', current: true },
  318. ]]]))
  319. const nav = screen.getByRole('navigation', { name: '目录导航' })
  320. expect([...nav.querySelectorAll('button')].map(button => button.textContent))
  321. .toEqual(['Workspace', 'src', 'module1'])
  322. // The listbox holds options alone; the header is its sibling, not a row.
  323. expect(screen.getByRole('listbox').contains(nav)).toBe(false)
  324. })
  325. it('mousedown on a crumb routes (source, index) without stealing focus; the current step is inert', () => {
  326. const { onCrumb } = mount(openState(), new Map([['command', [
  327. { label: 'Workspace', value: 'root' },
  328. { label: 'src', value: 'src', current: true },
  329. ]]]))
  330. const crumbs = screen.getByRole('navigation', { name: '目录导航' }).querySelectorAll('button')
  331. expect(fireEvent.mouseDown(crumbs[0]!)).toBe(false)
  332. expect(onCrumb).toHaveBeenCalledWith('command', 0)
  333. onCrumb.mockClear()
  334. expect(crumbs[1]!.disabled).toBe(true)
  335. fireEvent.mouseDown(crumbs[1]!)
  336. expect(onCrumb).not.toHaveBeenCalled()
  337. })
  338. it('renders no header for a source that published no crumbs', () => {
  339. mount(openState())
  340. expect(screen.queryByRole('navigation')).toBeNull()
  341. })
  342. })