streaming-code-block.client.spec.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // @vitest-environment jsdom
  2. // The streaming fence arm: StreamingHighlightSession's incremental
  3. // tokenization equals from-scratch tokenization at every appended prefix, and
  4. // CodeBlock's `streaming` arm renders the same token tree as the settled
  5. // shiki-HTML swap while keeping completed lines' DOM nodes untouched. Lives
  6. // apart from code-block.client.spec.tsx so its lazy-grammar timing cannot
  7. // race that file's first-touch assertions (files run isolated).
  8. import { afterEach, describe, expect, it, vi } from 'vitest'
  9. import { cleanup, render } from '@testing-library/react'
  10. import { CodeBlock } from '../src/markdown/CodeBlock.tsx'
  11. import { StreamingHighlightSession } from '../src/markdown/highlight.ts'
  12. import { markdownLabels } from './labels.client.ts'
  13. const LABELS = markdownLabels.code
  14. afterEach(cleanup)
  15. /**
  16. * One arm's rendered token tree, with every style channel the settled shiki
  17. * HTML emits (color plus the markup font-style bits), so equality between the
  18. * streaming spans and the settled `codeToHtml` swap pins full visual parity.
  19. */
  20. function readPre(root: HTMLElement) {
  21. const pre = root.querySelector('pre.shiki')
  22. expect(pre).not.toBeNull()
  23. return {
  24. classes: [...pre!.classList].sort().join(' '),
  25. tabIndex: pre!.getAttribute('tabindex'),
  26. text: pre!.textContent,
  27. lines: [...pre!.querySelectorAll('.line')].map(line =>
  28. [...line.querySelectorAll('span[style]')].map((span) => {
  29. const style = (span as HTMLElement).style
  30. return `${span.textContent ?? ''}|${style.color}|${style.fontStyle}|${style.fontWeight}|${style.textDecoration}`
  31. }),
  32. ),
  33. }
  34. }
  35. describe('StreamingHighlightSession', () => {
  36. it('reconstructs the code verbatim and colors tokens through --shiki-* properties', () => {
  37. const code = 'const a = 1\n// note\nconst b = "x"'
  38. const lines = new StreamingHighlightSession().update(code, 'ts')
  39. expect(lines?.map(line => line.map(span => span.text).join('')).join('\n')).toBe(code)
  40. expect(lines?.[0]?.[0]).toEqual({ text: 'const', style: { color: 'var(--shiki-token-keyword)' } })
  41. expect(lines?.[1]?.[0]?.style.color).toBe('var(--shiki-token-comment)')
  42. })
  43. it('incremental growth equals a fresh from-scratch tokenization at every prefix', () => {
  44. // The template literal spans lines, so mid-stream states leave the
  45. // grammar inside a multi-line construct — the case where a stale saved
  46. // state would color the continuation wrong.
  47. const code = 'const s = `template\nline ${x} mid\n` // done\nconst t: number = 42'
  48. const session = new StreamingHighlightSession()
  49. for (let end = 1; end <= code.length; end++) {
  50. const slice = code.slice(0, end)
  51. expect(session.update(slice, 'ts')).toEqual(new StreamingHighlightSession().update(slice, 'ts'))
  52. }
  53. })
  54. it('keeps completed lines\' span arrays identical across growth and re-tokenizes only the tail', () => {
  55. const session = new StreamingHighlightSession()
  56. const first = session.update('const a = 1\nlet', 'ts')
  57. expect(first).toBeDefined()
  58. const second = session.update('const a = 1\nlet b = 2', 'ts')
  59. expect(second?.[0]).toBe(first?.[0])
  60. expect(second?.[1]).not.toBe(first?.[1])
  61. })
  62. it('is idempotent per input: repeated calls return the identical result array', () => {
  63. const session = new StreamingHighlightSession()
  64. const result = session.update('const a = 1', 'ts')
  65. expect(result).toBeDefined()
  66. expect(session.update('const a = 1', 'ts')).toBe(result)
  67. })
  68. it('an alias switch onto the same grammar keeps the cache; a different grammar re-tokenizes correctly', () => {
  69. const session = new StreamingHighlightSession()
  70. const first = session.update('const a = 1\nlet', 'ts')
  71. expect(first).toBeDefined()
  72. // Same code under a different alias of the same grammar: recomputed
  73. // (the idempotence key is the raw input) but the line cache is kept.
  74. const aliased = session.update('const a = 1\nlet', 'typescript')
  75. expect(aliased?.[0]).toBe(first?.[0])
  76. const json = session.update('{"a": 1}', 'json')
  77. expect(json).toEqual(new StreamingHighlightSession().update('{"a": 1}', 'json'))
  78. })
  79. it('non-append input re-tokenizes from scratch', () => {
  80. const session = new StreamingHighlightSession()
  81. session.update('const a = 1\nconst b = 2', 'ts')
  82. const replaced = session.update('let c = 3', 'ts')
  83. expect(replaced).toEqual(new StreamingHighlightSession().update('let c = 3', 'ts'))
  84. })
  85. it('returns undefined for unknown or absent languages, then recovers when a known one arrives', () => {
  86. const session = new StreamingHighlightSession()
  87. expect(session.update('x', 'cobol')).toBeUndefined()
  88. expect(session.update('x', undefined)).toBeUndefined()
  89. expect(session.update('const x = 1', 'ts')).toEqual(new StreamingHighlightSession().update('const x = 1', 'ts'))
  90. })
  91. it('a lazy grammar reports plain until it registers, then highlights on the next update', async () => {
  92. const session = new StreamingHighlightSession()
  93. expect(session.update('print(1)', 'python')).toBeUndefined()
  94. await vi.waitFor(() => {
  95. const lines = session.update('print(1)', 'python')
  96. expect(lines?.[0]?.map(span => span.text).join('')).toBe('print(1)')
  97. expect(lines?.[0]?.length).toBeGreaterThan(1)
  98. }, { timeout: 5_000 })
  99. })
  100. it('a trailing newline renders as a real empty last line (settled-arm parity)', () => {
  101. const lines = new StreamingHighlightSession().update('const a = 1\n', 'ts')
  102. expect(lines).toHaveLength(2)
  103. expect(lines?.[1]).toEqual([])
  104. })
  105. it('a blank line inside a multi-line construct keeps the saved grammar state', () => {
  106. // The empty completed segment tokenizes as [[]]; the state saved after it
  107. // must still be the inside-template state, so the continuation stays
  108. // string-colored (incremental equals from-scratch at every prefix).
  109. const code = 'const s = `a\n\nb` // done'
  110. const session = new StreamingHighlightSession()
  111. for (let end = 1; end <= code.length; end++) {
  112. const slice = code.slice(0, end)
  113. expect(session.update(slice, 'ts')).toEqual(new StreamingHighlightSession().update(slice, 'ts'))
  114. }
  115. const lines = session.update(code, 'ts')
  116. expect(lines?.[1]).toEqual([])
  117. expect(lines?.[2]?.[0]?.text).toBe('b`')
  118. expect(lines?.[2]?.[0]?.style.color).toBe('var(--shiki-token-string-expression)')
  119. })
  120. it('a CRLF boundary never leaks its \\r into the grammar (shiki line-split parity)', () => {
  121. // bash: a backslash continuation only holds if the line ends at the
  122. // continuation — a leaked \r would break the saved state and recolor the
  123. // next line as a fresh command.
  124. const code = 'echo a \\\r\nb\r\nc'
  125. const session = new StreamingHighlightSession()
  126. for (let end = 1; end <= code.length; end++) {
  127. const slice = code.slice(0, end)
  128. expect(session.update(slice, 'bash')).toEqual(new StreamingHighlightSession().update(slice, 'bash'))
  129. }
  130. // Span text carries no \r for completed lines, exactly like the settled
  131. // arm's shiki output.
  132. const lines = session.update(code, 'bash')
  133. expect(lines?.map(line => line.map(span => span.text).join('')).join('\n')).toBe('echo a \\\nb\nc')
  134. })
  135. it('markdown markup styles (bold/italic/underline) reach the spans once the grammar loads', async () => {
  136. const snippet = '# Heading\n**bold words** and *italic* and a [link with spaces](https://x.example) tail'
  137. await vi.waitFor(() => {
  138. expect(new StreamingHighlightSession().update('# x', 'md')).toBeDefined()
  139. }, { timeout: 5_000 })
  140. const session = new StreamingHighlightSession()
  141. for (let end = 1; end <= snippet.length; end++) {
  142. const slice = snippet.slice(0, end)
  143. expect(session.update(slice, 'md')).toEqual(new StreamingHighlightSession().update(slice, 'md'))
  144. }
  145. const lines = session.update(snippet, 'md')
  146. expect(lines?.[0]?.[0]?.style.fontWeight).toBe('bold')
  147. const spans = lines?.[1] ?? []
  148. expect(spans.some(span => span.style.fontWeight === 'bold')).toBe(true)
  149. expect(spans.some(span => span.style.fontStyle === 'italic')).toBe(true)
  150. expect(spans.some(span => span.style.textDecoration === 'underline')).toBe(true)
  151. })
  152. })
  153. describe('CodeBlock streaming arm', () => {
  154. it('renders the same token tree as the settled shiki HTML swap', () => {
  155. const code = 'const s = `tpl\nline ${x}\n`\n'
  156. const streamed = render(<CodeBlock code={code} lang="ts" streaming {...LABELS} />)
  157. const settled = render(<CodeBlock code={code} lang="ts" {...LABELS} />)
  158. expect(readPre(streamed.container)).toEqual(readPre(settled.container))
  159. })
  160. it('a markdown fence matches the settled swap including font styles, and a CRLF fence matches too', async () => {
  161. // md is a lazy grammar: wait for it so both arms highlight.
  162. await vi.waitFor(() => {
  163. expect(new StreamingHighlightSession().update('# x', 'md')).toBeDefined()
  164. }, { timeout: 5_000 })
  165. const md = '# Heading\n**bold words** and *italic* and a [link with spaces](https://x.example) tail\n'
  166. const mdStreamed = render(<CodeBlock code={md} lang="md" streaming {...LABELS} />)
  167. const mdSettled = render(<CodeBlock code={md} lang="md" {...LABELS} />)
  168. const streamedTree = readPre(mdStreamed.container)
  169. expect(streamedTree).toEqual(readPre(mdSettled.container))
  170. // The settled arm really carries the styles, so the equality above cannot
  171. // pass by both arms dropping them.
  172. const flat = streamedTree.lines.flat().join(' ')
  173. expect(flat).toContain('|bold|')
  174. expect(flat).toContain('|italic|')
  175. expect(flat).toContain('|underline')
  176. const crlf = 'echo a \\\r\nb\r\nc\n'
  177. const crlfStreamed = render(<CodeBlock code={crlf} lang="bash" streaming {...LABELS} />)
  178. const crlfSettled = render(<CodeBlock code={crlf} lang="bash" {...LABELS} />)
  179. expect(readPre(crlfStreamed.container)).toEqual(readPre(crlfSettled.container))
  180. })
  181. it('keeps completed lines\' DOM nodes as the code grows and appends the new ones', () => {
  182. const view = render(<CodeBlock code={'const a = 1\nlet partial\n'} lang="ts" streaming {...LABELS} />)
  183. const firstLine = view.container.querySelector('pre.shiki .line')
  184. expect(firstLine).not.toBeNull()
  185. view.rerender(<CodeBlock code={'const a = 1\nlet partial = 2\n// tail\n'} lang="ts" streaming {...LABELS} />)
  186. const lines = view.container.querySelectorAll('pre.shiki .line')
  187. expect(lines).toHaveLength(3)
  188. expect(lines[0]).toBe(firstLine)
  189. expect(lines[2]?.textContent).toBe('// tail')
  190. // Newlines separate the line spans, so pre textContent (the copy source)
  191. // stays the code verbatim.
  192. expect(view.container.querySelector('pre.shiki')?.textContent).toBe('const a = 1\nlet partial = 2\n// tail')
  193. })
  194. it('streaming with an unknown language stays on the identical plain arm', () => {
  195. const view = render(<CodeBlock code={'IDENTIFICATION DIVISION.\n'} lang="cobol" streaming {...LABELS} />)
  196. expect(view.container.querySelector('pre.shiki')).toBeNull()
  197. expect(view.getByText('IDENTIFICATION DIVISION.')).toBeTruthy()
  198. })
  199. it('the settle swap (streaming to settled) preserves the code content', () => {
  200. const code = 'const answer = 42\n'
  201. const view = render(<CodeBlock code={code} lang="ts" streaming {...LABELS} />)
  202. const streamedText = view.container.querySelector('pre.shiki')?.textContent
  203. view.rerender(<CodeBlock code={code} lang="ts" {...LABELS} />)
  204. const settledText = view.container.querySelector('pre.shiki')?.textContent
  205. expect(streamedText).toBe('const answer = 42')
  206. expect(settledText).toBe(streamedText)
  207. })
  208. })