diff-block.client.spec.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // @vitest-environment jsdom
  2. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  3. import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
  4. import { DEFAULT_DIFF_MAX_LINES, DiffBlock, type DiffHunk } from '../src/index.ts'
  5. afterEach(cleanup)
  6. beforeEach(() => {
  7. vi.useRealTimers()
  8. })
  9. function bodyRows(container: HTMLElement): string[] {
  10. return [...container.querySelectorAll('[class*="_line_"]')].map(row => row.textContent ?? '')
  11. }
  12. function changeRows(container: HTMLElement): string[] {
  13. return [...container.querySelectorAll('[class*="_del_"], [class*="_add_"]')].map(row => row.textContent ?? '')
  14. }
  15. function added(count: number): string {
  16. return Array.from({ length: count }, (_v, i) => `line ${i + 1}`).join('\n')
  17. }
  18. describe('DiffBlock structure', () => {
  19. it('renders a create as a path header and an added block (no removed side)', () => {
  20. const diffs: DiffHunk[] = [{ path: 'notes/new.txt', oldText: null, newText: 'hello\nworld' }]
  21. const { container } = render(<DiffBlock diffs={diffs} />)
  22. expect(screen.getByText('notes/new.txt')).toBeTruthy()
  23. // No removed rows: both change lines are added.
  24. expect(changeRows(container)).toEqual(['hello', 'world'])
  25. expect(container.querySelectorAll('[class*="_del_"]').length).toBe(0)
  26. expect(container.querySelectorAll('[class*="_add_"]').length).toBe(2)
  27. })
  28. it('renders an edit as a removed block above an added block', () => {
  29. const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: 'old', newText: 'new' }]
  30. const { container } = render(<DiffBlock diffs={diffs} />)
  31. expect(container.querySelectorAll('[class*="_del_"]').length).toBe(1)
  32. expect(container.querySelectorAll('[class*="_add_"]').length).toBe(1)
  33. expect(changeRows(container)).toEqual(['old', 'new'])
  34. })
  35. it('opens a same-file second hunk with a gap instead of repeating the path', () => {
  36. const diffs: DiffHunk[] = [
  37. { path: 'a.ts', oldText: 'x', newText: 'y' },
  38. { path: 'a.ts', oldText: 'p', newText: 'q' },
  39. ]
  40. const { container } = render(<DiffBlock diffs={diffs} />)
  41. // One path header, one gap row.
  42. expect(container.querySelectorAll('[class*="_path_"]').length).toBe(1)
  43. expect(container.querySelectorAll('[class*="_gap_"]').length).toBe(1)
  44. })
  45. it('opens a new file with its own path header', () => {
  46. const diffs: DiffHunk[] = [
  47. { path: 'a.ts', oldText: 'x', newText: 'y' },
  48. { path: 'b.ts', oldText: 'p', newText: 'q' },
  49. ]
  50. const { container } = render(<DiffBlock diffs={diffs} />)
  51. expect(container.querySelectorAll('[class*="_path_"]').length).toBe(2)
  52. expect(container.querySelectorAll('[class*="_gap_"]').length).toBe(0)
  53. })
  54. it('renders nothing for empty diffs', () => {
  55. const { container } = render(<DiffBlock diffs={[]} />)
  56. expect(container.firstChild).toBeNull()
  57. })
  58. it('treats a trailing newline as a terminator, not an extra blank line', () => {
  59. // A create whose newText ends in a newline is one added line, not two, and
  60. // the footer counts one — the phantom `+ ` empty line the naive split drew.
  61. const { container } = render(<DiffBlock diffs={[{ path: 'n.txt', oldText: null, newText: 'hello\n' }]} />)
  62. expect(changeRows(container)).toEqual(['hello'])
  63. expect(screen.getByText('└ +1 -0 · 1 file')).toBeTruthy()
  64. })
  65. it('renders a full deletion as removed-only with no phantom added line', () => {
  66. // newText '' is zero added lines: an empty string must contribute nothing.
  67. const { container } = render(<DiffBlock diffs={[{ path: 'gone.ts', oldText: 'a\nb', newText: '' }]} />)
  68. expect(container.querySelectorAll('[class*="_add_"]').length).toBe(0)
  69. expect(screen.getByText('└ +0 -2 · 1 file')).toBeTruthy()
  70. })
  71. it('keeps a genuine interior blank line', () => {
  72. const { container } = render(<DiffBlock diffs={[{ path: 'a.ts', oldText: null, newText: 'x\n\ny' }]} />)
  73. expect(container.querySelectorAll('[class*="_add_"]').length).toBe(3)
  74. })
  75. })
  76. describe('DiffBlock footer', () => {
  77. it('counts added and removed lines and one file', () => {
  78. const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: 'a\nb', newText: 'c' }]
  79. render(<DiffBlock diffs={diffs} />)
  80. expect(screen.getByText('└ +1 -2 · 1 file')).toBeTruthy()
  81. })
  82. it('pluralizes the distinct-file count', () => {
  83. const diffs: DiffHunk[] = [
  84. { path: 'a.ts', oldText: null, newText: 'x' },
  85. { path: 'b.ts', oldText: null, newText: 'y' },
  86. ]
  87. render(<DiffBlock diffs={diffs} />)
  88. expect(screen.getByText('└ +2 -0 · 2 files')).toBeTruthy()
  89. })
  90. })
  91. describe('DiffBlock height cap', () => {
  92. it('shows head and tail with an expand control past the cap, then all lines expanded', () => {
  93. // One added line over the default cap forces the collapse.
  94. const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: null, newText: added(DEFAULT_DIFF_MAX_LINES) }]
  95. // The path header counts as a row, so a body of maxLines added lines plus
  96. // the header is one over the cap.
  97. const { container } = render(<DiffBlock diffs={diffs} />)
  98. const toggle = screen.getByRole('button', { name: /展开其余/ })
  99. expect(toggle.getAttribute('aria-expanded')).toBe('false')
  100. // Collapsed shows fewer rows than the full body.
  101. const collapsedCount = bodyRows(container).length
  102. expect(collapsedCount).toBeLessThan(DEFAULT_DIFF_MAX_LINES + 1)
  103. fireEvent.click(toggle)
  104. expect(screen.getByRole('button', { name: '收起差异' }).getAttribute('aria-expanded')).toBe('true')
  105. expect(bodyRows(container).length).toBeGreaterThan(collapsedCount)
  106. })
  107. it('shows no expand control at or under the cap', () => {
  108. const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: null, newText: added(4) }]
  109. render(<DiffBlock diffs={diffs} maxLines={16} />)
  110. expect(screen.queryByRole('button', { name: /展开其余|收起差异/ })).toBeNull()
  111. })
  112. })
  113. describe('DiffBlock copy', () => {
  114. it('copies the prefixed diff text and flips the label on success', async () => {
  115. vi.useFakeTimers()
  116. const writeText = vi.fn().mockResolvedValue(undefined)
  117. Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
  118. const diffs: DiffHunk[] = [
  119. { path: 'a.ts', oldText: 'old', newText: 'new' },
  120. { path: 'a.ts', oldText: 'p', newText: 'q' },
  121. ]
  122. render(<DiffBlock diffs={diffs} />)
  123. const copy = screen.getByRole('button', { name: '复制' })
  124. await act(async () => { fireEvent.click(copy) })
  125. // Path header, del/add prefixes, and the same-file gap all reach the clipboard.
  126. expect(writeText).toHaveBeenCalledWith('a.ts\n- old\n+ new\n⋯\n- p\n+ q')
  127. expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
  128. await act(async () => { await vi.advanceTimersByTimeAsync(1000) })
  129. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  130. })
  131. it('keeps the label on a refused clipboard write', async () => {
  132. Object.defineProperty(navigator, 'clipboard', {
  133. configurable: true,
  134. value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },
  135. })
  136. render(<DiffBlock diffs={[{ path: 'a.ts', oldText: null, newText: 'x' }]} />)
  137. const copy = screen.getByRole('button', { name: '复制' })
  138. await act(async () => { fireEvent.click(copy) })
  139. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  140. })
  141. it('ignores a second click while the copied label is showing', async () => {
  142. vi.useFakeTimers()
  143. const writeText = vi.fn().mockResolvedValue(undefined)
  144. Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
  145. render(<DiffBlock diffs={[{ path: 'a.ts', oldText: null, newText: 'x' }]} />)
  146. const copy = screen.getByRole('button', { name: '复制' })
  147. await act(async () => { fireEvent.click(copy) })
  148. await act(async () => { fireEvent.click(screen.getByRole('button', { name: '复制成功' })) })
  149. expect(writeText).toHaveBeenCalledTimes(1)
  150. })
  151. })