Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(docs): repeated shiki grammar registration (#50501)

Anthony Lio7fb2e8cd4239
diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts
index 866f55dd1a8..15996104ccd 100644
--- a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts
+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts
@@ -1,223 +1,87 @@
-import { bundledLanguages, createHighlighter, type BundledLanguage } from 'shiki'
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { bundledLanguages, createHighlighter, type Highlighter } from 'shiki'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import theme from './supabase-2.json' with { type: 'json' }
vi.mock('shiki', async (importOriginal) => {
const actual = await importOriginal<typeof import('shiki')>()
- return { ...actual, createHighlighter: vi.fn(actual.createHighlighter) }
+ return { ...actual, createHighlighter: vi.fn() }
})
-const fixtures: Array<{ name: string; lang: BundledLanguage | null; code: string }> = [
- { name: 'Bash', lang: 'bash', code: 'echo "hello ${USER}"\n# A comment' },
- { name: 'shell alias', lang: 'shell', code: "supabase sso add --metadata-url 'https://...'" },
- {
- name: 'JavaScript',
- lang: 'javascript',
- code: 'const greeting = /hello/g\ngreeting.test("hello")',
- },
- { name: 'JavaScript alias', lang: 'js', code: 'const value = 42\nconsole.log(value)' },
- {
- name: 'TypeScript',
- lang: 'typescript',
- code: 'interface User { id: number }\nconst id: User["id"] = 42',
- },
- { name: 'TypeScript alias', lang: 'ts', code: 'const count: number = 42' },
- {
- name: 'SQL',
- lang: 'sql',
- code: "select 'You had me at SELECT' as greeting, 42 as count;\n-- A comment",
- },
- { name: 'JSON', lang: 'json', code: '{"name":"reader","active":true}' },
- {
- name: 'Elixir',
- lang: 'elixir',
- code: 'defmodule Hello do\n def greet(name), do: "Hello #{name}"\nend',
- },
- {
- name: 'HTML scripts and styles',
- lang: 'html',
- code: '<style>.item { color: red; }</style>\n<script>const greeting = "hello"</script>',
- },
- {
- name: 'Markdown frontmatter, raw HTML, and fenced aliases',
- lang: 'markdown',
- code: [
- '---',
- 'title: "Greeting"',
- 'published: true',
- '---',
- '# Heading',
- '<div class="item">Hi</div>',
- '',
- '```ts',
- 'const value: number = 42',
- '```',
- '',
- '```sh',
- 'echo "hello ${USER}"',
- '```',
- ].join('\n'),
- },
- {
- name: 'MDX frontmatter, JSX, and fenced SQL',
- lang: 'mdx',
- code: '---\ntitle: "Greeting"\n---\nimport Component from "./component"\n\n<Component value={42} />\n\n```sql\nselect 42;\n```',
- },
- {
- name: 'Vue TypeScript and SCSS',
- lang: 'vue',
- code: '<template><div>{{ greeting }}</div></template>\n<script setup lang="ts">const greeting: string = "hello"</script>\n<style lang="scss">.item { &.active { color: red; } }</style>',
- },
- {
- name: 'Astro frontmatter and SCSS',
- lang: 'astro',
- code: '---\nconst title: string = "Hello"\n---\n<h1>{title}</h1>\n<style lang="scss">h1 { color: red; }</style>',
- },
- { name: 'empty code', lang: 'typescript', code: '' },
- { name: 'plain text', lang: null, code: 'plain <text> & punctuation\n second line' },
- {
- name: 'JavaScript tagged template injections',
- lang: 'javascript',
- code: 'const result = sql`select * from users where id = 42`\nconst style = css`div { color: red; }`\nconst markup = html`<div class="item">Hi</div>`',
- },
- {
- name: 'JSX tagged template injections',
- lang: 'jsx',
- code: 'const style = css`div { color: red; }`\nconst element = <div>{style}</div>',
- },
- {
- name: 'Markdown Vue and Angular injections',
- lang: 'markdown',
- code: '<div v-if="active">{{ name }}</div>\n\n@if (active) { <p>Hello</p> }\n\n```vue\n<template><p>{{ name }}</p></template>\n```',
- },
- {
- name: 'HTML embedded tagged templates',
- lang: 'html',
- code: '<script>const result = sql`select 42`</script>',
- },
-]
-
-describe('selective code block highlighting', () => {
- let baseline: Awaited<ReturnType<typeof createHighlighter>>
- let createActualHighlighter: typeof createHighlighter
- const create = vi.mocked(createHighlighter)
-
- beforeAll(async () => {
- const actual = await vi.importActual<typeof import('shiki')>('shiki')
- createActualHighlighter = actual.createHighlighter
- baseline = await createActualHighlighter({
- themes: [structuredClone(theme)],
- langs: Object.keys(bundledLanguages),
- })
- })
-
+const result = {
+ tokens: [[{ content: 'select', offset: 0, color: 'var(--code-token-keyword)', fontStyle: 1 }]],
+}
+const highlighter = {
+ codeToTokens: vi.fn<Highlighter['codeToTokens']>(),
+ loadLanguage: vi.fn(),
+ loadTheme: vi.fn(),
+}
+const create = vi.mocked(createHighlighter, { partial: true })
+
+describe('shared code block highlighting', () => {
beforeEach(() => {
vi.resetModules()
- create.mockReset().mockImplementation(createActualHighlighter)
- })
-
- afterEach(async () => {
- for (const result of create.mock.results) {
- if (result.type === 'return') {
- await result.value.then(
- (highlighter) => highlighter.dispose(),
- () => {}
- )
- }
- }
- vi.restoreAllMocks()
+ vi.resetAllMocks()
+ create.mockResolvedValue(highlighter)
+ highlighter.codeToTokens.mockReturnValue(result)
})
- afterAll(() => baseline.dispose())
-
- function expected({ code, lang }: (typeof fixtures)[number]) {
- return baseline.codeToTokens(code, {
- lang: lang || undefined,
- theme: 'Supabase Theme',
- tokenizeTimeLimit: 0,
- tokenizeMaxLineLength: 100_000,
- }).tokens
- }
-
- it('defers initialization until first use and reuses the theme and highlighter', async () => {
+ it('initializes all languages once and never reloads languages or themes between blocks', async () => {
const { highlightCode } = await import('./CodeBlock.highlight')
expect(create).not.toHaveBeenCalled()
- const first = fixtures[0]
- expect((await highlightCode(first.code, first.lang)).tokens).toEqual(expected(first))
- expect(create).toHaveBeenCalledTimes(1)
- const highlighter = await create.mock.results[0].value
- expect(highlighter.getLoadedLanguages()).toContain('bash')
- expect(highlighter.getLoadedLanguages()).not.toContain('sql')
- expect(highlighter.getLoadedLanguages()).not.toContain('markdown')
- expect(highlighter.getLoadedLanguages()).not.toContain('typescript')
-
- const loadLanguage = vi.spyOn(highlighter, 'loadLanguage')
- const loadTheme = vi.spyOn(highlighter, 'loadTheme')
- const second = fixtures.find(({ lang }) => lang === 'sql')!
- await highlightCode(second.code, second.lang)
- expect((await highlightCode(first.code, first.lang)).tokens).toEqual(expected(first))
- expect(create).toHaveBeenCalledTimes(1)
- expect(highlighter.getLoadedLanguages()).toContain('sql')
- expect(loadLanguage.mock.calls.filter((args) => args.length)).toEqual([['sql']])
- expect(loadTheme.mock.calls.every((args) => args.length === 0)).toBe(true)
- expect(highlighter.getLoadedThemes()).toEqual(['Supabase Theme'])
- })
+ await highlightCode('echo hello', 'bash')
+ await highlightCode('select 42', 'sql')
+ await highlightCode('echo again', 'shell')
- it('shares initialization across concurrent languages and aliases', async () => {
- const { highlightCode } = await import('./CodeBlock.highlight')
- const selected = [fixtures[0], fixtures[0], fixtures[1], fixtures[6]]
- const results = await Promise.all(selected.map(({ code, lang }) => highlightCode(code, lang)))
- expect(results.map(({ tokens }) => tokens)).toEqual(selected.map(expected))
- expect(create).toHaveBeenCalledTimes(1)
+ expect(create).toHaveBeenCalledExactlyOnceWith({
+ themes: [theme],
+ langs: Object.keys(bundledLanguages),
+ })
+ expect(create.mock.calls[0][0].themes?.[0]).not.toBe(theme)
+ expect(highlighter.loadLanguage).not.toHaveBeenCalled()
+ expect(highlighter.loadTheme).not.toHaveBeenCalled()
})
- it.each(fixtures)(
- 'matches eager token colors, font flags, and offsets for $name',
- async (fixture) => {
+ it.each(['javascript', 'js', null] as const)(
+ 'forwards the source and options for %s and returns the tokens unchanged',
+ async (lang) => {
const { highlightCode } = await import('./CodeBlock.highlight')
- const result = await highlightCode(fixture.code, fixture.lang)
- expect(result.tokens).toEqual(expected(fixture))
+ expect(await highlightCode('const value = 42', lang)).toBe(result)
+ expect(highlighter.codeToTokens).toHaveBeenCalledExactlyOnceWith('const value = 42', {
+ lang: lang ?? undefined,
+ theme: 'Supabase Theme',
+ tokenizeTimeLimit: 0,
+ tokenizeMaxLineLength: 100_000,
+ })
}
)
- it('keeps embedded tokens and CSS-variable colors stable across rendering order', async () => {
- const { highlightCode } = await import('./CodeBlock.highlight')
- const selected = fixtures.filter(({ lang }) =>
- ['markdown', 'vue', 'html', 'typescript'].includes(lang || '')
- )
- const first = await Promise.all(selected.map(({ code, lang }) => highlightCode(code, lang)))
- const reversed = await Promise.all(
- [...selected].reverse().map(({ code, lang }) => highlightCode(code, lang))
- )
- expect(first.map(({ tokens }) => tokens)).toEqual(selected.map(expected))
- expect(reversed.reverse().map(({ tokens }) => tokens)).toEqual(
- first.map(({ tokens }) => tokens)
- )
- const colors = first.flatMap(({ tokens }) => tokens.flat().map(({ color }) => color))
- expect(colors).toContain('var(--code-token-keyword)')
- expect(colors.every((color) => !color || color.startsWith('var(--'))).toBe(true)
- })
-
- it('surfaces supported grammar loading failures', async () => {
+ it('shares pending initialization across concurrent languages and aliases', async () => {
+ const { promise, resolve } = Promise.withResolvers<typeof highlighter>()
+ create.mockReturnValue(promise)
const { highlightCode } = await import('./CodeBlock.highlight')
- await highlightCode('echo hello', 'bash')
- const highlighter = await create.mock.results[0].value
- const failure = new Error('Grammar could not be loaded')
- vi.spyOn(highlighter, 'loadLanguage').mockImplementation(async (...languages) => {
- if (languages.length) throw failure
- })
- await expect(highlightCode('select 42', 'sql')).rejects.toBe(failure)
+ const pending = [
+ highlightCode('echo hello', 'bash'),
+ highlightCode('echo again', 'shell'),
+ highlightCode('select 42', 'sql'),
+ ]
expect(create).toHaveBeenCalledTimes(1)
+ expect(highlighter.codeToTokens).not.toHaveBeenCalled()
+
+ resolve(highlighter)
+ expect(await Promise.all(pending)).toEqual([result, result, result])
+ expect(highlighter.codeToTokens).toHaveBeenCalledTimes(3)
})
- it('retains native singleton initialization failure without adding retries', async () => {
+ it('retains initialization failures without adding retries', async () => {
const failure = new Error('Highlighter could not be initialized')
create.mockRejectedValue(failure)
const { highlightCode } = await import('./CodeBlock.highlight')
+
await expect(highlightCode('echo hello', 'bash')).rejects.toBe(failure)
await expect(highlightCode('select 42', 'sql')).rejects.toBe(failure)
expect(create).toHaveBeenCalledTimes(1)
+ expect(highlighter.codeToTokens).not.toHaveBeenCalled()
})
})
diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts
index bf287d629cc..4081a001568 100644
--- a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts
+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts
@@ -1,49 +1,15 @@
-import {
- bundledLanguages,
- createHighlighter,
- makeSingletonHighlighter,
- type BundledLanguage,
-} from 'shiki'
+import { bundledLanguages, createHighlighter, type BundledLanguage } from 'shiki'
import theme from './supabase-2.json' with { type: 'json' }
-const getHighlighter = makeSingletonHighlighter(() =>
- createHighlighter({ themes: [structuredClone(theme)], langs: [] })
-)
-
-// keep the eager highlighter's tagged templates and component syntax intact
-const INJECTED_LANGUAGES: Record<string, Array<BundledLanguage>> = {
- 'source.js': ['ts-tags'],
- 'source.ts': ['ts-tags'],
- 'text.html.markdown': ['vue'],
- 'text.html.derivative': ['angular-html', 'vue'],
- 'text.pug': ['vue'],
-}
+let highlighterPromise: ReturnType<typeof createHighlighter> | undefined
export async function highlightCode(code: string, lang: BundledLanguage | null) {
- const highlighter = await getHighlighter()
- if (lang && !highlighter.getLoadedLanguages().includes(lang)) {
- const languages = new Set<BundledLanguage>()
-
- async function collectLanguages(language: BundledLanguage) {
- if (languages.has(language)) return
- languages.add(language)
- const { default: grammars } = await bundledLanguages[language]()
- await Promise.all(
- grammars.flatMap(({ embeddedLangsLazy = [], scopeName }) => {
- const injected = Object.entries(INJECTED_LANGUAGES).flatMap(([scope, languages]) =>
- scopeName === scope || scopeName.startsWith(`${scope}.`) ? languages : []
- )
- return [...embeddedLangsLazy, ...injected].map((embedded) =>
- collectLanguages(embedded as BundledLanguage)
- )
- })
- )
- }
-
- await collectLanguages(lang)
- await highlighter.loadLanguage(...languages)
- }
+ // init all grammars once so later blocks stay fast
+ const highlighter = await (highlighterPromise ??= createHighlighter({
+ themes: [structuredClone(theme)],
+ langs: Object.keys(bundledLanguages),
+ }))
return highlighter.codeToTokens(code, {
lang: lang || undefined,
diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx
index 715db31e754..22d4df75829 100644
--- a/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx
+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx
@@ -1,18 +1,17 @@
-import { readFile } from 'node:fs/promises'
import { load } from 'cheerio'
import { type ComponentProps, type PropsWithChildren } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
-import { createHighlighter, type BundledLanguage, type ThemeRegistration } from 'shiki'
-import { createTwoslasher } from 'twoslash'
-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CodeBlock } from './CodeBlock'
import { type CodeToken } from './CodeBlock.client'
-import { getTokenClassName } from './CodeBlock.utils'
+import { highlightCode } from './CodeBlock.highlight'
-vi.mock('./types/lib.deno.d.ts.include', async () => ({
- default: await readFile(new URL('./types/lib.deno.d.ts.include', import.meta.url), 'utf8'),
-}))
+const { twoslasher } = vi.hoisted(() => ({ twoslasher: vi.fn() }))
+
+vi.mock('./CodeBlock.highlight', () => ({ highlightCode: vi.fn() }))
+vi.mock('twoslash', () => ({ createTwoslasher: () => twoslasher }))
+vi.mock('./types/lib.deno.d.ts.include', () => ({ default: '' }))
// Keep the real token renderer while isolating unrelated UI imports and tooltip portals.
vi.mock('ui', async () => {
@@ -32,134 +31,124 @@ function getLines(block: Awaited<ReturnType<typeof CodeBlock>>): Array<Array<Cod
return block.props.children[0].props.children.props.lines
}
-const fixtures: Array<{ name: string; lang?: string; code: string }> = [
- {
- name: 'JavaScript',
- lang: 'javascript',
- code: '// A greeting\nconst greeting = "hello"\ngreeting',
- },
- {
- name: 'TypeScript',
- lang: 'typescript',
- code: 'const count: number = 42\nconst values = [count]',
- },
- { name: 'SQL', lang: 'sql', code: "select 'hello' as greeting, 42 as count;\n-- A comment" },
- { name: 'shell', lang: 'shell', code: 'echo "hello ${USER}"\n# A comment' },
- { name: 'JSON', lang: 'json', code: '{\n "greeting": "hello",\n "count": 42\n}' },
- { name: 'empty code', lang: 'typescript', code: '' },
- { name: 'plain text', code: 'plain <text> & punctuation\n second line' },
- { name: 'unsupported language', lang: 'not-a-language', code: 'plain <text> & punctuation' },
-]
-
describe('code block serialization and rendering', () => {
- let highlighter: Awaited<ReturnType<typeof createHighlighter>>
-
- beforeAll(async () => {
- // Shiki mutates theme.colors, so use a fresh raw theme for this independent tokenization.
- const theme: ThemeRegistration = JSON.parse(
- await readFile(new URL('./supabase-2.json', import.meta.url), 'utf8')
- )
- highlighter = await createHighlighter({
- themes: [theme],
- langs: ['javascript', 'typescript', 'sql', 'shell', 'json'],
- })
+ const highlight = vi.mocked(highlightCode, { partial: true })
+
+ beforeEach(() => {
+ highlight.mockReset().mockImplementation(async (code) => ({
+ tokens: code
+ .split('\n')
+ .map((content) =>
+ content ? [{ content, offset: 0, color: 'var(--code-foreground)' }] : []
+ ),
+ }))
+ twoslasher.mockReset().mockImplementation((code: string) => ({ code, nodes: [] }))
})
- afterEach(() => vi.restoreAllMocks())
- afterAll(() => highlighter.dispose())
-
- it.each(fixtures)(
- 'preserves $name token boundaries using compact namespaced classes',
- async ({ lang, code }) => {
- const block = await CodeBlock({
- contents: code,
- lang,
- skipTypeGeneration: true,
- hideControls: true,
- })
- const lines = getLines(block)
- const { tokens } = highlighter.codeToTokens(code, {
- lang: lang === 'not-a-language' ? undefined : (lang as BundledLanguage | undefined),
- theme: 'Supabase Theme',
- tokenizeTimeLimit: 0,
- tokenizeMaxLineLength: 100_000,
- })
-
- expect(lines.map((line) => line.map(([content]) => content))).toEqual(
- tokens.map((line) => line.map(({ content }) => content))
- )
- for (const [lineIndex, line] of tokens.entries()) {
- for (const [tokenIndex, token] of line.entries()) {
- expect(lines[lineIndex][tokenIndex]).toEqual([
- token.content,
- getTokenClassName(token.color, token.fontStyle),
- ])
- }
- }
+ it('serializes compact classes and renders numbered, escaped source without inline styles', async () => {
+ const code = "const text = '<hello> & world'\n// note"
+ highlight.mockResolvedValueOnce({
+ tokens: [
+ [
+ { content: 'const ', offset: 0, color: 'var(--code-token-keyword)' },
+ { content: "text = '<hello> & world'", offset: 6, color: 'var(--code-token-string)' },
+ ],
+ [{ content: '// note', offset: 31, color: 'var(--code-token-comment)', fontStyle: 1 }],
+ ],
+ })
+ const block = await CodeBlock({
+ contents: code,
+ lang: 'javascript',
+ skipTypeGeneration: true,
+ hideControls: true,
+ })
- const $ = load(renderToStaticMarkup(block))
- expect(
- $('.code-line-number')
- .toArray()
- .map((element) => $(element).text())
- ).toEqual(lines.map((_, index) => String(index + 1)))
- expect(
- $('.code-line-content')
- .toArray()
- .map((element) => $(element).text())
- ).toEqual(lines.map((line) => line.map(([content]) => content).join('')))
- expect($('.code-content [style]')).toHaveLength(0)
- }
- )
+ expect(twoslasher).not.toHaveBeenCalled()
+ expect(getLines(block)).toEqual([
+ [
+ ['const ', 's-k'],
+ ["text = '<hello> & world'", 's-s'],
+ ],
+ [['// note', 's-c s-i']],
+ ])
+ const $ = load(renderToStaticMarkup(block))
+ expect(
+ $('.code-line-number')
+ .toArray()
+ .map((element) => $(element).text())
+ ).toEqual(['1', '2'])
+ expect(
+ $('.code-line-content')
+ .toArray()
+ .map((element) => $(element).text())
+ ).toEqual(code.split('\n'))
+ expect($('.code-content .s-k').text()).toBe('const ')
+ expect($('.code-content .s-c.s-i').text()).toBe('// note')
+ expect($('.code-content [style]')).toHaveLength(0)
+ })
- it('preserves actual Twoslash annotations and offsets after its source edits', async () => {
- const source = [
- "const prefix = 'Hello'",
- '// ---cut---',
- '/** The name shown in the greeting. */',
- "const username = 'reader'",
- 'const message = `${prefix}, ${username}`',
- 'message',
- ].join('\n')
- const twoslashed = createTwoslasher({ compilerOptions: { ignoreDeprecations: '6.0' } })(source)
- const hovers = twoslashed.nodes.filter((node) => node.type === 'hover')
- expect(hovers.length).toBeGreaterThan(0)
- expect(twoslashed.code).not.toContain('// ---cut---')
+ it.each([
+ { name: 'plain text', lang: undefined, code: 'plain <text> & punctuation', expectedLang: null },
+ {
+ name: 'unsupported language',
+ lang: 'not-a-language',
+ code: 'plain text',
+ expectedLang: null,
+ },
+ { name: 'empty code', lang: 'typescript', code: '', expectedLang: 'typescript' },
+ { name: 'language alias', lang: 'ts', code: 'const count = 42', expectedLang: 'ts' },
+ ])('handles $name', async ({ lang, code, expectedLang }) => {
+ const block = await CodeBlock({
+ contents: code,
+ lang,
+ skipTypeGeneration: true,
+ hideControls: true,
+ })
+ expect(highlight).toHaveBeenCalledWith(code, expectedLang)
+ const $ = load(renderToStaticMarkup(block))
+ expect($('.code-line-content').text()).toBe(code)
+ })
+ it('highlights edited Twoslash source and attaches hovers at the correct token offsets', async () => {
+ const source = 'const hidden = 0\n// ---cut---\nconst count = 42\ncount'
+ const edited = 'const count = 42\ncount'
+ const annotation = { text: 'const count: 42', docs: 'The current count.', tags: undefined }
+ twoslasher.mockReturnValueOnce({
+ code: edited,
+ nodes: [
+ { type: 'hover', line: 0, character: 6, ...annotation },
+ { type: 'hover', line: 1, character: 0, ...annotation },
+ ],
+ })
+ highlight.mockResolvedValueOnce({
+ tokens: [
+ [
+ { content: 'const ', offset: 0, color: 'var(--code-token-keyword)' },
+ { content: 'count', offset: 6, color: 'var(--code-token-variable)' },
+ { content: ' = 42', offset: 11 },
+ ],
+ [{ content: 'count', offset: 17, color: 'var(--code-token-variable)' }],
+ ],
+ })
const block = await CodeBlock({ contents: source, lang: 'typescript', hideControls: true })
- const lines = getLines(block)
- expect(lines.map((line) => line.map(([content]) => content).join('')).join('\n')).toBe(
- twoslashed.code
- )
- for (const [lineIndex, line] of lines.entries()) {
- let offset = 0
- for (const token of line) {
- const annotations = hovers
- .filter((hover) => hover.line === lineIndex && hover.character === offset)
- .map(({ text, docs, tags }) => ({ text, docs, tags }))
- expect(token[2]).toEqual(annotations.length ? annotations : undefined)
- expect(token).toHaveLength(annotations.length ? 3 : 2)
- offset += token[0].length
- }
- }
- const annotated = lines.flat().filter((token) => token[2])
- expect(annotated.length).toBeGreaterThan(0)
+ expect(twoslasher).toHaveBeenCalledWith(source)
+ expect(highlight).toHaveBeenCalledWith(edited, 'typescript')
+ expect(getLines(block)).toEqual([
+ [
+ ['const ', 's-k'],
+ ['count', 's-v', [annotation]],
+ [' = 42', undefined],
+ ],
+ [['count', 's-v', [annotation]]],
+ ])
const $ = load(renderToStaticMarkup(block))
expect(
$('.code-content button')
.toArray()
.map((element) => $(element).text())
- ).toEqual(annotated.map(([content]) => content))
- expect($('.code-content button[tabindex="0"]')).toHaveLength(annotated.length)
- })
-
- it('keeps classes stable across repeated renders in a different order', async () => {
- const render = async ({ lang, code }: (typeof fixtures)[number]) =>
- getLines(await CodeBlock({ contents: code, lang, skipTypeGeneration: true }))
- const first = await Promise.all(fixtures.map(render))
- const reversed = await Promise.all([...fixtures].reverse().map(render))
- expect(reversed.reverse()).toEqual(first)
+ ).toEqual(['count', 'count'])
+ expect($('.code-content button[tabindex="0"]')).toHaveLength(2)
})
it('retains unnumbered layout, source text, hidden controls, and the accessible label', async () => {
@@ -172,7 +161,6 @@ describe('code block serialization and rendering', () => {
})
const $ = load(renderToStaticMarkup(block))
expect($('.code-line-number')).toHaveLength(0)
- expect($('.code-content')).toHaveLength(1)
expect(
$('.code-content > span')
.toArray()