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(highlight): warn about languages dynamic loading #1291

Merged
merged 4 commits into from
Jun 27, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 18 additions & 6 deletions src/runtime/server/api/highlight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ const resolveBody = (body: Partial<HighlightParams>) => {
// Remove trailing carriage returns
code: body.code.replace(/\n+$/, ''),
// Resolve lang & theme (i.e check if shiki supports them)
lang: resolveLang(body.lang),
theme: resolveTheme(body.theme)
lang: resolveLang(body.lang || ''),
theme: resolveTheme(body.theme || '')
}
}

Expand Down Expand Up @@ -87,7 +87,14 @@ export default defineLazyEventHandler(async () => {

// Load supported language on-demand
if (!highlighter.getLoadedLanguages().includes(lang)) {
await highlighter.loadLanguage(lang)
// eslint-disable-next-line no-console
console.warn(`[Nuxt] [Content] Language "${lang}" is not loaded Shiki. Falling back to plain code.`)
Tahul marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line no-console
console.warn(`[Nuxt] [Content] Please make sure you add "${lang}" to the 'preload' list in your Nuxt config. See https://content.nuxtjs.org/api/configuration#highlight`)
Tahul marked this conversation as resolved.
Show resolved Hide resolved
// TODO: Enable autoloading of language when upstream Shiki supports it\
// See: https://github.com/nuxt/content/issues/1225#issuecomment-1148786924
// await highlighter.loadLanguage(lang)
return [[{ content: code }]]
}

// Load supported theme on-demand
Expand Down Expand Up @@ -119,15 +126,20 @@ export default defineLazyEventHandler(async () => {
key: color.key,
tokens: color.tokens[line]
})
}, coloredTokens[0].tokens[line])
}, coloredTokens[0].tokens[line] as HighlightThemedToken[])
}

return highlightedCode
}
})

function mergeLines (line1, line2) {
const mergedTokens = []
interface HighlightThemedTokenLine {
key: string
tokens: HighlightThemedToken[]
}

function mergeLines (line1: HighlightThemedTokenLine, line2: HighlightThemedTokenLine) {
const mergedTokens: HighlightThemedToken[] = []
const getColors = (h, i) => typeof h.tokens[i].color === 'string' ? { [h.key]: h.tokens[i].color } : h.tokens[i].color

const [big, small] = line1.tokens.length > line2.tokens.length ? [line1, line2] : [line2, line1]
Expand Down