json-tree.client.spec.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. // @vitest-environment jsdom
  2. import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
  3. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  4. import type { ComponentProps } from 'react'
  5. import { JsonTree as LocalizedJsonTree } from '@deepseek-ai/dsh-client-ui-primitives'
  6. import { jsonTreeLabels } from './labels.client.ts'
  7. function JsonTree(props: Omit<ComponentProps<typeof LocalizedJsonTree>, 'label' | 'labels'> & {
  8. label?: string
  9. }) {
  10. return <LocalizedJsonTree label="JSON" {...props} labels={jsonTreeLabels} />
  11. }
  12. let writeText: ReturnType<typeof vi.fn<Clipboard['writeText']>>
  13. let originalClipboard: PropertyDescriptor | undefined
  14. beforeEach(() => {
  15. originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
  16. writeText = vi.fn<Clipboard['writeText']>().mockResolvedValue(undefined)
  17. Object.defineProperty(navigator, 'clipboard', {
  18. configurable: true,
  19. value: { writeText },
  20. })
  21. })
  22. afterEach(() => {
  23. cleanup()
  24. vi.useRealTimers()
  25. vi.restoreAllMocks()
  26. vi.unstubAllGlobals()
  27. if (originalClipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard')
  28. else Object.defineProperty(navigator, 'clipboard', originalClipboard)
  29. })
  30. function stubStringLayout(scrollHeight = 200): void {
  31. vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(scrollHeight)
  32. const computedStyle = window.getComputedStyle.bind(window)
  33. vi.spyOn(window, 'getComputedStyle').mockImplementation((element) => {
  34. const style = computedStyle(element)
  35. style.lineHeight = '16px'
  36. if (style.paddingBottom === '') style.paddingBottom = '0px'
  37. return style
  38. })
  39. }
  40. describe('JsonTree', () => {
  41. it('ignores clipboard settlement after the row changes or the tree unmounts', async () => {
  42. vi.useFakeTimers()
  43. const pending: (() => void)[] = []
  44. writeText.mockImplementation(() => new Promise<void>((resolve) => { pending.push(resolve) }))
  45. const view = render(<JsonTree data={{ first: 1, second: 2 }} />)
  46. const rows = screen.getAllByRole('treeitem')
  47. fireEvent.mouseOver(rows[0] as HTMLElement)
  48. fireEvent.click(screen.getByRole('button', { name: 'Copy value' }))
  49. fireEvent.mouseOver(rows[1] as HTMLElement)
  50. await act(async () => { pending[0]!() })
  51. expect(screen.queryByRole('button', { name: 'Copied' })).toBeNull()
  52. fireEvent.click(screen.getByRole('button', { name: 'Copy value' }))
  53. view.unmount()
  54. const timerCount = vi.getTimerCount()
  55. await act(async () => { pending[1]!() })
  56. expect(vi.getTimerCount()).toBe(timerCount)
  57. })
  58. it('updates copy actions without rereading JSON properties on hover', () => {
  59. const readValue = vi.fn(() => 'payload '.repeat(100))
  60. const data = Object.fromEntries(Array.from({ length: 500 }, (_, index) => [
  61. `field${index}`,
  62. { get value() { return readValue() } },
  63. ]))
  64. render(<JsonTree data={data} />)
  65. const rows = within(screen.getByRole('tree')).getAllByRole('treeitem')
  66. readValue.mockClear()
  67. fireEvent.mouseOver(rows[0] as HTMLElement)
  68. expect(within(rows[0] as HTMLElement).getByRole('button', { name: 'Copy pretty JSON' })).toBeTruthy()
  69. fireEvent.mouseOver(rows[1] as HTMLElement)
  70. expect(within(rows[0] as HTMLElement).queryByRole('button', { name: 'Copy pretty JSON' })).toBeNull()
  71. expect(within(rows[1] as HTMLElement).getByRole('button', { name: 'Copy pretty JSON' })).toBeTruthy()
  72. expect(readValue).not.toHaveBeenCalled()
  73. })
  74. it('expands raw strings without ResizeObserver and keeps the visible viewport limit', () => {
  75. stubStringLayout()
  76. vi.stubGlobal('ResizeObserver', undefined)
  77. let rawTop = 150
  78. const view = render(
  79. <div style={{ overflowY: 'auto', paddingBottom: '10px' }}>
  80. <JsonTree data={{ first: 'raw\ntext', last: 'last\ntext' }} />
  81. </div>,
  82. )
  83. const clip = view.container.firstElementChild as HTMLElement
  84. vi.spyOn(clip, 'clientTop', 'get').mockReturnValue(2)
  85. vi.spyOn(clip, 'clientHeight', 'get').mockReturnValue(140)
  86. vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
  87. return new DOMRect(0, this === clip ? 100 : rawTop, 200, 140)
  88. })
  89. const rows = within(screen.getByRole('tree')).getAllByRole('treeitem')
  90. fireEvent.click(within(rows[0] as HTMLElement).getByRole('button', { name: 'Expand JSON node' }))
  91. const raw = rows[0]?.querySelector('pre') as HTMLPreElement
  92. expect(raw.textContent).toBe('raw\ntext')
  93. expect(raw.style.maxHeight).toBe('78px')
  94. expect(raw.nextElementSibling?.textContent).toBe(',')
  95. rawTop = 80
  96. fireEvent.scroll(clip)
  97. expect(raw.style.maxHeight).toBe('126px')
  98. rawTop = 300
  99. fireEvent.resize(window)
  100. expect(raw.style.maxHeight).toBe('16px')
  101. fireEvent.click(within(rows[0] as HTMLElement).getByRole('button', { name: 'Collapse JSON node' }))
  102. expect(raw.isConnected).toBe(false)
  103. rawTop = 100
  104. fireEvent.scroll(clip)
  105. expect(raw.style.maxHeight).toBe('16px')
  106. fireEvent.click(within(rows[1] as HTMLElement).getByRole('button', { name: 'Expand JSON node' }))
  107. expect(rows[1]?.querySelector('pre')?.nextElementSibling?.textContent).not.toBe(',')
  108. })
  109. it('shows the string expander only beyond the configured collapsed line count', () => {
  110. stubStringLayout(48)
  111. let resize: (() => void) | undefined
  112. const disconnect = vi.fn()
  113. vi.stubGlobal('ResizeObserver', class {
  114. constructor(callback: () => void) { resize = callback }
  115. observe() {}
  116. disconnect = disconnect
  117. })
  118. const data = { text: 'three lines of text' }
  119. const view = render(<JsonTree data={data} />)
  120. expect(screen.queryByRole('button', { name: 'Expand JSON node' })).toBeNull()
  121. view.rerender(<JsonTree data={data} collapsedStringLines={2} />)
  122. expect(screen.getByRole('button', { name: 'Expand JSON node' })).toBeTruthy()
  123. vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(16)
  124. act(() => { resize?.() })
  125. expect(screen.queryByRole('button', { name: 'Expand JSON node' })).toBeNull()
  126. view.unmount()
  127. expect(disconnect).toHaveBeenCalledTimes(2)
  128. })
  129. it('keeps raw strings intact and samples the wrapping preference on every expansion', async () => {
  130. stubStringLayout()
  131. vi.stubGlobal('ResizeObserver', class {
  132. observe() {}
  133. disconnect() {}
  134. })
  135. let wrapped = false
  136. const stringWrapping = {
  137. label: 'Wrap lines',
  138. getDefault: () => wrapped,
  139. setDefault: (value: boolean) => { wrapped = value },
  140. }
  141. const original = ` leading spaces\n\t"quoted" \\${'long'.repeat(100)}\nlast line\n`
  142. render(<JsonTree data={{ first: original, second: original }} stringWrapping={stringWrapping} />)
  143. const [first, second] = within(screen.getByRole('tree')).getAllByRole('treeitem')
  144. const a = within(first as HTMLElement)
  145. const b = within(second as HTMLElement)
  146. fireEvent.click(a.getByRole('button', { name: 'Expand JSON node' }))
  147. fireEvent.click(b.getByRole('button', { name: 'Expand JSON node' }))
  148. expect(a.getByRole('button', { name: 'Wrap lines' }).getAttribute('aria-pressed')).toBe('false')
  149. fireEvent.click(a.getByRole('button', { name: 'Wrap lines' }))
  150. expect(wrapped).toBe(true)
  151. expect(a.getByRole('button', { name: 'Wrap lines' }).getAttribute('aria-pressed')).toBe('true')
  152. expect(b.getByRole('button', { name: 'Wrap lines' }).getAttribute('aria-pressed')).toBe('false')
  153. fireEvent.click(b.getByRole('button', { name: 'Collapse JSON node' }))
  154. fireEvent.click(b.getByRole('button', { name: 'Expand JSON node' }))
  155. expect(b.getByRole('button', { name: 'Wrap lines' }).getAttribute('aria-pressed')).toBe('true')
  156. fireEvent.click(b.getByRole('button', { name: 'Wrap lines' }))
  157. expect(wrapped).toBe(false)
  158. expect(a.getByRole('button', { name: 'Wrap lines' }).getAttribute('aria-pressed')).toBe('true')
  159. fireEvent.click(a.getByRole('button', { name: 'Collapse JSON node' }))
  160. fireEvent.click(a.getByRole('button', { name: 'Expand JSON node' }))
  161. const toggle = a.getByRole('button', { name: 'Wrap lines' })
  162. expect(toggle.getAttribute('aria-pressed')).toBe('false')
  163. const contents = document.getElementById(toggle.getAttribute('aria-controls') as string)
  164. expect(contents?.textContent).toBe(original)
  165. fireEvent.click(a.getByRole('button', { name: 'Copy value' }))
  166. await waitFor(() => { expect(writeText).toHaveBeenCalledWith(original) })
  167. })
  168. it('keeps the top level open and renders expandable value previews', () => {
  169. render(
  170. <JsonTree
  171. label="Payload"
  172. data={{
  173. nested: { answer: 42 },
  174. list: ['alpha', 'beta'],
  175. }}
  176. />,
  177. )
  178. const tree = screen.getByRole('tree', { name: 'Payload' })
  179. const rows = within(tree).getAllByRole('treeitem')
  180. expect(rows).toHaveLength(2)
  181. expect(rows[0]?.textContent).toBe('nested:{answer: 42},')
  182. expect(rows[1]?.textContent).toBe('list:["alpha", "beta"]')
  183. const expanders = within(tree).getAllByRole('button', { name: 'Expand JSON node' })
  184. expect(expanders[0]?.tabIndex).toBe(0)
  185. expect(expanders[1]?.tabIndex).toBe(-1)
  186. fireEvent.click(expanders[0] as HTMLElement)
  187. expect(within(tree).getAllByRole('treeitem')).toHaveLength(3)
  188. expect(screen.getByText('answer:')).toBeDefined()
  189. expect(within(tree).getByRole('button', { name: 'Collapse JSON node' })).toBeDefined()
  190. })
  191. it('moves the single tab stop between visible expanders with arrow keys', () => {
  192. render(
  193. <JsonTree
  194. expandTopLevel={false}
  195. data={{
  196. first: { nested: 1 },
  197. second: { nested: 2 },
  198. }}
  199. />,
  200. )
  201. const tree = screen.getByRole('tree', { name: 'JSON' })
  202. const root = within(tree).getByRole('button', { name: 'Collapse JSON node' })
  203. const children = within(tree).getAllByRole('button', { name: 'Expand JSON node' })
  204. expect(root.tabIndex).toBe(0)
  205. fireEvent.keyDown(root, { key: 'ArrowDown' })
  206. expect(document.activeElement).toBe(children[0])
  207. expect(root.tabIndex).toBe(-1)
  208. expect(children[0]?.tabIndex).toBe(0)
  209. fireEvent.keyDown(children[0] as HTMLElement, { key: 'ArrowRight' })
  210. expect(children[0]?.getAttribute('aria-expanded')).toBe('true')
  211. fireEvent.keyDown(children[0] as HTMLElement, { key: 'ArrowLeft' })
  212. expect(children[0]?.getAttribute('aria-expanded')).toBe('false')
  213. fireEvent.keyDown(children[0] as HTMLElement, { key: 'Enter' })
  214. fireEvent.keyDown(children[0] as HTMLElement, { key: 'ArrowUp' })
  215. expect(document.activeElement).toBe(root)
  216. fireEvent.keyDown(root, { key: 'ArrowUp' })
  217. expect(document.activeElement).toBe(children[1])
  218. })
  219. it('copies an array element path without recovering data from rendered labels', async () => {
  220. render(<JsonTree data={{ list: [{ value: 'x' }, 'tail'] }} />)
  221. const tree = screen.getByRole('tree')
  222. fireEvent.click(within(tree).getByRole('button', { name: 'Expand JSON node' }))
  223. const arrayRow = within(tree).getAllByRole('treeitem')
  224. .find(row => row.textContent?.startsWith('0:'))
  225. expect(arrayRow).toBeDefined()
  226. fireEvent.mouseOver(arrayRow as HTMLElement)
  227. const copyButton = screen.getByRole('button', { name: 'Copy pretty JSON' })
  228. fireEvent.contextMenu(copyButton)
  229. fireEvent.click(screen.getByRole('menuitem', { name: 'Copy property path' }))
  230. await waitFor(() => {
  231. expect(writeText).toHaveBeenCalledWith('$.list[0]')
  232. })
  233. })
  234. it('renders empty containers, JSON-adjacent primitives, and bounded deep previews', () => {
  235. const anonymous = Object.defineProperty(() => {}, 'name', { value: '' })
  236. const date = new Date('2026-07-28T00:00:00.000Z')
  237. const data = {
  238. '': 'empty key',
  239. nil: null,
  240. text: 'quoted',
  241. flag: true,
  242. count: 3,
  243. big: 4n,
  244. date,
  245. named: function named() {},
  246. missing: undefined,
  247. symbol: Symbol('token'),
  248. emptyObject: {},
  249. emptyArray: [],
  250. primitivePreview: {
  251. nil: null,
  252. flag: false,
  253. big: 9n,
  254. missing: undefined,
  255. },
  256. exoticPreview: {
  257. symbol: Symbol(),
  258. named: function sample() {},
  259. anonymous,
  260. date,
  261. },
  262. wideObject: { a: 1, b: 2, c: 3, d: 4, e: 5 },
  263. wideArray: [1, 2, 3, 4, 5, 6],
  264. deep: { a: { b: { c: 1 } } },
  265. }
  266. render(<JsonTree copyable={false} data={data} />)
  267. const text = screen.getByRole('tree').textContent
  268. expect(text).toContain('"":\"empty key\"')
  269. expect(text).toContain('nil:null')
  270. expect(text).toContain('flag:true')
  271. expect(text).toContain('count:3')
  272. expect(text).toContain('big:4n')
  273. expect(text).toContain('date:2026-07-28T00:00:00.000Z')
  274. expect(text).toContain('named:function() { }')
  275. expect(text).toContain('missing:undefined')
  276. expect(text).toContain('symbol:Symbol(token)')
  277. expect(text).toContain('emptyObject:{}')
  278. expect(text).toContain('emptyArray:[]')
  279. expect(text).toContain('primitivePreview:{nil: null, flag: false, big: 9, missing: undefined}')
  280. expect(text).toContain('exoticPreview:{symbol: Symbol, named: sample, anonymous: Function, date: }')
  281. expect(text).toContain('wideObject:{a: 1, b: 2, c: 3, d: 4, …}')
  282. expect(text).toContain('wideArray:[1, 2, 3, 4, 5, …]')
  283. expect(text).toContain('deep:{a: {b: {…}}}')
  284. expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
  285. fireEvent.mouseOver(screen.getByRole('tree').parentElement as HTMLElement)
  286. })
  287. it('renders child commas and lets a clickable property label toggle its node', () => {
  288. render(<JsonTree data={{ parent: { emptyObject: {}, emptyArray: [], scalar: 1, last: 2 } }} />)
  289. fireEvent.click(screen.getByText('parent:'))
  290. const tree = screen.getByRole('tree')
  291. const rows = within(tree).getAllByRole('treeitem')
  292. expect(rows.find(row => row.textContent === 'emptyObject:{},')).toBeDefined()
  293. expect(rows.find(row => row.textContent === 'emptyArray:[],')).toBeDefined()
  294. expect(rows.find(row => row.textContent === 'scalar:1,')).toBeDefined()
  295. expect(rows.find(row => row.textContent === 'last:2')).toBeDefined()
  296. fireEvent.click(screen.getByText('parent:'))
  297. expect(within(tree).getAllByRole('treeitem')).toHaveLength(1)
  298. })
  299. it('assigns the initial array tab stop and supports an empty collapsible root', () => {
  300. const first = render(<JsonTree data={['plain', { nested: true }]} />)
  301. const tree = screen.getByRole('tree')
  302. expect(tree.textContent).toContain('0:"plain"')
  303. expect(within(tree).getByRole('button', { name: 'Expand JSON node' }).tabIndex).toBe(0)
  304. first.unmount()
  305. render(<JsonTree expandTopLevel={false} data={{}} />)
  306. expect(screen.getByRole('tree').textContent).toBe('{}')
  307. expect(screen.queryByRole('button', { name: /JSON node/ })).toBeNull()
  308. })
  309. it('copies primitive and object values in every menu mode', async () => {
  310. const anonymous = Object.defineProperty(() => {}, 'name', { value: '' })
  311. render(
  312. <JsonTree
  313. data={{
  314. plain: 'hello',
  315. 'odd-key': 3,
  316. object: { a: 1 },
  317. missing: undefined,
  318. big: 7n,
  319. symbol: Symbol(),
  320. symbolNamed: Symbol('token'),
  321. named: function named() {},
  322. anonymous,
  323. }}
  324. />,
  325. )
  326. const tree = screen.getByRole('tree')
  327. const row = (prefix: string) => {
  328. const match = within(tree).getAllByRole('treeitem')
  329. .find(item => item.textContent?.startsWith(prefix))
  330. expect(match).toBeDefined()
  331. return match as HTMLElement
  332. }
  333. const hover = (prefix: string) => {
  334. fireEvent.mouseOver(row(prefix))
  335. return screen.getByRole('button', { name: /Cop/ })
  336. }
  337. const select = (name: string) => {
  338. const button = screen.getByRole('button', { name: /Cop/ })
  339. fireEvent.contextMenu(button)
  340. fireEvent.click(screen.getByRole('menuitem', { name }))
  341. }
  342. fireEvent.click(hover('plain:'))
  343. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('hello') })
  344. hover('odd-key:')
  345. select('Copy property path')
  346. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('$["odd-key"]') })
  347. select('Copy JSON')
  348. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('3') })
  349. fireEvent.click(hover('odd-key:'))
  350. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('3') })
  351. fireEvent.click(hover('object:'))
  352. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('{\n "a": 1\n}') })
  353. select('Copy compact JSON')
  354. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('{"a":1}') })
  355. for (const [prefix, expected] of [
  356. ['missing:', 'undefined'],
  357. ['big:', '7'],
  358. ['symbol:', 'Symbol'],
  359. ['symbolNamed:', 'token'],
  360. ['named:', 'named'],
  361. ['anonymous:', 'Function'],
  362. ] as const) {
  363. fireEvent.click(hover(prefix))
  364. await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith(expected) })
  365. }
  366. })
  367. it('reports clipboard failure, resets feedback, and clears a prior timer', async () => {
  368. vi.useFakeTimers()
  369. writeText.mockRejectedValue(new Error('denied'))
  370. const view = render(<JsonTree data={{ value: 'x' }} />)
  371. const row = screen.getByRole('treeitem')
  372. fireEvent.mouseOver(row)
  373. fireEvent.click(screen.getByRole('button', { name: 'Copy value' }))
  374. await act(async () => { await Promise.resolve() })
  375. expect(screen.getByRole('button', { name: 'Copy failed' })).toBeDefined()
  376. fireEvent.click(screen.getByRole('button', { name: 'Copy failed' }))
  377. await act(async () => { await Promise.resolve() })
  378. act(() => { vi.advanceTimersByTime(1_500) })
  379. expect(screen.getByRole('button', { name: 'Copy value' })).toBeDefined()
  380. view.unmount()
  381. })
  382. it('keeps the copy action on its hovered row and clears stale targets', () => {
  383. const view = render(<JsonTree data={{ first: { a: 1 }, second: 2 }} />)
  384. const root = view.container.firstElementChild as HTMLElement
  385. const tree = screen.getByRole('tree')
  386. const firstRow = within(tree).getAllByRole('treeitem')[0] as HTMLElement
  387. const secondRow = within(tree).getAllByRole('treeitem')[1] as HTMLElement
  388. fireEvent.mouseOver(firstRow)
  389. const copyButton = screen.getByRole('button', { name: 'Copy pretty JSON' })
  390. expect(firstRow.contains(copyButton)).toBe(true)
  391. fireEvent.mouseOver(copyButton)
  392. expect(screen.getByRole('button', { name: 'Copy pretty JSON' })).toBeDefined()
  393. fireEvent.mouseOver(firstRow)
  394. fireEvent.scroll(root)
  395. fireEvent.contextMenu(copyButton)
  396. fireEvent.mouseOver(secondRow)
  397. fireEvent.mouseOver(root)
  398. fireEvent.mouseLeave(root)
  399. expect(screen.getByRole('menu')).toBeDefined()
  400. fireEvent.keyDown(document, { key: 'Escape' })
  401. expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
  402. fireEvent.mouseOver(secondRow)
  403. expect(screen.getByRole('button', { name: 'Copy value' })).toBeDefined()
  404. fireEvent.mouseOver(root)
  405. expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
  406. fireEvent.scroll(root)
  407. view.rerender(<JsonTree data={{ replacement: 3 }} />)
  408. expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
  409. })
  410. it('copies the fixed root and clears it when the pointer leaves', async () => {
  411. const view = render(<JsonTree data={{ value: 1 }} />)
  412. const root = view.container.firstElementChild as HTMLElement
  413. const openingBracket = root.querySelector<HTMLElement>('[data-json-root-row]')
  414. expect(openingBracket).not.toBeNull()
  415. fireEvent.mouseOver(openingBracket as HTMLElement)
  416. fireEvent.click(screen.getByRole('button', { name: 'Copy pretty JSON' }))
  417. await waitFor(() => { expect(writeText).toHaveBeenCalledWith('{\n "value": 1\n}') })
  418. fireEvent.mouseLeave(root)
  419. expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
  420. })
  421. })