Open arvinxx opened 3 days ago
Hmm I'm not quite sure what does the logic in initHighlighter
do. Normally to lazy load required languages, we use async highlighter.loadLanguage
function in advanced of codeToHast
/codeToHtml
.
Here's my example tested in CodeSandbox:
"use client";
import { useEffect, useState } from "react";
import { BundledLanguage, createHighlighter } from "shiki";
const snippets = [
{
lang: "ts",
code: `export const hello: string = "Hello"`,
},
{
lang: "java",
code: `System.out.println("Hello")`,
},
{
lang: "py",
code: `print(f"Hello")`,
},
];
export default function Page() {
return <div>{snippets.map(item => <Highlight key={item.lang} {...item} />)}</div>;
}
const highlighter = createHighlighter({
langs: ["ts"], // preload language
themes: ["vitesse-dark"],
});
function Highlight({ code, lang }: { code: string; lang: string }) {
const [html, setHtml] = useState<string>();
useEffect(() => {
// TEST: do it on browser only
async function run() {
const instance = await highlighter;
if (!instance.getLoadedLanguages().includes(lang)) {
console.log('load', lang)
// the language may not exist, we assume it is always valid
await instance.loadLanguage(lang as BundledLanguage);
}
setHtml(instance.codeToHtml(code, {
lang,
theme: 'vitesse-dark'
}))
}
void run()
}, [code, lang]);
if (!html) return null
return <div dangerouslySetInnerHTML={{ __html: html }} />
}
Notice that the function codeToHast
/codeToHtml
exported from shiki
does lazy load by default, this is only required for highlighter API.
As you are using React, I would suggest you to check https://shiki.style/packages/next#custom-components, which illustrates the way to render JSX instead of HTML with Shiki.
Shiki v1.18 does not introduce any functionality changes (https://github.com/shikijs/shiki/compare/v1.17.7...v1.18.0). The only thing notable is https://github.com/shikijs/shiki/pull/781 - which seems not related to your case.
The example and repo has too much React related logic for me to take a look, can you provide a minimal reproduction instead?
Validations
Describe the bug
Thank you for bring this amazing work! LobeChat have this beautiful code highlight all credit to you~
But it seems there is a breaking change for 1.18.0 which case the code highlight invalid.
So I pin to 1.17.7 temporarily with the PR to fix it.
Our usage code is:
and the code in
useHighlight
is:the source is here: https://github.com/lobehub/lobe-ui/blob/master/src/hooks/useHighlight.ts#L41
I dig it a little and find that the dom seems different:
v1.17.7 's dom:
but in the v1.18.0's dom:
it means that in the v1.18.0 the control flow is go to the condition of `isLoading || !data ? ( <div className={cx(styles.unshiki, className)} style={style}>
and then I try to log the error, and it show up with:
Why it's worked in v1.17.7 but breaking in the 1.18.0 ?
Reproduction
https://github.com/lobehub/lobe-chat/tree/reproduction/shiki-1.18.0
Contributes