popup.spec.ts 16 KB

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