code-block.client.spec.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 type { ComponentProps } from 'react'
  5. import { CodeBlock as LocalizedCodeBlock } from '../src/markdown/CodeBlock.tsx'
  6. import { highlightToHtml, subscribeGrammarLoaded } from '../src/markdown/highlight.ts'
  7. import { markdownLabels } from './labels.client.ts'
  8. function CodeBlock(props: Omit<ComponentProps<typeof LocalizedCodeBlock>, 'copyLabel' | 'copiedLabel'>) {
  9. return <LocalizedCodeBlock {...props} {...markdownLabels.code} />
  10. }
  11. afterEach(cleanup)
  12. beforeEach(() => {
  13. vi.useRealTimers()
  14. })
  15. describe('highlightToHtml', () => {
  16. it('highlights a registered grammar into css-variables token spans', () => {
  17. const html = highlightToHtml('const x: number = 1', 'typescript')
  18. expect(html).toContain('pre class="shiki css-variables"')
  19. expect(html).toContain('var(--shiki-')
  20. })
  21. it.each([['ts'], ['js'], ['bash'], ['sh'], ['jsonc']])('resolves the %s alias', (alias) => {
  22. expect(highlightToHtml('x', alias)).toContain('shiki')
  23. })
  24. it('returns undefined for unknown or absent languages', () => {
  25. expect(highlightToHtml('x', 'cobol')).toBeUndefined()
  26. expect(highlightToHtml('x', undefined)).toBeUndefined()
  27. })
  28. // Every read-tool language hint whose grammar loads lazily (the boot set —
  29. // ts/js/shell/sh/json — is covered above). Touching each one drives its own
  30. // dynamic import thunk, so the whole LAZY_GRAMMARS table is exercised.
  31. const LAZY_ALIASES = [
  32. 'py', 'rb', 'go', 'rs', 'java', 'c', 'cpp', 'cs', 'kotlin', 'swift', 'php',
  33. 'yaml', 'toml', 'ini', 'md', 'mdx', 'html', 'css', 'scss', 'less', 'sql',
  34. 'xml', 'lua',
  35. ]
  36. it('lazily loads every read-card grammar: plain first, highlighted after load', async () => {
  37. const registered = Promise.withResolvers<undefined>()
  38. // Registration notifications, not a private polling deadline, establish readiness.
  39. const stop = subscribeGrammarLoaded(() => {
  40. if (LAZY_ALIASES.every(alias => highlightToHtml('x', alias) !== undefined)) registered.resolve(undefined)
  41. })
  42. try {
  43. for (const alias of LAZY_ALIASES) expect(highlightToHtml('x', alias), alias).toBeUndefined()
  44. await registered.promise
  45. for (const alias of LAZY_ALIASES) expect(highlightToHtml('x', alias), alias).toContain('shiki')
  46. } finally {
  47. stop()
  48. }
  49. })
  50. })
  51. describe('CodeBlock', () => {
  52. it('renders the highlighted tree for TypeScript', () => {
  53. const view = render(<CodeBlock code={'const a = 1\n'} lang="ts" />)
  54. const pre = view.container.querySelector('pre.shiki')
  55. expect(pre).not.toBeNull()
  56. expect(pre!.textContent).toBe('const a = 1')
  57. expect(pre!.querySelectorAll('span[style]').length).toBeGreaterThan(1)
  58. expect(view.container.querySelector('[data-line-numbers]')).toBeNull()
  59. })
  60. it.each(['ts', 'unregistered'])('numbers %s source lines without copying the gutter', async (lang) => {
  61. const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
  62. const writeText = vi.fn().mockResolvedValue(undefined)
  63. vi.useFakeTimers()
  64. try {
  65. Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
  66. const code = 'const first = 1\n\nconst last = 3'
  67. const view = render(<CodeBlock code={`${code}\n`} lang={lang} lineNumbers />)
  68. expect(view.container.querySelector('[data-line-numbers]')).not.toBeNull()
  69. expect([...view.container.querySelectorAll('code > .line')].map(line => line.textContent))
  70. .toEqual(['const first = 1', '', 'const last = 3'])
  71. expect(view.container.querySelector('pre')!.textContent).toBe(code)
  72. await act(async () => { fireEvent.click(view.getByRole('button', { name: '复制' })) })
  73. expect(writeText).toHaveBeenCalledWith(code)
  74. await act(async () => { await vi.runOnlyPendingTimersAsync() })
  75. } finally {
  76. cleanup()
  77. vi.useRealTimers()
  78. if (clipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard')
  79. else Object.defineProperty(navigator, 'clipboard', clipboard)
  80. }
  81. })
  82. it('keeps an empty numbered line and widens the gutter as streaming content grows', () => {
  83. const view = render(<CodeBlock code="" lineNumbers />)
  84. expect(view.container.querySelectorAll('code > .line')).toHaveLength(1)
  85. expect(view.container.querySelector('pre')!.textContent).toBe('')
  86. const gutter = () => view.container.querySelector<HTMLElement>('[data-line-numbers]')!
  87. .style.getPropertyValue('--dsl-code-block-line-number-width')
  88. expect(gutter()).toBe('2ch')
  89. view.rerender(<CodeBlock code="const first = 1" lang="ts" streaming lineNumbers />)
  90. const code = ['const first = 1', ...Array.from({ length: 99 }, (_, index) => `const line${index} = 0`)].join('\n')
  91. view.rerender(<CodeBlock code={code} lang="ts" streaming lineNumbers />)
  92. expect(view.container.querySelectorAll('code > .line')).toHaveLength(100)
  93. const firstLine = view.container.querySelector('code > .line')
  94. expect(view.container.querySelector('pre')!.textContent).toBe(code)
  95. expect(gutter()).toBe('3ch')
  96. view.rerender(<CodeBlock code={code} lang="ts" lineNumbers />)
  97. expect(view.container.querySelector('code > .line')).toBe(firstLine)
  98. expect(gutter()).toBe('3ch')
  99. })
  100. it('renders the plain arm for an unknown language with the text verbatim', () => {
  101. const view = render(<CodeBlock code={'IDENTIFICATION DIVISION.'} lang="cobol" />)
  102. expect(view.container.querySelector('pre.shiki')).toBeNull()
  103. expect(view.getByText('IDENTIFICATION DIVISION.')).toBeTruthy()
  104. })
  105. it('renders the plain arm when no language is given', () => {
  106. const view = render(<CodeBlock code="plain text" />)
  107. expect(view.container.querySelector('pre.shiki')).toBeNull()
  108. expect(view.getByText('plain text')).toBeTruthy()
  109. })
  110. it('shows the language banner and copies the pre textContent', async () => {
  111. vi.useFakeTimers()
  112. const writeText = vi.fn().mockResolvedValue(undefined)
  113. Object.defineProperty(navigator, 'clipboard', {
  114. configurable: true,
  115. value: { writeText },
  116. })
  117. render(<CodeBlock code={'const a = 1\n'} lang="ts" />)
  118. expect(screen.getByText('ts')).toBeTruthy()
  119. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  120. expect(writeText).toHaveBeenCalledWith('const a = 1')
  121. // Flush the clipboard promise under fake timers before asserting the label.
  122. await act(async () => {
  123. await Promise.resolve()
  124. })
  125. expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
  126. // While the ok label is showing, further clicks are no-ops.
  127. fireEvent.click(screen.getByRole('button', { name: '复制成功' }))
  128. expect(writeText).toHaveBeenCalledTimes(1)
  129. await vi.advanceTimersByTimeAsync(1000)
  130. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  131. })
  132. it('does not claim success when clipboard.writeText rejects', async () => {
  133. const writeText = vi.fn().mockRejectedValue(new Error('denied'))
  134. Object.defineProperty(navigator, 'clipboard', {
  135. configurable: true,
  136. value: { writeText },
  137. })
  138. render(<CodeBlock code="plain body" />)
  139. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  140. await act(async () => {
  141. await Promise.resolve()
  142. })
  143. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  144. expect(screen.queryByRole('button', { name: '复制成功' })).toBeNull()
  145. })
  146. it('falls back to execCommand when clipboard.writeText is unavailable', async () => {
  147. Object.defineProperty(navigator, 'clipboard', {
  148. configurable: true,
  149. value: undefined,
  150. })
  151. const exec = vi.fn().mockReturnValue(true)
  152. Object.defineProperty(document, 'execCommand', {
  153. configurable: true,
  154. value: exec,
  155. })
  156. render(<CodeBlock code="plain body" />)
  157. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  158. expect(exec).toHaveBeenCalledWith('copy')
  159. expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy()
  160. })
  161. it('does not claim success when execCommand throws or is absent', async () => {
  162. Object.defineProperty(navigator, 'clipboard', {
  163. configurable: true,
  164. value: undefined,
  165. })
  166. Object.defineProperty(document, 'execCommand', {
  167. configurable: true,
  168. value: () => {
  169. throw new Error('denied')
  170. },
  171. })
  172. const denied = render(<CodeBlock code="plain body" />)
  173. fireEvent.click(denied.getByRole('button', { name: '复制' }))
  174. await Promise.resolve()
  175. expect(denied.getByRole('button', { name: '复制' })).toBeTruthy()
  176. denied.unmount()
  177. Object.defineProperty(document, 'execCommand', {
  178. configurable: true,
  179. value: undefined,
  180. })
  181. const absent = render(<CodeBlock code="plain body" />)
  182. fireEvent.click(absent.getByRole('button', { name: '复制' }))
  183. await Promise.resolve()
  184. expect(absent.getByRole('button', { name: '复制' })).toBeTruthy()
  185. expect(absent.queryByRole('button', { name: '复制成功' })).toBeNull()
  186. })
  187. })