Skip to content

Commit

Permalink
Add fallback language support for lazy loading in rehype-shiki; updat…
Browse files Browse the repository at this point in the history
…e tests and documentation.
  • Loading branch information
liuyan committed Oct 29, 2024
1 parent c08a332 commit c9646ab
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions packages/rehype/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { Root } from 'hast'
import type { Transformer } from 'unified'
import type { RehypeShikiHandler } from './handlers'
import type { RehypeShikiCoreOptions } from './types'
import { bundledLanguages } from 'shiki'
import { isSpecialLang } from 'shiki/core'
import { visit } from 'unist-util-visit'
import { InlineCodeHandlers, PreHandler } from './handlers'
Expand Down Expand Up @@ -97,6 +98,9 @@ function rehypeShikiFromHighlighter(
return lang

if (lazy) {
if (fallbackLanguage && !(Object.keys(bundledLanguages) as string[]).includes(lang)) {
lang = fallbackLanguage as string
}
languageQueue.push(lang)
return lang
}
Expand Down
1 change: 0 additions & 1 deletion packages/rehype/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export interface RehypeShikiExtraOptions {
/**
* The fallback language to use when specified language is not loaded
*
* Ignored if `lazy` is enabled
*/
fallbackLanguage?: string

Expand Down
24 changes: 24 additions & 0 deletions packages/rehype/test/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,30 @@ it('run with lazy', async () => {
expect(file.toString()).toMatchFileSnapshot('./fixtures/a.core.out.html')
})

it('run with lazy and fallback', async () => {
const highlighter = await createHighlighter({
themes: [
'vitesse-light',
],
langs: [],
})

const file = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeShikiFromHighlighter, highlighter, {
lazy: true,
theme: 'vitesse-light',
fallbackLanguage: 'text',
transformers: [
transformerMetaHighlight(),
],
})
.use(rehypeStringify)
.process(await fs.readFile(new URL('./fixtures/d.md', import.meta.url)))

expect(file.toString()).toMatchFileSnapshot('./fixtures/d.core.out.html')
})
it('run with rehype-raw', async () => {
const highlighter = await createHighlighter({
themes: [
Expand Down
1 change: 1 addition & 0 deletions packages/rehype/test/fixtures/d.core.out.html

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/rehype/test/fixtures/d.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c9646ab

Please sign in to comment.