code-block.client.spec.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. })
  59. it('renders the plain arm for an unknown language with the text verbatim', () => {
  60. const view = render(<CodeBlock code={'IDENTIFICATION DIVISION.'} lang="cobol" />)
  61. expect(view.container.querySelector('pre.shiki')).toBeNull()
  62. expect(view.getByText('IDENTIFICATION DIVISION.')).toBeTruthy()
  63. })
  64. it('renders the plain arm when no language is given', () => {
  65. const view = render(<CodeBlock code="plain text" />)
  66. expect(view.container.querySelector('pre.shiki')).toBeNull()
  67. expect(view.getByText('plain text')).toBeTruthy()
  68. })
  69. it('shows the language banner and copies the pre textContent', async () => {
  70. vi.useFakeTimers()
  71. const writeText = vi.fn().mockResolvedValue(undefined)
  72. Object.defineProperty(navigator, 'clipboard', {
  73. configurable: true,
  74. value: { writeText },
  75. })
  76. render(<CodeBlock code={'const a = 1\n'} lang="ts" />)
  77. expect(screen.getByText('ts')).toBeTruthy()
  78. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  79. expect(writeText).toHaveBeenCalledWith('const a = 1')
  80. // Flush the clipboard promise under fake timers before asserting the label.
  81. await act(async () => {
  82. await Promise.resolve()
  83. })
  84. expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
  85. // While the ok label is showing, further clicks are no-ops.
  86. fireEvent.click(screen.getByRole('button', { name: '复制成功' }))
  87. expect(writeText).toHaveBeenCalledTimes(1)
  88. await vi.advanceTimersByTimeAsync(1000)
  89. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  90. })
  91. it('does not claim success when clipboard.writeText rejects', async () => {
  92. const writeText = vi.fn().mockRejectedValue(new Error('denied'))
  93. Object.defineProperty(navigator, 'clipboard', {
  94. configurable: true,
  95. value: { writeText },
  96. })
  97. render(<CodeBlock code="plain body" />)
  98. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  99. await act(async () => {
  100. await Promise.resolve()
  101. })
  102. expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
  103. expect(screen.queryByRole('button', { name: '复制成功' })).toBeNull()
  104. })
  105. it('falls back to execCommand when clipboard.writeText is unavailable', async () => {
  106. Object.defineProperty(navigator, 'clipboard', {
  107. configurable: true,
  108. value: undefined,
  109. })
  110. const exec = vi.fn().mockReturnValue(true)
  111. Object.defineProperty(document, 'execCommand', {
  112. configurable: true,
  113. value: exec,
  114. })
  115. render(<CodeBlock code="plain body" />)
  116. fireEvent.click(screen.getByRole('button', { name: '复制' }))
  117. expect(exec).toHaveBeenCalledWith('copy')
  118. expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy()
  119. })
  120. it('does not claim success when execCommand throws or is absent', async () => {
  121. Object.defineProperty(navigator, 'clipboard', {
  122. configurable: true,
  123. value: undefined,
  124. })
  125. Object.defineProperty(document, 'execCommand', {
  126. configurable: true,
  127. value: () => {
  128. throw new Error('denied')
  129. },
  130. })
  131. const denied = render(<CodeBlock code="plain body" />)
  132. fireEvent.click(denied.getByRole('button', { name: '复制' }))
  133. await Promise.resolve()
  134. expect(denied.getByRole('button', { name: '复制' })).toBeTruthy()
  135. denied.unmount()
  136. Object.defineProperty(document, 'execCommand', {
  137. configurable: true,
  138. value: undefined,
  139. })
  140. const absent = render(<CodeBlock code="plain body" />)
  141. fireEvent.click(absent.getByRole('button', { name: '复制' }))
  142. await Promise.resolve()
  143. expect(absent.getByRole('button', { name: '复制' })).toBeTruthy()
  144. expect(absent.queryByRole('button', { name: '复制成功' })).toBeNull()
  145. })
  146. })