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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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('reports only newly completed lines to a retained renderer', () => {
  63. const session = new StreamingHighlightSession()
  64. const first = session.updateFrame('const a = 1\nlet', 'ts')
  65. const second = session.updateFrame('const a = 1\nlet b = 2\n// tail', 'ts')
  66. expect(first?.appended).toHaveLength(1)
  67. expect(first?.tail).toHaveLength(1)
  68. expect(second?.appended).toHaveLength(1)
  69. expect(second?.appended[0]?.map(span => span.text).join('')).toBe('let b = 2')
  70. expect(second?.tail[0]?.map(span => span.text).join('')).toBe('// tail')
  71. expect(second?.generation).toBe(first?.generation)
  72. expect(session.updateFrame('const a = 1\nlet b = 2\n// tail', 'ts')).toBe(second)
  73. })
  74. it('emits one completed line per frame across an 800-line stream', () => {
  75. const session = new StreamingHighlightSession()
  76. let code = ''
  77. let generation: number | undefined
  78. let appended = 0
  79. for (let index = 0; index < 800; index += 1) {
  80. const line = `const value${String(index)} = ${String(index)}`
  81. code += `${line}\n`
  82. const frame = session.updateFrame(code, 'ts')
  83. expect(frame?.appended).toHaveLength(1)
  84. expect(frame?.appended[0]?.map(span => span.text).join('')).toBe(line)
  85. generation ??= frame?.generation
  86. expect(frame?.generation).toBe(generation)
  87. appended += frame?.appended.length ?? 0
  88. }
  89. // Frame cardinality is stable across CI hosts; wall-clock thresholds are
  90. // diagnostics owned by the manual Web performance inventory.
  91. expect(appended).toBe(800)
  92. })
  93. it('is idempotent per input: repeated calls return the identical result array', () => {
  94. const session = new StreamingHighlightSession()
  95. const result = session.update('const a = 1', 'ts')
  96. expect(result).toBeDefined()
  97. expect(session.update('const a = 1', 'ts')).toBe(result)
  98. })
  99. it('an alias switch onto the same grammar keeps the cache; a different grammar re-tokenizes correctly', () => {
  100. const session = new StreamingHighlightSession()
  101. const first = session.update('const a = 1\nlet', 'ts')
  102. expect(first).toBeDefined()
  103. // Same code under a different alias of the same grammar: recomputed
  104. // (the idempotence key is the raw input) but the line cache is kept.
  105. const aliased = session.update('const a = 1\nlet', 'typescript')
  106. expect(aliased?.[0]).toBe(first?.[0])
  107. const json = session.update('{"a": 1}', 'json')
  108. expect(json).toEqual(new StreamingHighlightSession().update('{"a": 1}', 'json'))
  109. })
  110. it('non-append input re-tokenizes from scratch', () => {
  111. const session = new StreamingHighlightSession()
  112. session.update('const a = 1\nconst b = 2', 'ts')
  113. const replaced = session.update('let c = 3', 'ts')
  114. expect(replaced).toEqual(new StreamingHighlightSession().update('let c = 3', 'ts'))
  115. })
  116. it('returns undefined for unknown or absent languages, then recovers when a known one arrives', () => {
  117. const session = new StreamingHighlightSession()
  118. expect(session.update('x', 'cobol')).toBeUndefined()
  119. expect(session.update('x', undefined)).toBeUndefined()
  120. expect(session.update('const x = 1', 'ts')).toEqual(new StreamingHighlightSession().update('const x = 1', 'ts'))
  121. })
  122. it('a lazy grammar reports plain until it registers, then highlights on the next update', async () => {
  123. const session = new StreamingHighlightSession()
  124. expect(session.update('print(1)', 'python')).toBeUndefined()
  125. await vi.waitFor(() => {
  126. const lines = session.update('print(1)', 'python')
  127. expect(lines?.[0]?.map(span => span.text).join('')).toBe('print(1)')
  128. expect(lines?.[0]?.length).toBeGreaterThan(1)
  129. }, { timeout: 5_000 })
  130. })
  131. it('a trailing newline renders as a real empty last line (settled-arm parity)', () => {
  132. const lines = new StreamingHighlightSession().update('const a = 1\n', 'ts')
  133. expect(lines).toHaveLength(2)
  134. expect(lines?.[1]).toEqual([])
  135. })
  136. it('a blank line inside a multi-line construct keeps the saved grammar state', () => {
  137. // The empty completed segment tokenizes as [[]]; the state saved after it
  138. // must still be the inside-template state, so the continuation stays
  139. // string-colored (incremental equals from-scratch at every prefix).
  140. const code = 'const s = `a\n\nb` // done'
  141. const session = new StreamingHighlightSession()
  142. for (let end = 1; end <= code.length; end++) {
  143. const slice = code.slice(0, end)
  144. expect(session.update(slice, 'ts')).toEqual(new StreamingHighlightSession().update(slice, 'ts'))
  145. }
  146. const lines = session.update(code, 'ts')
  147. expect(lines?.[1]).toEqual([])
  148. expect(lines?.[2]?.[0]?.text).toBe('b`')
  149. expect(lines?.[2]?.[0]?.style.color).toBe('var(--shiki-token-string-expression)')
  150. })
  151. it('a CRLF boundary never leaks its \\r into the grammar (shiki line-split parity)', () => {
  152. // bash: a backslash continuation only holds if the line ends at the
  153. // continuation — a leaked \r would break the saved state and recolor the
  154. // next line as a fresh command.
  155. const code = 'echo a \\\r\nb\r\nc'
  156. const session = new StreamingHighlightSession()
  157. for (let end = 1; end <= code.length; end++) {
  158. const slice = code.slice(0, end)
  159. expect(session.update(slice, 'bash')).toEqual(new StreamingHighlightSession().update(slice, 'bash'))
  160. }
  161. // Span text carries no \r for completed lines, exactly like the settled
  162. // arm's shiki output.
  163. const lines = session.update(code, 'bash')
  164. expect(lines?.map(line => line.map(span => span.text).join('')).join('\n')).toBe('echo a \\\nb\nc')
  165. })
  166. it('markdown markup styles (bold/italic/underline) reach the spans once the grammar loads', async () => {
  167. const snippet = '# Heading\n**bold words** and *italic* and a [link with spaces](https://x.example) tail'
  168. await vi.waitFor(() => {
  169. expect(new StreamingHighlightSession().update('# x', 'md')).toBeDefined()
  170. }, { timeout: 5_000 })
  171. const session = new StreamingHighlightSession()
  172. for (let end = 1; end <= snippet.length; end++) {
  173. const slice = snippet.slice(0, end)
  174. expect(session.update(slice, 'md')).toEqual(new StreamingHighlightSession().update(slice, 'md'))
  175. }
  176. const lines = session.update(snippet, 'md')
  177. expect(lines?.[0]?.[0]?.style.fontWeight).toBe('bold')
  178. const spans = lines?.[1] ?? []
  179. expect(spans.some(span => span.style.fontWeight === 'bold')).toBe(true)
  180. expect(spans.some(span => span.style.fontStyle === 'italic')).toBe(true)
  181. expect(spans.some(span => span.style.textDecoration === 'underline')).toBe(true)
  182. })
  183. })
  184. describe('CodeBlock streaming arm', () => {
  185. it('renders the same token tree as the settled shiki HTML swap', () => {
  186. const code = 'const s = `tpl\nline ${x}\n`\n'
  187. const streamed = render(<CodeBlock code={code} lang="ts" streaming {...LABELS} />)
  188. const settled = render(<CodeBlock code={code} lang="ts" {...LABELS} />)
  189. expect(readPre(streamed.container)).toEqual(readPre(settled.container))
  190. })
  191. it('a markdown fence matches the settled swap including font styles, and a CRLF fence matches too', async () => {
  192. // md is a lazy grammar: wait for it so both arms highlight.
  193. await vi.waitFor(() => {
  194. expect(new StreamingHighlightSession().update('# x', 'md')).toBeDefined()
  195. }, { timeout: 5_000 })
  196. const md = '# Heading\n**bold words** and *italic* and a [link with spaces](https://x.example) tail\n'
  197. const mdStreamed = render(<CodeBlock code={md} lang="md" streaming {...LABELS} />)
  198. const mdSettled = render(<CodeBlock code={md} lang="md" {...LABELS} />)
  199. const streamedTree = readPre(mdStreamed.container)
  200. expect(streamedTree).toEqual(readPre(mdSettled.container))
  201. // The settled arm really carries the styles, so the equality above cannot
  202. // pass by both arms dropping them.
  203. const flat = streamedTree.lines.flat().join(' ')
  204. expect(flat).toContain('|bold|')
  205. expect(flat).toContain('|italic|')
  206. expect(flat).toContain('|underline')
  207. const crlf = 'echo a \\\r\nb\r\nc\n'
  208. const crlfStreamed = render(<CodeBlock code={crlf} lang="bash" streaming {...LABELS} />)
  209. const crlfSettled = render(<CodeBlock code={crlf} lang="bash" {...LABELS} />)
  210. expect(readPre(crlfStreamed.container)).toEqual(readPre(crlfSettled.container))
  211. })
  212. it('keeps completed lines\' DOM nodes as the code grows and appends the new ones', () => {
  213. const view = render(<CodeBlock code={'const a = 1\nlet partial\n'} lang="ts" streaming {...LABELS} />)
  214. const firstLine = view.container.querySelector('pre.shiki .line')
  215. expect(firstLine).not.toBeNull()
  216. view.rerender(<CodeBlock code={'const a = 1\nlet partial = 2\n// tail\n'} lang="ts" streaming {...LABELS} />)
  217. const lines = view.container.querySelectorAll('pre.shiki .line')
  218. expect(lines).toHaveLength(3)
  219. expect(lines[0]).toBe(firstLine)
  220. expect(lines[2]?.textContent).toBe('// tail')
  221. // Newlines separate the line spans, so pre textContent (the copy source)
  222. // stays the code verbatim.
  223. expect(view.container.querySelector('pre.shiki')?.textContent).toBe('const a = 1\nlet partial = 2\n// tail')
  224. })
  225. it('keeps a tail line mounted when the next frame completes it', () => {
  226. const view = render(<CodeBlock code={'const first = 1\n'} lang="ts" streaming {...LABELS} />)
  227. const firstLine = view.container.querySelector('pre.shiki .line')
  228. expect(firstLine).not.toBeNull()
  229. view.rerender(
  230. <CodeBlock code={'const first = 1\nconst second = 2\nlet tail'} lang="ts" streaming {...LABELS} />,
  231. )
  232. expect(view.container.querySelector('pre.shiki .line')).toBe(firstLine)
  233. })
  234. it('keeps completed line groups mounted while later groups grow', () => {
  235. const code = (count: number) => Array.from({ length: count }, (_, index) => `const v${String(index)} = ${String(index)}`).join('\n')
  236. const view = render(<CodeBlock code={code(40)} lang="ts" streaming {...LABELS} />)
  237. const firstLine = view.container.querySelector('pre.shiki .line')
  238. const thirtySecond = view.container.querySelectorAll('pre.shiki .line')[31]
  239. view.rerender(<CodeBlock code={code(80)} lang="ts" streaming {...LABELS} />)
  240. const lines = view.container.querySelectorAll('pre.shiki .line')
  241. expect(lines).toHaveLength(80)
  242. expect(lines[0]).toBe(firstLine)
  243. expect(lines[31]).toBe(thirtySecond)
  244. })
  245. it('reuses an unchanged frame when an unrelated lazy grammar finishes loading', async () => {
  246. const view = render(<CodeBlock code={'const stable = 1\n'} lang="ts" streaming {...LABELS} />)
  247. const line = view.container.querySelector('pre.shiki .line')
  248. expect(line).not.toBeNull()
  249. const loader = new StreamingHighlightSession()
  250. expect(loader.update('puts 1', 'ruby')).toBeUndefined()
  251. await vi.waitFor(() => { expect(loader.update('puts 1', 'ruby')).toBeDefined() }, { timeout: 5_000 })
  252. expect(view.container.querySelector('pre.shiki .line')).toBe(line)
  253. })
  254. it('streaming with an unknown language stays on the identical plain arm', () => {
  255. const view = render(<CodeBlock code={'IDENTIFICATION DIVISION.\n'} lang="cobol" streaming {...LABELS} />)
  256. expect(view.container.querySelector('pre.shiki')).toBeNull()
  257. expect(view.getByText('IDENTIFICATION DIVISION.')).toBeTruthy()
  258. })
  259. it('the settle transition preserves the highlighted DOM when the code is unchanged', () => {
  260. const code = 'const answer = 42\n'
  261. const view = render(<CodeBlock code={code} lang="ts" streaming {...LABELS} />)
  262. const streamedLine = view.container.querySelector('pre.shiki .line')
  263. const streamedText = view.container.querySelector('pre.shiki')?.textContent
  264. view.rerender(<CodeBlock code={code} lang="ts" {...LABELS} />)
  265. const settledText = view.container.querySelector('pre.shiki')?.textContent
  266. expect(streamedText).toBe('const answer = 42')
  267. expect(settledText).toBe(streamedText)
  268. expect(view.container.querySelector('pre.shiki .line')).toBe(streamedLine)
  269. view.rerender(<CodeBlock code={code} lang="ts" streaming {...LABELS} />)
  270. expect(view.container.querySelector('pre.shiki')?.textContent).toBe(streamedText)
  271. expect(view.container.querySelector('pre.shiki .line')).toBe(streamedLine)
  272. })
  273. })