Skip to content

Commit

Permalink
fix(error-handling): Add error handling for unsupported/unbundled lan…
Browse files Browse the repository at this point in the history
…guages
  • Loading branch information
AVGVSTVS96 committed Jul 28, 2024
1 parent f85bda7 commit 602021e
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions src/lib/hooks/useShiki.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useState, useEffect, type ReactNode } from 'react';
import { codeToHtml, type BundledLanguage, type BundledTheme } from 'shiki';
import {
codeToHtml,
type BundledLanguage,
type BundledTheme,
} from 'shiki';
import parse from 'html-react-parser';
import { removeTabIndexFromPre } from '@/lib/utils';

Expand All @@ -13,14 +17,25 @@ export const useShikiHighlighter = (
);

useEffect(() => {
codeToHtml(code,
{
lang: lang as BundledLanguage,
theme,
transformers: [removeTabIndexFromPre]
}).then((html) => {
setHighlightedCode(parse(html));
});
const highlightCode = async () => {
try {
const html = await codeToHtml(code, {
lang: lang as BundledLanguage,
theme,
transformers: [removeTabIndexFromPre],
});
setHighlightedCode(parse(html));
} catch (error) {
const fallbackHtml = await codeToHtml(code, {
lang: 'plaintext',
theme,
transformers: [removeTabIndexFromPre],
});
setHighlightedCode(parse(fallbackHtml));
}
};

highlightCode();
}, [code]);

return highlightedCode;
Expand Down

0 comments on commit 602021e

Please sign in to comment.