Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rehype): improve lazy performance #896

Merged
merged 1 commit into from
Jan 20, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 30 additions & 29 deletions packages/rehype/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,24 +86,7 @@ function rehypeShikiFromHighlighter(

return (tree) => {
// use this queue if lazy is enabled
const languageQueue: string[] = []
const queue: (() => void)[] = []

function getLanguage(lang: string | undefined): string | undefined {
if (!lang)
return defaultLanguage

if (highlighter.getLoadedLanguages().includes(lang) || isSpecialLang(lang))
return lang

if (lazy) {
languageQueue.push(lang)
return lang
}

if (fallbackLanguage)
return fallbackLanguage
}
const queue: Promise<void>[] = []

visit(tree, 'element', (node, index, parent) => {
let handler: RehypeShikiHandler | undefined
Expand All @@ -127,7 +110,23 @@ function rehypeShikiFromHighlighter(
if (!res)
return

const lang = getLanguage(res.lang)
let lang: string | undefined
let lazyLoad = false

if (!res.lang) {
lang = defaultLanguage
}
else if (highlighter.getLoadedLanguages().includes(res.lang) || isSpecialLang(res.lang)) {
lang = res.lang
}
else if (lazy) {
lazyLoad = true
lang = res.lang
}
else if (fallbackLanguage) {
lang = fallbackLanguage
}

if (!lang)
return

Expand All @@ -145,24 +144,26 @@ function rehypeShikiFromHighlighter(
}
}

parent.children.splice(index, 1, ...fragment.children)
parent.children[index] = fragment as any
}

if (lazy)
queue.push(processNode)
else
if (lazyLoad) {
queue.push(highlighter.loadLanguage(lang).then(() => processNode()))
}
else {
processNode()
}

// don't visit processed nodes
return 'skip'
})

if (lazy) {
return highlighter
.loadLanguage(...languageQueue)
.then(() => {
queue.forEach(fn => fn())
})
if (queue.length > 0) {
async function run(): Promise<void> {
await Promise.all(queue)
}

return run()
}
}
}
Expand Down
Loading