popup.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /**
  2. * PopupSelectController behavior (design §10.2/§10.3): one options load per
  3. * open with local search filtering, filtered highlight movement,
  4. * single-flight select with open-time context, consume-on-success (CAS miss
  5. * benign), failure-keeps-open retry semantics for both options and onSelect,
  6. * and binding-identity revocation of late settlements after
  7. * dismiss/reopen/dispose.
  8. */
  9. import { describe, expect, it, vi } from 'vitest'
  10. import type { SelectOption } from '../src/client/contract.ts'
  11. import type { PopupSpec, TokenSegment } from '../src/client/popup.ts'
  12. import { filterOptions, PopupSelectController } from '../src/client/popup.ts'
  13. interface Ctx { readonly session: string }
  14. const CTX_A: Ctx = { session: 'A' }
  15. const OPTIONS: SelectOption[] = [
  16. { id: 'dark', label: 'Dark' },
  17. { id: 'light', label: 'Light', active: true },
  18. { id: 'sepia', label: 'Sepia', detail: 'warm' },
  19. ]
  20. const SEGMENT: TokenSegment = { via: 'enter', token: '/theme' }
  21. function spec(overrides: Partial<PopupSpec<Ctx>> = {}): PopupSpec<Ctx> {
  22. return {
  23. options: () => Promise.resolve(OPTIONS),
  24. onSelect: () => undefined,
  25. ...overrides,
  26. }
  27. }
  28. /** Fake session wiring: records consume/focus calls; consume answer is settable per test. */
  29. function makeDeps(consumeResult = true) {
  30. const consume = vi.fn((_segment: TokenSegment) => consumeResult)
  31. const focusComposer = vi.fn()
  32. return { consume, focusComposer }
  33. }
  34. async function readyPopup(overrides: Partial<PopupSpec<Ctx>> = {}, deps = makeDeps()) {
  35. const popup = new PopupSelectController<Ctx>(deps)
  36. popup.open('theme', spec(overrides), CTX_A, SEGMENT)
  37. await Promise.resolve()
  38. return { popup, deps }
  39. }
  40. describe('filterOptions', () => {
  41. it('matches case-insensitively over label and detail; blank keeps all', () => {
  42. expect(filterOptions(OPTIONS, '')).toBe(OPTIONS)
  43. expect(filterOptions(OPTIONS, ' ')).toBe(OPTIONS)
  44. expect(filterOptions(OPTIONS, 'DARK')).toEqual([OPTIONS[0]])
  45. expect(filterOptions(OPTIONS, 'warm')).toEqual([OPTIONS[2]])
  46. expect(filterOptions(OPTIONS, 'nope')).toEqual([])
  47. })
  48. })
  49. describe('open and options load', () => {
  50. it('publishes pending immediately, ready when options land', async () => {
  51. const popup = new PopupSelectController<Ctx>(makeDeps())
  52. let release!: (options: readonly SelectOption[]) => void
  53. popup.open('theme', spec({ options: () => new Promise((resolve) => { release = resolve }) }), CTX_A, SEGMENT)
  54. expect(popup.state.getSnapshot()).toMatchObject({ open: true, command: 'theme', status: 'pending', search: '', submitting: false, error: null })
  55. release(OPTIONS)
  56. await Promise.resolve()
  57. expect(popup.state.getSnapshot()).toMatchObject({ status: 'ready', options: OPTIONS, active: 0 })
  58. })
  59. it('loads options exactly once: search filters locally without re-querying the provider', async () => {
  60. const options = vi.fn(() => Promise.resolve(OPTIONS))
  61. const { popup } = await readyPopup({ options })
  62. popup.setSearch('li')
  63. popup.setSearch('light')
  64. const s = popup.state.getSnapshot()
  65. expect(options).toHaveBeenCalledTimes(1)
  66. expect(s.options).toEqual(OPTIONS) // original array retained; filtering is view-side
  67. expect(s.search).toBe('light')
  68. expect(filterOptions(s.options, s.search)).toEqual([OPTIONS[1]])
  69. })
  70. it('a reopen aborts the old load and drops its late arrival', async () => {
  71. const popup = new PopupSelectController<Ctx>(makeDeps())
  72. let firstSignal!: AbortSignal
  73. let releaseFirst!: (options: readonly SelectOption[]) => void
  74. popup.open('alpha', spec({
  75. options: (_ctx, signal) => {
  76. firstSignal = signal
  77. return new Promise((resolve) => { releaseFirst = resolve })
  78. },
  79. }), CTX_A, SEGMENT)
  80. popup.open('beta', spec(), CTX_A, SEGMENT)
  81. expect(firstSignal.aborted).toBe(true)
  82. releaseFirst([{ id: 'stale', label: 'stale' }])
  83. await Promise.resolve()
  84. const s = popup.state.getSnapshot()
  85. expect(s.command).toBe('beta')
  86. expect(s.options).toEqual(OPTIONS)
  87. })
  88. it('dispose aborts the flying load, clears state, and drops the late arrival', async () => {
  89. const popup = new PopupSelectController<Ctx>(makeDeps())
  90. let signal!: AbortSignal
  91. let release!: (options: readonly SelectOption[]) => void
  92. popup.open('theme', spec({
  93. options: (_ctx, s) => {
  94. signal = s
  95. return new Promise((resolve) => { release = resolve })
  96. },
  97. }), CTX_A, SEGMENT)
  98. popup.dispose()
  99. expect(signal.aborted).toBe(true)
  100. expect(popup.state.getSnapshot().open).toBe(false)
  101. release(OPTIONS)
  102. await Promise.resolve()
  103. expect(popup.state.getSnapshot().open).toBe(false)
  104. })
  105. it('an options failure keeps the shell open with search retained, surfaces the error, and retry reloads', async () => {
  106. let attempts = 0
  107. const { popup } = await readyPopup({
  108. options: () => {
  109. attempts += 1
  110. return attempts === 1 ? Promise.reject(new Error('directory down')) : Promise.resolve(OPTIONS)
  111. },
  112. })
  113. await Promise.resolve()
  114. popup.setSearch('da')
  115. // The failure landed before setSearch (readyPopup awaited); search must survive it and retry.
  116. expect(popup.state.getSnapshot()).toMatchObject({ open: true, status: 'failed', error: 'directory down', search: 'da' })
  117. popup.retry()
  118. expect(popup.state.getSnapshot()).toMatchObject({ status: 'pending', error: null })
  119. await Promise.resolve()
  120. expect(popup.state.getSnapshot()).toMatchObject({ status: 'ready', options: OPTIONS, search: 'da' })
  121. expect(attempts).toBe(2)
  122. })
  123. it('retry is a no-op unless the options load failed', async () => {
  124. const { popup } = await readyPopup()
  125. popup.retry()
  126. expect(popup.state.getSnapshot().status).toBe('ready')
  127. const closed = new PopupSelectController<Ctx>(makeDeps())
  128. closed.retry()
  129. expect(closed.state.getSnapshot().open).toBe(false)
  130. })
  131. })
  132. describe('search / move / highlight over the filtered list', () => {
  133. it('setSearch rebases the highlight to 0 and ignores closed shells and identical text', async () => {
  134. const { popup } = await readyPopup()
  135. popup.move(1)
  136. expect(popup.state.getSnapshot().active).toBe(1)
  137. popup.setSearch('s')
  138. expect(popup.state.getSnapshot()).toMatchObject({ search: 's', active: 0 })
  139. const before = popup.state.getSnapshot()
  140. popup.setSearch('s')
  141. expect(popup.state.getSnapshot()).toBe(before)
  142. const closed = new PopupSelectController<Ctx>(makeDeps())
  143. closed.setSearch('x')
  144. expect(closed.state.getSnapshot().search).toBe('')
  145. })
  146. it('move wraps across the FILTERED rows', async () => {
  147. const { popup } = await readyPopup()
  148. popup.setSearch('a') // Dark, Sepia (detail 'warm' also matches 'a'? label match: Dark, Sepia)
  149. const rows = filterOptions(popup.state.getSnapshot().options, 'a')
  150. expect(rows.length).toBe(2)
  151. popup.move(1)
  152. expect(popup.state.getSnapshot().active).toBe(1)
  153. popup.move(1)
  154. expect(popup.state.getSnapshot().active).toBe(0)
  155. popup.move(-1)
  156. expect(popup.state.getSnapshot().active).toBe(1)
  157. })
  158. it('move is a no-op while pending, closed, or when the filter matches nothing', async () => {
  159. const pending = new PopupSelectController<Ctx>(makeDeps())
  160. pending.open('theme', spec({ options: () => new Promise(() => {}) }), CTX_A, SEGMENT)
  161. pending.move(1)
  162. expect(pending.state.getSnapshot().active).toBe(0)
  163. const closed = new PopupSelectController<Ctx>(makeDeps())
  164. closed.move(1)
  165. expect(closed.state.getSnapshot().active).toBe(0)
  166. const { popup } = await readyPopup()
  167. popup.setSearch('nope')
  168. popup.move(1)
  169. expect(popup.state.getSnapshot().active).toBe(0)
  170. })
  171. it('highlight sets the active filtered row and ignores out-of-range or same-index calls', async () => {
  172. const { popup } = await readyPopup()
  173. popup.highlight(1)
  174. expect(popup.state.getSnapshot().active).toBe(1)
  175. popup.highlight(99)
  176. popup.highlight(-1)
  177. popup.highlight(1)
  178. expect(popup.state.getSnapshot().active).toBe(1)
  179. popup.setSearch('dark') // one filtered row → index 1 now out of range
  180. popup.highlight(1)
  181. expect(popup.state.getSnapshot().active).toBe(0)
  182. })
  183. })
  184. describe('select', () => {
  185. it('runs onSelect with the filtered option and the open-time context, consumes, closes, refocuses', async () => {
  186. const seen: Array<{ option: SelectOption; context: Ctx }> = []
  187. const deps = makeDeps()
  188. const { popup } = await readyPopup({
  189. onSelect: (option, context) => { seen.push({ option, context }) },
  190. }, deps)
  191. popup.setSearch('light')
  192. await popup.select(0)
  193. expect(seen).toEqual([{ option: OPTIONS[1], context: CTX_A }])
  194. expect(deps.consume).toHaveBeenCalledExactlyOnceWith(SEGMENT)
  195. expect(deps.focusComposer).toHaveBeenCalledTimes(1)
  196. expect(popup.state.getSnapshot().open).toBe(false)
  197. })
  198. it('is single-flight: the first call enters submitting, later Enter/click calls no-op', async () => {
  199. let release!: () => void
  200. const onSelect = vi.fn(() => new Promise<void>((resolve) => { release = resolve }))
  201. const deps = makeDeps()
  202. const { popup } = await readyPopup({ onSelect }, deps)
  203. const first = popup.select(0)
  204. expect(popup.state.getSnapshot().submitting).toBe(true)
  205. await popup.select(0)
  206. await popup.select(1)
  207. popup.setSearch('x') // locked while submitting
  208. popup.move(1)
  209. popup.highlight(1)
  210. expect(popup.state.getSnapshot()).toMatchObject({ search: '', active: 0 })
  211. release()
  212. await first
  213. expect(onSelect).toHaveBeenCalledTimes(1)
  214. expect(deps.consume).toHaveBeenCalledTimes(1)
  215. expect(popup.state.getSnapshot().open).toBe(false)
  216. })
  217. it('a consume CAS miss is benign: no retry, still closes and refocuses', async () => {
  218. const deps = makeDeps(false)
  219. const { popup } = await readyPopup({}, deps)
  220. await popup.select(0)
  221. expect(deps.consume).toHaveBeenCalledTimes(1)
  222. expect(deps.focusComposer).toHaveBeenCalledTimes(1)
  223. expect(popup.state.getSnapshot().open).toBe(false)
  224. })
  225. it('an onSelect failure keeps the shell open with search/highlight/token intact, no consumption, and select re-arms', async () => {
  226. let attempts = 0
  227. const deps = makeDeps()
  228. const { popup } = await readyPopup({
  229. onSelect: () => {
  230. attempts += 1
  231. if (attempts === 1) throw new Error('host rejected')
  232. return undefined
  233. },
  234. }, deps)
  235. popup.setSearch('a')
  236. popup.move(1)
  237. await popup.select(1)
  238. expect(popup.state.getSnapshot()).toMatchObject({
  239. open: true, status: 'ready', submitting: false, error: 'host rejected', search: 'a', active: 1,
  240. })
  241. expect(deps.consume).not.toHaveBeenCalled()
  242. await popup.select(1) // retry = selecting again
  243. expect(deps.consume).toHaveBeenCalledExactlyOnceWith(SEGMENT)
  244. expect(popup.state.getSnapshot().open).toBe(false)
  245. })
  246. it('ignores selects while closed, pending, failed, or out of filtered range', async () => {
  247. const closed = new PopupSelectController<Ctx>(makeDeps())
  248. await closed.select(0)
  249. expect(closed.state.getSnapshot().open).toBe(false)
  250. const failedDeps = makeDeps()
  251. const { popup: failed } = await readyPopup({ options: () => Promise.reject(new Error('x')) }, failedDeps)
  252. await failed.select(0)
  253. expect(failedDeps.consume).not.toHaveBeenCalled()
  254. const deps = makeDeps()
  255. const { popup } = await readyPopup({}, deps)
  256. popup.setSearch('dark')
  257. await popup.select(1) // only one filtered row
  258. expect(deps.consume).not.toHaveBeenCalled()
  259. expect(popup.state.getSnapshot().open).toBe(true)
  260. })
  261. it('a dismiss racing a succeeding onSelect revokes it: no consume, no focus, state stays closed', async () => {
  262. let release!: () => void
  263. const deps = makeDeps()
  264. const { popup } = await readyPopup({
  265. onSelect: () => new Promise<void>((resolve) => { release = resolve }),
  266. }, deps)
  267. const selecting = popup.select(0)
  268. popup.dismiss()
  269. release()
  270. await selecting
  271. expect(deps.consume).not.toHaveBeenCalled()
  272. expect(deps.focusComposer).not.toHaveBeenCalled()
  273. expect(popup.state.getSnapshot().open).toBe(false)
  274. })
  275. it('a dispose racing a failing onSelect revokes its error write', async () => {
  276. let reject!: (error: Error) => void
  277. const deps = makeDeps()
  278. const { popup } = await readyPopup({
  279. onSelect: () => new Promise<void>((_resolve, rej) => { reject = rej }),
  280. }, deps)
  281. const selecting = popup.select(0)
  282. popup.dispose()
  283. reject(new Error('late'))
  284. await selecting
  285. expect(popup.state.getSnapshot()).toMatchObject({ open: false, error: null })
  286. expect(deps.consume).not.toHaveBeenCalled()
  287. })
  288. it('a reopen racing a succeeding onSelect keeps the new shell: no consume of the old segment', async () => {
  289. let release!: () => void
  290. const deps = makeDeps()
  291. const { popup } = await readyPopup({
  292. onSelect: () => new Promise<void>((resolve) => { release = resolve }),
  293. }, deps)
  294. const selecting = popup.select(0)
  295. popup.open('other', spec(), CTX_A, { via: 'enter', token: '/other' })
  296. release()
  297. await selecting
  298. await Promise.resolve()
  299. expect(deps.consume).not.toHaveBeenCalled()
  300. expect(popup.state.getSnapshot()).toMatchObject({ open: true, command: 'other' })
  301. })
  302. })
  303. describe('dismiss / dispose', () => {
  304. it('dismiss closes, aborts the flying fetch, and is a no-op when already closed', async () => {
  305. const deps = makeDeps()
  306. const popup = new PopupSelectController<Ctx>(deps)
  307. let signal!: AbortSignal
  308. popup.open('theme', spec({
  309. options: (_ctx, s) => {
  310. signal = s
  311. return new Promise(() => {})
  312. },
  313. }), CTX_A, SEGMENT)
  314. popup.dismiss()
  315. expect(signal.aborted).toBe(true)
  316. expect(popup.state.getSnapshot().open).toBe(false)
  317. expect(deps.focusComposer).not.toHaveBeenCalled() // outside-pointer path: the click's target takes focus
  318. popup.dismiss()
  319. popup.dispose()
  320. expect(popup.state.getSnapshot().open).toBe(false)
  321. })
  322. it('the Escape path restores composer focus explicitly', async () => {
  323. const deps = makeDeps()
  324. const { popup } = await readyPopup({}, deps)
  325. popup.dismiss({ focusComposer: true })
  326. expect(deps.focusComposer).toHaveBeenCalledTimes(1)
  327. expect(popup.state.getSnapshot().open).toBe(false)
  328. })
  329. })