app-frame.spec.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // @vitest-environment jsdom
  2. /**
  3. * AppFrame interaction spec under the four-share props form: real layout
  4. * store instance (createLayoutStore().create() — the test-sanctioned engine
  5. * path), a recording renderSlot stub, and a render-prop SessionProvider stub
  6. * (the real one is framework-wired to the renderer host; its own behavior is
  7. * web-react's spec territory). Drag sequences (pointer capture + rAF flush),
  8. * concession response to viewport change, and details staying mounted at
  9. * zero width are the preserved behavior assertions. jsdom has no layout
  10. * engine, so the frame width comes from a mocked getBoundingClientRect and
  11. * resizes are driven through the ResizeObserver stub.
  12. */
  13. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  14. import { act, cleanup, render } from '@testing-library/react'
  15. import { useSyncExternalStore } from 'react'
  16. import { AppFrame } from '@deepseek-ai/dsh-client-ui-layout/src/client/AppFrame.tsx'
  17. import type { AppFrameProps } from '@deepseek-ai/dsh-client-ui-layout/src/client/AppFrame.tsx'
  18. import { SIDEBAR_COLLAPSED } from '@deepseek-ai/dsh-client-ui-layout/src/client/columns.ts'
  19. import { createLayoutStore } from '@deepseek-ai/dsh-client-ui-layout/src/client/stores.ts'
  20. import type {
  21. SessionId, SessionListState, WorkspaceListState,
  22. } from '@deepseek-ai/dsh-client-runtime/client'
  23. // Session selection controls for the SessionProvider and useSessions stubs.
  24. const selectedSession = { current: 's-test' as SessionId | undefined }
  25. const selectedSessionBlank = { current: false }
  26. const baselinesReady = { current: true }
  27. // Render-prop contract stub fed through the standard seat prop (the renderer
  28. // injects the real one in production): session mode runs children(id), empty
  29. // mode runs the empty branch — the frame must work against exactly this
  30. // shape. Typed as the seat's own component type so the branded sessionId
  31. // parameter stays contract-checked.
  32. const SessionProviderStub: AppFrameProps['SessionProvider'] = ({ children, empty }) =>
  33. selectedSession.current === undefined ? <>{empty?.() ?? null}</> : <>{children(selectedSession.current)}</>
  34. /** Observer stub: captures the callback so tests can fire resizes manually. */
  35. let fireResize: (() => void) | null = null
  36. class ResizeObserverStub {
  37. #cb: ResizeObserverCallback
  38. constructor(cb: ResizeObserverCallback) { this.#cb = cb }
  39. observe(): void { fireResize = () => { this.#cb([], this) } }
  40. unobserve(): void {}
  41. disconnect(): void { fireResize = null }
  42. }
  43. let frameWidth = 1920
  44. /** Test-local selector hook over a framework-neutral store instance. */
  45. function hookOf<T>(inst: { subscribe: (fn: () => void) => () => void; getSnapshot: () => T }) {
  46. return function useSelector<S>(sel: (s: T) => S): S { return sel(useSyncExternalStore(inst.subscribe, inst.getSnapshot)) }
  47. }
  48. function mountFrame() {
  49. window.innerWidth = frameWidth // first-render viewport source before the observer fires
  50. const instance = createLayoutStore().create()
  51. const slotCalls: { key: string; props: unknown }[] = []
  52. const renderSlot = ((key: string, owner: object) => {
  53. slotCalls.push({ key, props: owner })
  54. if (key === 'sidebar') return <div data-testid="sidebar-content" />
  55. if (key === 'conversation') return <div data-testid="center-content" />
  56. if (key === 'details') return <div data-testid="details-content" />
  57. if (key === 'conversation.empty') return <div data-testid="empty-content" />
  58. return <div data-testid="other-content" />
  59. }) as AppFrameProps['renderSlot']
  60. const useSessions = ((sel: (s: SessionListState) => unknown) => {
  61. const current = selectedSession.current
  62. const sessionState = {
  63. ids: current === undefined ? [] : [current],
  64. byId: current === undefined
  65. ? {}
  66. : { [current]: { id: current, displayTitle: 'Test', running: false, blank: selectedSessionBlank.current, updatedAt: 1 } },
  67. current,
  68. phase: 'ready',
  69. } as SessionListState
  70. return sel(sessionState)
  71. }) as never
  72. const workspaceState: WorkspaceListState = {
  73. items: [], archivedSessionIds: [], state: 'idle', phase: 'ready', error: null,
  74. baselinesReady: baselinesReady.current, recentWorkspaceId: undefined,
  75. }
  76. const element = () => (
  77. <AppFrame
  78. useStore={hookOf(instance)}
  79. actions={instance.actions}
  80. renderSlot={renderSlot}
  81. useSessions={useSessions}
  82. useWorkspaces={((sel: (s: WorkspaceListState) => unknown) => sel(workspaceState)) as never}
  83. SessionProvider={SessionProviderStub}
  84. />
  85. )
  86. const utils = render(element())
  87. const frame = utils.container.firstElementChild as HTMLElement
  88. return { instance, frame, slotCalls, rerenderFrame: () => { utils.rerender(element()) }, ...utils }
  89. }
  90. function tracks(frame: HTMLElement): number[] {
  91. const m = /^(\d+)px minmax\(0, 1fr\) (\d+)px$/.exec(frame.style.gridTemplateColumns)
  92. if (m === null) throw new Error(`unexpected template: ${frame.style.gridTemplateColumns}`)
  93. return [Number(m[1]), Number(m[2])]
  94. }
  95. function drag(handle: Element, fromX: number, toX: number): void {
  96. const down = new PointerEvent('pointerdown', { pointerId: 1, clientX: fromX, bubbles: true })
  97. const move = new PointerEvent('pointermove', { pointerId: 1, clientX: toX, bubbles: true })
  98. const up = new PointerEvent('pointerup', { pointerId: 1, clientX: toX, bubbles: true })
  99. act(() => { handle.dispatchEvent(down) })
  100. act(() => { handle.dispatchEvent(move); vi.advanceTimersByTime(20) })
  101. act(() => { handle.dispatchEvent(up) })
  102. }
  103. beforeEach(() => {
  104. frameWidth = 1920
  105. selectedSession.current = 's-test' as SessionId
  106. selectedSessionBlank.current = false
  107. baselinesReady.current = true
  108. vi.useFakeTimers()
  109. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  110. vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => setTimeout(() => { cb(0) }, 16) as unknown as number)
  111. vi.stubGlobal('cancelAnimationFrame', (h: number) => { clearTimeout(h) })
  112. window.innerWidth = frameWidth
  113. Element.prototype.getBoundingClientRect = function () {
  114. return { width: frameWidth, height: 1080, top: 0, left: 0, right: frameWidth, bottom: 1080, x: 0, y: 0, toJSON: () => ({}) }
  115. }
  116. // jsdom lacks pointer capture: emulate per-element so hasPointerCapture gates pass.
  117. const captured = new WeakSet<Element>()
  118. Element.prototype.setPointerCapture = function () { captured.add(this) }
  119. Element.prototype.releasePointerCapture = function () { captured.delete(this) }
  120. Element.prototype.hasPointerCapture = function () { return captured.has(this) }
  121. })
  122. afterEach(() => {
  123. cleanup()
  124. vi.useRealTimers()
  125. vi.unstubAllGlobals()
  126. })
  127. describe('AppFrame', () => {
  128. it('renders three tracks from store state', () => {
  129. const { frame } = mountFrame()
  130. expect(tracks(frame)).toEqual([280, 0])
  131. })
  132. it('renders the session pair with empty owner shares (sessionId is framework-standard)', () => {
  133. const { slotCalls, getByTestId } = mountFrame()
  134. expect(getByTestId('center-content')).toBeTruthy()
  135. expect(getByTestId('details-content')).toBeTruthy()
  136. const keys = slotCalls.map(c => c.key)
  137. expect(keys).toContain('conversation')
  138. expect(keys).toContain('details')
  139. expect(keys).not.toContain('conversation.empty')
  140. expect(slotCalls.find(c => c.key === 'conversation')!.props).toEqual({})
  141. expect(slotCalls.find(c => c.key === 'details')!.props).toEqual({})
  142. })
  143. it('keeps the conversation slot mounted while no session is current', () => {
  144. // No current session: the session-maybe conversation shell owns the New
  145. // Session view itself — the center column renders it unconditionally.
  146. selectedSession.current = undefined
  147. const { slotCalls, getByTestId } = mountFrame()
  148. expect(getByTestId('center-content')).toBeTruthy()
  149. expect(slotCalls.map(c => c.key)).toContain('conversation')
  150. })
  151. it('renders both column occupants before baselines settle (no loading gate)', () => {
  152. // User ruling: the bare loading status looked worse than the shell's own
  153. // pending rendering — both occupants mount from first paint.
  154. baselinesReady.current = false
  155. const { slotCalls } = mountFrame()
  156. expect(slotCalls.map(c => c.key)).toContain('conversation')
  157. expect(slotCalls.map(c => c.key)).toContain('details')
  158. })
  159. it('ignores unselected states and closes only when the Session id changes', () => {
  160. const { frame, instance, rerenderFrame } = mountFrame()
  161. expect(tracks(frame)).toEqual([280, 0])
  162. act(() => { instance.actions.openDetails() })
  163. expect(tracks(frame)).toEqual([280, 360])
  164. selectedSession.current = 's-next' as SessionId
  165. act(() => { rerenderFrame() })
  166. expect(tracks(frame)).toEqual([280, 0])
  167. act(() => { instance.actions.openDetails() })
  168. selectedSession.current = 's-blank' as SessionId
  169. selectedSessionBlank.current = true
  170. act(() => { rerenderFrame() })
  171. expect(tracks(frame)).toEqual([280, 0])
  172. expect(instance.getSnapshot().details).toBe(360)
  173. selectedSession.current = 's-next' as SessionId
  174. selectedSessionBlank.current = false
  175. act(() => { rerenderFrame() })
  176. expect(tracks(frame)).toEqual([280, 360])
  177. selectedSession.current = undefined
  178. act(() => { rerenderFrame() })
  179. expect(tracks(frame)).toEqual([280, 0])
  180. selectedSession.current = 's-test' as SessionId
  181. act(() => { rerenderFrame() })
  182. expect(tracks(frame)).toEqual([280, 0])
  183. })
  184. it('keeps details closed when the first Session materializes', () => {
  185. selectedSession.current = undefined
  186. const { frame, instance, rerenderFrame } = mountFrame()
  187. expect(tracks(frame)).toEqual([280, 0])
  188. expect(instance.getSnapshot().details).toBe(0)
  189. selectedSession.current = 's-first' as SessionId
  190. act(() => { rerenderFrame() })
  191. expect(tracks(frame)).toEqual([280, 0])
  192. })
  193. it('sidebar slot receives live concession output as owner props', () => {
  194. const { slotCalls } = mountFrame()
  195. expect(slotCalls.find(c => c.key === 'sidebar')!.props).toEqual({ collapsed: false, width: 280 })
  196. })
  197. it('sidebar drag widens through rAF-batched pointer moves', () => {
  198. const { frame } = mountFrame()
  199. const handles = frame.querySelectorAll('[class*="handle"]')
  200. drag(handles[0]!, 280, 350)
  201. expect(tracks(frame)[0]).toBe(350)
  202. })
  203. it('details drag widens leftward (negative dx grows the panel)', () => {
  204. const { frame, instance } = mountFrame()
  205. act(() => { instance.actions.openDetails() })
  206. const handles = frame.querySelectorAll('[class*="handle"]')
  207. drag(handles[1]!, 1560, 1500)
  208. expect(tracks(frame)[1]).toBe(420)
  209. })
  210. it('drag base is the rendered (concession-clamped) width, not the preference', () => {
  211. frameWidth = 1250 // step-2 squeeze: details renders 330 while preference is 360
  212. const { frame, instance } = mountFrame()
  213. act(() => { instance.actions.openDetails() })
  214. expect(tracks(frame)).toEqual([280, 330])
  215. const handles = frame.querySelectorAll('[class*="handle"]')
  216. drag(handles[1]!, 920, 930) // shrink by 10 from the rendered width
  217. expect(instance.getSnapshot().details).toBe(320)
  218. })
  219. it('details column stays mounted at zero width', () => {
  220. const { frame, getByTestId } = mountFrame()
  221. expect(tracks(frame)).toEqual([280, 0])
  222. expect(getByTestId('details-content')).toBeTruthy()
  223. expect(frame.hasAttribute('data-details-collapsed')).toBe(true)
  224. })
  225. it('closed sidebar keeps its compact rail with mounted slot content and collapsed owner props', () => {
  226. const { frame, instance, slotCalls, getByTestId } = mountFrame()
  227. act(() => { instance.actions.toggleSidebar() })
  228. expect(tracks(frame)).toEqual([SIDEBAR_COLLAPSED, 0])
  229. expect(getByTestId('sidebar-content')).toBeTruthy()
  230. expect(frame.hasAttribute('data-sidebar-collapsed')).toBe(true)
  231. const lastSidebarCall = slotCalls.filter(c => c.key === 'sidebar').at(-1)!
  232. expect(lastSidebarCall.props).toEqual({ collapsed: true, width: SIDEBAR_COLLAPSED })
  233. })
  234. it('viewport shrink triggers the concession chain via ResizeObserver', () => {
  235. const { frame, instance } = mountFrame()
  236. act(() => { instance.actions.openDetails() })
  237. frameWidth = 1250
  238. act(() => { fireResize?.(); vi.advanceTimersByTime(20) })
  239. expect(tracks(frame)).toEqual([280, 330])
  240. frameWidth = 1920
  241. act(() => { fireResize?.(); vi.advanceTimersByTime(20) })
  242. expect(tracks(frame)).toEqual([280, 360])
  243. })
  244. it('drag handles disappear for collapsed columns', () => {
  245. const { frame, instance } = mountFrame()
  246. expect(frame.querySelectorAll('[class*="handle"]')).toHaveLength(1)
  247. act(() => { instance.actions.openDetails() })
  248. expect(frame.querySelectorAll('[class*="handle"]')).toHaveLength(2)
  249. act(() => { instance.actions.closeDetails() })
  250. expect(frame.querySelectorAll('[class*="handle"]')).toHaveLength(1)
  251. act(() => { instance.actions.toggleSidebar() })
  252. expect(frame.querySelectorAll('[class*="handle"]')).toHaveLength(0)
  253. })
  254. })
  255. describe('AppFrame — narrow-viewport auto-collapse', () => {
  256. it('mounts collapsed below the breakpoint with no sidebar handle', () => {
  257. frameWidth = 980
  258. const { frame, slotCalls } = mountFrame()
  259. expect(tracks(frame)).toEqual([SIDEBAR_COLLAPSED, 0])
  260. expect(frame.hasAttribute('data-sidebar-collapsed')).toBe(true)
  261. expect(slotCalls.filter(c => c.key === 'sidebar').at(-1)!.props).toEqual({ collapsed: true, width: SIDEBAR_COLLAPSED })
  262. expect(frame.querySelectorAll('[class*="handle"]')).toHaveLength(0)
  263. })
  264. it('narrow toggle re-expands over the squeezed center and back', () => {
  265. frameWidth = 980
  266. const { frame, instance } = mountFrame()
  267. act(() => { instance.actions.toggleSidebar() })
  268. expect(tracks(frame)).toEqual([280, 0])
  269. expect(frame.hasAttribute('data-sidebar-collapsed')).toBe(false)
  270. expect(frame.querySelectorAll('[class*="handle"]')).toHaveLength(1)
  271. act(() => { instance.actions.toggleSidebar() })
  272. expect(tracks(frame)).toEqual([SIDEBAR_COLLAPSED, 0])
  273. })
  274. it('a wide-closed preference re-expands at the contract default while narrow', () => {
  275. frameWidth = 1920
  276. const { frame, instance } = mountFrame()
  277. act(() => { instance.actions.toggleSidebar() }) // close while wide: preference 0
  278. frameWidth = 980
  279. act(() => { fireResize?.(); vi.advanceTimersByTime(20) })
  280. act(() => { instance.actions.toggleSidebar() })
  281. expect(tracks(frame)).toEqual([280, 0])
  282. expect(instance.getSnapshot().sidebar).toBe(0) // preference untouched
  283. })
  284. it('shrinking across the breakpoint auto-collapses; re-widening restores the drag width', () => {
  285. const { frame, instance } = mountFrame()
  286. act(() => { instance.actions.setSidebar(400) })
  287. frameWidth = 980
  288. act(() => { fireResize?.(); vi.advanceTimersByTime(20) })
  289. expect(tracks(frame)).toEqual([SIDEBAR_COLLAPSED, 0])
  290. frameWidth = 1920
  291. act(() => { fireResize?.(); vi.advanceTimersByTime(20) })
  292. expect(tracks(frame)).toEqual([400, 0])
  293. })
  294. })
  295. describe('AppFrame — guard branches', () => {
  296. it('pointer moves without capture are ignored (no width write)', () => {
  297. const { frame, instance } = mountFrame()
  298. const handle = frame.querySelectorAll('[class*="handle"]')[0]!
  299. const before = instance.getSnapshot().sidebar
  300. // Move + up without a preceding pointerdown: hasPointerCapture is false.
  301. act(() => {
  302. handle.dispatchEvent(new PointerEvent('pointermove', { pointerId: 9, clientX: 500, bubbles: true }))
  303. vi.advanceTimersByTime(20)
  304. handle.dispatchEvent(new PointerEvent('pointerup', { pointerId: 9, clientX: 500, bubbles: true }))
  305. })
  306. expect(instance.getSnapshot().sidebar).toBe(before)
  307. })
  308. it('two moves inside one frame coalesce through the pending rAF', () => {
  309. const { frame, instance } = mountFrame()
  310. const handle = frame.querySelectorAll('[class*="handle"]')[0]!
  311. act(() => { handle.dispatchEvent(new PointerEvent('pointerdown', { pointerId: 1, clientX: 280, bubbles: true })) })
  312. act(() => {
  313. // Two moves before the frame flushes: the second must ride the pending
  314. // rAF (frame.current ??= guard), and the flush sees the latest x.
  315. handle.dispatchEvent(new PointerEvent('pointermove', { pointerId: 1, clientX: 320, bubbles: true }))
  316. handle.dispatchEvent(new PointerEvent('pointermove', { pointerId: 1, clientX: 340, bubbles: true }))
  317. vi.advanceTimersByTime(20)
  318. })
  319. act(() => { handle.dispatchEvent(new PointerEvent('pointerup', { pointerId: 1, clientX: 340, bubbles: true })) })
  320. expect(instance.getSnapshot().sidebar).toBe(340)
  321. })
  322. it('pointerup with a pending rAF cancels it and commits the final position', () => {
  323. const { frame, instance } = mountFrame()
  324. const handle = frame.querySelectorAll('[class*="handle"]')[0]!
  325. act(() => { handle.dispatchEvent(new PointerEvent('pointerdown', { pointerId: 1, clientX: 280, bubbles: true })) })
  326. act(() => {
  327. handle.dispatchEvent(new PointerEvent('pointermove', { pointerId: 1, clientX: 360, bubbles: true }))
  328. // No timer advance: the rAF is still pending when pointerup arrives.
  329. handle.dispatchEvent(new PointerEvent('pointerup', { pointerId: 1, clientX: 360, bubbles: true }))
  330. })
  331. expect(instance.getSnapshot().sidebar).toBe(360)
  332. })
  333. it('zero-width resize reports are ignored (display:none window)', () => {
  334. const { frame } = mountFrame()
  335. frameWidth = 0
  336. act(() => { fireResize?.(); vi.advanceTimersByTime(20) })
  337. // Track template still reflects the last non-zero viewport.
  338. expect(tracks(frame)).toEqual([280, 0])
  339. })
  340. })
  341. describe('AppFrame — unmount with an in-flight resize frame', () => {
  342. it('cancels the pending rAF on unmount (no post-unmount setState)', () => {
  343. const { unmount } = mountFrame()
  344. frameWidth = 800
  345. act(() => { fireResize?.() }) // rAF scheduled, NOT flushed
  346. unmount()
  347. // Flushing after unmount must be a no-op (the frame was cancelled).
  348. expect(() => { vi.advanceTimersByTime(20) }).not.toThrow()
  349. })
  350. it('double resize inside one frame rides the pending rAF (??= guard)', () => {
  351. const { frame, instance } = mountFrame()
  352. act(() => { instance.actions.openDetails() })
  353. frameWidth = 1250
  354. act(() => { fireResize?.(); fireResize?.(); vi.advanceTimersByTime(20) })
  355. expect(tracks(frame)).toEqual([280, 330])
  356. })
  357. })