code-block.client.spec.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 } 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. // First touch returns the plain fallback (undefined) and starts the import.
  38. for (const alias of LAZY_ALIASES) expect(highlightToHtml('x', alias)).toBeUndefined()
  39. // Once every grammar has registered, the same call highlights.
  40. await vi.waitFor(() => {
  41. for (const alias of LAZY_ALIASES) expect(highlightToHtml('x', alias)).toContain('shiki')
  42. }, { timeout: 5_000 })
  43. })
  44. })
  45. describe('CodeBlock', () => {
  46. it('renders the highlighted tree for TypeScript', () => {
  47. const view = render(<CodeBlock code={'const a = 1\n'} lang="ts" />)
  48. const pre = view.container.querySelector('pre.shiki')
  49. expect(pre).not.toBeNull()
  50. expect(pre!.textContent).toBe('const a = 1')
  51. expect(pre!.querySelectorAll('span[style]').length).toBeGreaterThan(1)
  52. })
  53. it('renders the plain arm for an unknown language with the text verbatim', () => {
  54. const view = render(<CodeBlock code={'IDENTIFICATION DIVISION.'} lang="cobol" />)
  55. expect(view.container.querySelector('pre.shiki')).toBeNull()
  56. expect(view.getByText('IDENTIFICATION DIVISION.')).toBeTruthy()
  57. })
  58. it('renders the plain arm when no language is given', () => {
  59. const view = render(<CodeBlock code="plain text" />)
  60. expect(view.container.querySelector('pre.shiki')).toBeNull()
  61. expect(view.getByText('plain text')).toBeTruthy()
  62. })
  63. it('shows the language banner and copies the pre textContent', async () => {
  64. vi.useFakeTimers()
  65. const writeText = vi.fn().mockResolvedValue(undefined)
  66. Object.defineProperty(navigator, 'clipboard', {
  67. configurable: true,
  68. value: { writeText },
  69. })
  70. render(<CodeBlock code={'const a = 1\n'} lang="ts" />)
  71. expect(screen.getByText('ts')).toBeTruthy()
  72. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  73. expect(writeText).toHaveBeenCalledWith('const a = 1')
  74. // Flush the clipboard promise under fake timers before asserting the label.
  75. await act(async () => {
  76. await Promise.resolve()
  77. })
  78. expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
  79. // While the ok label is showing, further clicks are no-ops.
  80. fireEvent.click(screen.getByRole('button', { name: '复制成功' }))
  81. expect(writeText).toHaveBeenCalledTimes(1)
  82. await vi.advanceTimersByTimeAsync(1000)
  83. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  84. })
  85. it('does not claim success when clipboard.writeText rejects', async () => {
  86. const writeText = vi.fn().mockRejectedValue(new Error('denied'))
  87. Object.defineProperty(navigator, 'clipboard', {
  88. configurable: true,
  89. value: { writeText },
  90. })
  91. render(<CodeBlock code="plain body" />)
  92. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  93. await act(async () => {
  94. await Promise.resolve()
  95. })
  96. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  97. expect(screen.queryByRole('button', { name: '复制成功' })).toBeNull()
  98. })
  99. it('falls back to execCommand when clipboard.writeText is unavailable', async () => {
  100. Object.defineProperty(navigator, 'clipboard', {
  101. configurable: true,
  102. value: undefined,
  103. })
  104. const exec = vi.fn().mockReturnValue(true)
  105. Object.defineProperty(document, 'execCommand', {
  106. configurable: true,
  107. value: exec,
  108. })
  109. render(<CodeBlock code="plain body" />)
  110. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  111. expect(exec).toHaveBeenCalledWith('copy')
  112. expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy()
  113. })
  114. it('does not claim success when execCommand throws or is absent', async () => {
  115. Object.defineProperty(navigator, 'clipboard', {
  116. configurable: true,
  117. value: undefined,
  118. })
  119. Object.defineProperty(document, 'execCommand', {
  120. configurable: true,
  121. value: () => {
  122. throw new Error('denied')
  123. },
  124. })
  125. const denied = render(<CodeBlock code="plain body" />)
  126. fireEvent.click(denied.getByRole('button', { name: '复制' }))
  127. await Promise.resolve()
  128. expect(denied.getByRole('button', { name: '复制' })).toBeTruthy()
  129. denied.unmount()
  130. Object.defineProperty(document, 'execCommand', {
  131. configurable: true,
  132. value: undefined,
  133. })
  134. const absent = render(<CodeBlock code="plain body" />)
  135. fireEvent.click(absent.getByRole('button', { name: '复制' }))
  136. await Promise.resolve()
  137. expect(absent.getByRole('button', { name: '复制' })).toBeTruthy()
  138. expect(absent.queryByRole('button', { name: '复制成功' })).toBeNull()
  139. })
  140. })